tunes 1.1.0

A music composition, synthesis, and audio generation library
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! Convolution reverb using FFT-based overlap-add algorithm
//!
//! Convolution reverb applies the acoustic characteristics of a real space
//! to your audio by convolving it with an impulse response (IR).
//!
//! # How It Works
//!
//! 1. **Impulse Response (IR)**: A recording or simulation of how a space responds to sound
//! 2. **Convolution**: Mathematically applies that response to your audio
//! 3. **FFT Optimization**: Uses FFT to make convolution fast enough for real-time
//!
//! # Usage
//!
//! ```no_run
//! use tunes::synthesis::effects::{Convolution, convolution};
//!
//! // From preset (synthetic IR generated on-the-fly)
//! let reverb = convolution::presets::cathedral(0.5)?;
//!
//! // From file (real recorded IR)
//! let reverb = Convolution::from_file("cathedral.wav", 0.5)?;
//!
//! // Custom parameters
//! use tunes::synthesis::effects::IRParams;
//! let reverb = Convolution::from_params(IRParams::cathedral(), 0.5)?;
//! # Ok::<(), anyhow::Error>(())
//! ```

use crate::error::{Result, TunesError};
use crate::synthesis::sample::Sample;
use crate::track::PRIORITY_SPATIAL;
use rustfft::num_complex::Complex;
use rustfft::{Fft, FftPlanner};
use std::collections::VecDeque;
use std::sync::Arc;
#[cfg(feature = "gpu")]
use std::sync::Mutex;

#[cfg(feature = "gpu")]
use crate::gpu::{GpuConvolution, GpuDevice};

/// Convolution reverb effect using FFT-based processing
///
/// Applies the acoustic characteristics of a space to audio through convolution.
/// Uses overlap-add FFT algorithm for efficient real-time processing.
///
/// When the `gpu` feature is enabled, convolution can be accelerated on the GPU
/// for significant speedups (5-50x faster than CPU).
#[derive(Clone)]
pub struct ConvolutionReverb {
    /// Pre-computed impulse response in frequency domain
    ir_fft: Vec<Complex<f32>>,

    /// FFT size (power of 2, large enough for IR + block)
    fft_size: usize,

    /// Processing block size (samples per FFT block)
    block_size: usize,

    /// Hop size for overlap-add (typically block_size / 2)
    hop_size: usize,

    /// Input accumulation buffer
    input_buffer: Vec<f32>,

    /// Output buffer (stores processed samples)
    output_buffer: VecDeque<f32>,

    /// Overlap buffer for overlap-add algorithm
    overlap_buffer: Vec<f32>,

    /// Pre-allocated FFT working buffer (reused, avoids allocation per block)
    fft_working_buffer: Vec<Complex<f32>>,

    /// Forward FFT planner (CPU fallback)
    fft: Arc<dyn Fft<f32>>,

    /// Inverse FFT planner (CPU fallback)
    ifft: Arc<dyn Fft<f32>>,

    /// GPU convolution processor (when enabled)
    #[cfg(feature = "gpu")]
    gpu_convolution: Option<Arc<Mutex<GpuConvolution>>>,

    /// Wet/dry mix (0.0 = dry, 1.0 = wet)
    pub mix: f32,

    /// Processing priority (lower = earlier in signal chain)
    pub priority: u8,

    /// Sample counter for processing state
    sample_count: u64,

    /// GPU enabled flag
    gpu_enabled: bool,
}

impl ConvolutionReverb {
    /// Create convolution reverb from impulse response samples
    ///
    /// # Arguments
    /// * `ir` - Impulse response samples (mono)
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    /// * `block_size` - FFT block size (None = auto-select based on IR length)
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::synthesis::effects::ConvolutionReverb;
    /// let ir = vec![1.0, 0.5, 0.25, 0.1];  // Simple IR
    /// let reverb = ConvolutionReverb::from_samples(&ir, 0.5, None)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn from_samples(ir: &[f32], mix: f32, block_size: Option<usize>) -> Result<Self> {
        if ir.is_empty() {
            return Err(TunesError::AudioEngineError(
                "Impulse response cannot be empty".to_string(),
            ));
        }

        // Auto-select block size based on IR length
        let block_size = block_size.unwrap_or({
            if ir.len() < 4096 {
                2048
            } else if ir.len() < 16384 {
                4096
            } else {
                8192
            }
        });

        // FFT size must be large enough for IR + block (use next power of 2)
        let fft_size = (ir.len() + block_size).next_power_of_two();

        // Create FFT planners
        let mut planner = FftPlanner::new();
        let fft = planner.plan_fft_forward(fft_size);
        let ifft = planner.plan_fft_inverse(fft_size);

        // Pre-compute IR FFT (do this once at creation)
        let ir_fft = {
            let mut ir_complex = vec![Complex::new(0.0, 0.0); fft_size];

            // Copy IR samples to complex buffer
            for (i, &sample) in ir.iter().enumerate() {
                ir_complex[i] = Complex::new(sample, 0.0);
            }

            // Transform to frequency domain
            fft.process(&mut ir_complex);
            ir_complex
        };

        Ok(Self {
            ir_fft,
            fft_size,
            block_size,
            hop_size: block_size / 2,
            input_buffer: Vec::with_capacity(block_size),
            output_buffer: VecDeque::with_capacity(fft_size),
            overlap_buffer: vec![0.0; fft_size],
            fft_working_buffer: vec![Complex::new(0.0, 0.0); fft_size], // Pre-allocated
            fft,
            ifft,
            #[cfg(feature = "gpu")]
            gpu_convolution: None,
            mix: mix.clamp(0.0, 1.0),
            priority: PRIORITY_SPATIAL, // Convolution reverb typically comes last
            sample_count: 0,
            gpu_enabled: false,
        })
    }

    /// Create convolution reverb from IR file
    ///
    /// Loads a WAV file containing an impulse response and creates a convolution reverb.
    ///
    /// # Arguments
    /// * `ir_path` - Path to impulse response WAV file
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    /// * `block_size` - Optional FFT block size
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::synthesis::effects::ConvolutionReverb;
    /// let reverb = ConvolutionReverb::from_ir("cathedral.wav", 0.5, None)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn from_ir(ir_path: &str, mix: f32, block_size: Option<usize>) -> Result<Self> {
        // Load IR from file
        let ir_sample = Sample::from_file(ir_path)?;

        // Convert to mono if stereo (average channels)
        let ir_mono = if ir_sample.channels == 2 {
            ir_sample
                .data
                .chunks(2)
                .map(|chunk| (chunk[0] + chunk[1]) / 2.0)
                .collect::<Vec<f32>>()
        } else {
            ir_sample.data.as_ref().clone()
        };

        Self::from_samples(&ir_mono, mix, block_size)
    }

    /// Process a single audio sample through convolution
    ///
    /// Uses overlap-add FFT convolution for efficient processing.
    ///
    /// # Arguments
    /// * `input` - Input sample
    ///
    /// # Returns
    /// Processed output sample (wet/dry mixed)
    pub fn process(&mut self, input: f32) -> f32 {
        // Accumulate input samples
        self.input_buffer.push(input);

        // Process block when we have enough samples
        if self.input_buffer.len() >= self.block_size {
            self.process_block();
        }

        // Get output sample
        let output = self.output_buffer.pop_front().unwrap_or(0.0);

        self.sample_count += 1;

        // Apply wet/dry mix
        input * (1.0 - self.mix) + output * self.mix
    }

    /// Process accumulated input block with FFT convolution
    fn process_block(&mut self) {
        // GPU path (when enabled)
        #[cfg(feature = "gpu")]
        if self.gpu_enabled {
            if let Some(ref gpu_conv) = self.gpu_convolution {
                // Collect input block
                let input_block: Vec<f32> = self
                    .input_buffer
                    .iter()
                    .take(self.block_size)
                    .copied()
                    .collect();

                // Process on GPU (lock mutex for mutable access)
                match gpu_conv
                    .lock()
                    .unwrap()
                    .process_block(&input_block, &self.overlap_buffer)
                {
                    Ok((output_samples, new_overlap)) => {
                        // Add output samples to output buffer
                        for sample in output_samples {
                            self.output_buffer.push_back(sample);
                        }

                        // Update overlap buffer
                        self.overlap_buffer = new_overlap;

                        // Clear processed samples from input buffer
                        self.input_buffer.drain(0..self.hop_size);

                        return; // GPU processing complete
                    }
                    Err(e) => {
                        eprintln!("GPU convolution error (falling back to CPU): {}", e);
                        // Fall through to CPU path
                        self.gpu_enabled = false;
                    }
                }
            }
        }

        // CPU path (fallback or when GPU disabled)
        // Reuse pre-allocated FFT working buffer (zero it first)
        for i in 0..self.fft_size {
            self.fft_working_buffer[i] = Complex::new(0.0, 0.0);
        }

        // Prepare input block
        for (i, &sample) in self.input_buffer.iter().enumerate().take(self.block_size) {
            self.fft_working_buffer[i] = Complex::new(sample, 0.0);
        }

        // FFT the input block
        self.fft.process(&mut self.fft_working_buffer);

        // Multiply in frequency domain (complex multiplication = convolution in time domain)
        for i in 0..self.fft_size {
            self.fft_working_buffer[i] *= self.ir_fft[i];
        }

        // IFFT back to time domain
        self.ifft.process(&mut self.fft_working_buffer);

        // Normalize (rustfft doesn't auto-normalize IFFT)
        let scale = 1.0 / (self.fft_size as f32);

        // Overlap-add with previous block
        for i in 0..self.fft_size {
            let sample = self.fft_working_buffer[i].re * scale;

            // Add to overlap buffer and output
            let output_sample = sample + self.overlap_buffer[i];
            self.output_buffer.push_back(output_sample);

            // Update overlap buffer for next block
            self.overlap_buffer[i] = if i < self.fft_size - self.block_size {
                self.fft_working_buffer[i + self.block_size].re * scale
            } else {
                0.0
            };
        }

        // Keep hop_size samples in input buffer for overlap
        self.input_buffer.drain(0..self.hop_size);
    }

    /// Process a block of samples at once (more efficient than sample-by-sample)
    ///
    /// # Arguments
    /// * `buffer` - Audio buffer to process in-place
    pub fn process_block_direct(&mut self, buffer: &mut [f32]) {
        for sample in buffer.iter_mut() {
            *sample = self.process(*sample);
        }
    }

    /// Reset the convolution state
    ///
    /// Clears all internal buffers. Useful when stopping/starting playback.
    pub fn reset(&mut self) {
        self.input_buffer.clear();
        self.output_buffer.clear();
        self.overlap_buffer.fill(0.0);
        self.sample_count = 0;
    }

    /// Get the wet/dry mix amount
    pub fn mix(&self) -> f32 {
        self.mix
    }

    /// Set the wet/dry mix amount
    pub fn set_mix(&mut self, mix: f32) {
        self.mix = mix.clamp(0.0, 1.0);
    }

    /// Enable GPU acceleration for convolution (requires `gpu` feature)
    ///
    /// When enabled, FFT operations are performed on the GPU using compute shaders,
    /// which can be 5-50x faster than CPU depending on GPU capabilities.
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::synthesis::effects::convolution::presets;
    /// let mut reverb = presets::cathedral(0.5)?;
    /// reverb.enable_gpu()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    #[cfg(feature = "gpu")]
    pub fn enable_gpu(&mut self) -> Result<()> {
        // Note: Partitioned convolution supports any IR size by splitting into 4096-sample chunks

        // Initialize GPU device

        use std::sync::Mutex;
        let gpu_device = GpuDevice::new().map_err(|e| {
            TunesError::AudioEngineError(format!("Failed to initialize GPU: {}", e))
        })?;

        // Create GPU convolution processor
        let gpu_conv =
            GpuConvolution::new(gpu_device, &self.ir_fft, self.fft_size, self.block_size).map_err(
                |e| {
                    TunesError::AudioEngineError(format!("Failed to create GPU convolution: {}", e))
                },
            )?;

        self.gpu_convolution = Some(Arc::new(Mutex::new(gpu_conv)));
        self.gpu_enabled = true;

        Ok(())
    }

    /// Check if GPU acceleration is enabled
    pub fn is_gpu_enabled(&self) -> bool {
        self.gpu_enabled
    }
}

impl std::fmt::Debug for ConvolutionReverb {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConvolutionReverb")
            .field("fft_size", &self.fft_size)
            .field("block_size", &self.block_size)
            .field("mix", &self.mix)
            .finish()
    }
}

/// Parameters for synthetic impulse response generation
///
/// These parameters define the characteristics of a simulated acoustic space.
#[derive(Debug, Clone)]
pub struct IRParams {
    /// Room dimensions in meters (length, width, height)
    pub room_dimensions: (f32, f32, f32),

    /// Reverb time (RT60) in seconds - time for 60dB decay
    pub rt60: f32,

    /// High frequency damping (0.0 = bright/reflective, 1.0 = dark/absorptive)
    pub damping: f32,

    /// Early reflection density (0.0 = sparse, 1.0 = dense)
    pub early_density: f32,

    /// Sample rate for IR generation
    pub sample_rate: f32,
}

impl IRParams {
    /// Small room preset (tight, intimate space)
    ///
    /// Good for: vocals, drums, close-mic'd instruments
    pub fn small_room() -> Self {
        Self {
            room_dimensions: (4.0, 5.0, 2.5),
            rt60: 0.3,
            damping: 0.6,
            early_density: 0.7,
            sample_rate: 44100.0,
        }
    }

    /// Concert hall preset (large, spacious venue)
    ///
    /// Good for: orchestral, ambient, classical music
    pub fn concert_hall() -> Self {
        Self {
            room_dimensions: (40.0, 30.0, 15.0),
            rt60: 2.5,
            damping: 0.4,
            early_density: 0.9,
            sample_rate: 44100.0,
        }
    }

    /// Cathedral preset (massive, long decay)
    ///
    /// Good for: pads, atmospheric sounds, experimental music
    pub fn cathedral() -> Self {
        Self {
            room_dimensions: (60.0, 40.0, 25.0),
            rt60: 4.5,
            damping: 0.5,
            early_density: 0.8,
            sample_rate: 44100.0,
        }
    }

    /// Plate reverb preset (vintage hardware simulation)
    ///
    /// Good for: vocals, drums, classic production
    pub fn plate() -> Self {
        Self {
            room_dimensions: (2.0, 1.5, 0.01),
            rt60: 2.0,
            damping: 0.2,
            early_density: 1.0,
            sample_rate: 44100.0,
        }
    }

    /// Spring reverb preset (vintage spring tank simulation)
    ///
    /// Good for: guitars, retro effects, surf music
    pub fn spring() -> Self {
        Self {
            room_dimensions: (0.5, 0.1, 0.1),
            rt60: 1.0,
            damping: 0.3,
            early_density: 0.6,
            sample_rate: 44100.0,
        }
    }
}

impl ConvolutionReverb {
    /// Create convolution reverb from synthetic IR parameters
    ///
    /// Generates an impulse response on-the-fly based on room characteristics.
    ///
    /// # Arguments
    /// * `params` - IR generation parameters
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::synthesis::effects::{ConvolutionReverb, IRParams};
    /// let reverb = ConvolutionReverb::from_params(IRParams::cathedral(), 0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn from_params(params: IRParams, mix: f32) -> Result<Self> {
        let ir = generate_ir(&params);
        Self::from_samples(&ir, mix, None)
    }
}

/// Generate a synthetic impulse response from parameters
///
/// Creates a simulated room impulse response using:
/// - Early reflections based on room geometry
/// - Diffuse reverb tail with exponential decay
/// - Frequency-dependent damping
pub fn generate_ir(params: &IRParams) -> Vec<f32> {
    let duration = params.rt60 * 1.5; // Generate 1.5x RT60 for full decay
    let num_samples = (duration * params.sample_rate) as usize;

    let mut ir = vec![0.0; num_samples];

    // 1. Initial impulse (delta function)
    ir[0] = 1.0;

    // 2. Add early reflections (geometric room model)
    add_early_reflections(&mut ir, params);

    // 3. Add diffuse reverb tail (exponential decay)
    add_diffuse_tail(&mut ir, params);

    // 4. Normalize to prevent clipping
    let max = ir.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    if max > 0.0 {
        for sample in &mut ir {
            *sample /= max;
        }
    }

    ir
}

/// Add early reflections based on room geometry
fn add_early_reflections(ir: &mut [f32], params: &IRParams) {
    let (length, width, height) = params.room_dimensions;
    let speed_of_sound = 343.0; // m/s

    // First-order reflections (6 surfaces: walls, floor, ceiling)
    let reflections = [
        (length / speed_of_sound, 0.8),       // Front wall
        (width / speed_of_sound, 0.8),        // Side wall
        (height / speed_of_sound, 0.7),       // Floor
        (length * 1.5 / speed_of_sound, 0.6), // Back wall reflection
        (width * 1.5 / speed_of_sound, 0.6),  // Opposite side
        (height * 2.0 / speed_of_sound, 0.5), // Ceiling reflection
    ];

    for (delay_seconds, amplitude) in reflections {
        let delay_samples = (delay_seconds * params.sample_rate) as usize;
        if delay_samples < ir.len() {
            ir[delay_samples] += amplitude;
        }
    }

    // Add additional random early reflections based on density
    if params.early_density > 0.5 {
        use rand::Rng;
        let mut rng = rand::rng();
        let num_extra = (params.early_density * 20.0) as usize;

        for _ in 0..num_extra {
            let delay = rng.random_range(0.01..0.1); // 10-100ms
            let delay_samples = (delay * params.sample_rate) as usize;
            let amplitude = rng.random_range(0.1..0.5);

            if delay_samples < ir.len() {
                ir[delay_samples] += amplitude;
            }
        }
    }
}

/// Add diffuse reverb tail with exponential decay
fn add_diffuse_tail(ir: &mut [f32], params: &IRParams) {
    use rand::Rng;
    let mut rng = rand::rng();

    // Start diffuse tail after early reflections (~50ms)
    let start_sample = (0.05 * params.sample_rate) as usize;

    // Decay rate based on RT60
    // RT60 = time for 60dB decay (amplitude drops to 0.001)
    let decay_rate = (-60.0 / params.rt60) / params.sample_rate;
    let decay_coefficient = 10.0f32.powf(decay_rate / 20.0);

    // Simple one-pole lowpass for frequency-dependent damping
    let damping_coeff = 1.0 - params.damping;
    let mut lowpass_state = 0.0;

    for (offset, sample) in ir.iter_mut().enumerate().skip(start_sample) {
        // Generate random noise
        let noise = rng.random_range(-1.0..1.0);

        // Apply exponential decay
        let decay = decay_coefficient.powf(offset as f32);

        // Apply lowpass filter (simulates high-frequency absorption)
        lowpass_state = lowpass_state * params.damping + noise * damping_coeff;

        // Add to IR with decay
        *sample += lowpass_state * decay * 0.3;
    }
}

/// Type-safe convolution reverb namespace
///
/// Provides compile-time checked methods for creating convolution reverb.
///
/// # Example
/// ```no_run
/// use tunes::synthesis::effects::{Convolution, convolution};
///
/// // Type-safe preset (IDE autocomplete works!)
/// let reverb = convolution::presets::cathedral(0.5)?;
///
/// // From file
/// let reverb = Convolution::from_file("real_hall.wav", 0.5)?;
///
/// // Custom parameters
/// use tunes::synthesis::effects::IRParams;
/// let reverb = Convolution::from_params(IRParams::cathedral(), 0.5)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub struct Convolution;

impl Convolution {
    /// Create convolution reverb from impulse response file
    ///
    /// Loads a WAV file containing a real or recorded impulse response.
    ///
    /// # Arguments
    /// * `ir_path` - Path to WAV file
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::Convolution;
    ///
    /// let reverb = Convolution::from_file("cathedral.wav", 0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn from_file(ir_path: &str, mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_ir(ir_path, mix, None)
    }

    /// Create convolution reverb from custom IR parameters
    ///
    /// Generates a synthetic IR based on room characteristics.
    ///
    /// # Arguments
    /// * `params` - Room parameters
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::{Convolution, IRParams};
    ///
    /// let params = IRParams {
    ///     room_dimensions: (10.0, 8.0, 4.0),
    ///     rt60: 1.5,
    ///     damping: 0.4,
    ///     early_density: 0.8,
    ///     sample_rate: 44100.0,
    /// };
    /// let reverb = Convolution::from_params(params, 0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn from_params(params: IRParams, mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_params(params, mix)
    }
}

/// Built-in preset impulse responses
///
/// Type-safe presets with compile-time checking and IDE autocomplete.
///
/// # Example
/// ```no_run
/// use tunes::synthesis::effects::convolution;
///
/// let reverb = convolution::presets::cathedral(0.5)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub mod presets {
    use super::*;

    /// Small room reverb (0.3s RT60)
    ///
    /// Tight, intimate space.
    ///
    /// **Good for:** Vocals, drums, close-mic'd instruments
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::convolution;
    ///
    /// let reverb = convolution::presets::small_room(0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn small_room(mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_params(IRParams::small_room(), mix)
    }

    /// Concert hall reverb (2.5s RT60)
    ///
    /// Large, spacious venue with balanced reflections.
    ///
    /// **Good for:** Orchestral, ambient, classical music
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::convolution;
    ///
    /// let reverb = convolution::presets::concert_hall(0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn concert_hall(mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_params(IRParams::concert_hall(), mix)
    }

    /// Cathedral reverb (4.5s RT60)
    ///
    /// Massive space with very long decay time.
    ///
    /// **Good for:** Pads, atmospheric sounds, experimental music
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::convolution;
    ///
    /// let reverb = convolution::presets::cathedral(0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn cathedral(mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_params(IRParams::cathedral(), mix)
    }

    /// Plate reverb (2.0s RT60)
    ///
    /// Bright, dense reflections simulating vintage plate reverb hardware.
    ///
    /// **Good for:** Vocals, drums, classic production sound
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::convolution;
    ///
    /// let reverb = convolution::presets::plate(0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn plate(mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_params(IRParams::plate(), mix)
    }

    /// Spring reverb (1.0s RT60)
    ///
    /// Characteristic "boing" sound of vintage spring reverb tanks.
    ///
    /// **Good for:** Guitars, retro effects, surf music
    ///
    /// # Example
    /// ```no_run
    /// use tunes::synthesis::effects::convolution;
    ///
    /// let reverb = convolution::presets::spring(0.5)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn spring(mix: f32) -> Result<ConvolutionReverb> {
        ConvolutionReverb::from_params(IRParams::spring(), mix)
    }
}

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

    #[test]
    fn test_create_from_samples() {
        let ir = vec![1.0, 0.5, 0.25, 0.1];
        let reverb = ConvolutionReverb::from_samples(&ir, 0.5, None);
        assert!(reverb.is_ok());
    }

    #[test]
    fn test_process_sample() {
        let ir = vec![1.0, 0.5, 0.25];
        let mut reverb = ConvolutionReverb::from_samples(&ir, 0.5, Some(256)).unwrap();

        // Process some samples
        for _ in 0..1000 {
            let output = reverb.process(1.0);
            assert!(output.is_finite());
        }
    }

    #[test]
    fn test_empty_ir_fails() {
        let ir: Vec<f32> = vec![];
        let result = ConvolutionReverb::from_samples(&ir, 0.5, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_reset() {
        let ir = vec![1.0, 0.5, 0.25];
        let mut reverb = ConvolutionReverb::from_samples(&ir, 0.5, None).unwrap();

        // Process some samples
        for _ in 0..100 {
            reverb.process(1.0);
        }

        // Reset
        reverb.reset();

        // Buffers should be empty
        assert_eq!(reverb.sample_count, 0);
    }

    #[test]
    fn test_generate_ir() {
        let params = IRParams::small_room();
        let ir = generate_ir(&params);

        assert!(!ir.is_empty());
        assert!(ir[0].abs() > 0.0); // Should have initial impulse
    }

    #[test]
    fn test_from_params() {
        let reverb = ConvolutionReverb::from_params(IRParams::cathedral(), 0.5);
        assert!(reverb.is_ok());
    }

    #[test]
    fn test_ir_presets() {
        // Test all presets generate valid IRs
        for params in [
            IRParams::small_room(),
            IRParams::concert_hall(),
            IRParams::cathedral(),
            IRParams::plate(),
            IRParams::spring(),
        ] {
            let ir = generate_ir(&params);
            assert!(!ir.is_empty());
            assert!(ir.iter().all(|x| x.is_finite()));
        }
    }
}