voirs-sdk 0.1.0-rc.1

Unified SDK and public API for VoiRS speech synthesis
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
//! Enhancement plugins for speech quality improvement
//!
//! This module provides various audio enhancement plugins specifically designed
//! for improving speech synthesis quality, including noise reduction, speech
//! enhancement, quality upsampling, and artifact removal.

use crate::{
    audio::AudioBuffer,
    error::Result,
    plugins::{AudioEffect, ParameterDefinition, ParameterType, ParameterValue, VoirsPlugin},
    VoirsError,
};
use async_trait::async_trait;
use parking_lot::RwLock;
use std::collections::HashMap;

/// Noise reduction plugin using spectral subtraction
pub struct NoiseReduction {
    /// Noise floor threshold in dB
    pub noise_floor: RwLock<f32>,

    /// Reduction strength (0.0 - 1.0)
    pub reduction_strength: RwLock<f32>,

    /// Smoothing factor for spectral subtraction
    pub smoothing: RwLock<f32>,

    /// Preserve speech clarity (0.0 - 1.0)
    pub speech_preservation: RwLock<f32>,
}

impl NoiseReduction {
    pub fn new() -> Self {
        Self {
            noise_floor: RwLock::new(-40.0),
            reduction_strength: RwLock::new(0.7),
            smoothing: RwLock::new(0.8),
            speech_preservation: RwLock::new(0.9),
        }
    }

    /// Simple noise reduction using amplitude thresholding
    fn apply_noise_reduction(&self, samples: &mut [f32]) {
        let noise_floor_linear = 10.0_f32.powf(*self.noise_floor.read() / 20.0);
        let reduction_strength = *self.reduction_strength.read();
        let speech_preservation = *self.speech_preservation.read();

        for sample in samples.iter_mut() {
            let abs_sample = sample.abs();

            if abs_sample < noise_floor_linear {
                // Apply noise reduction
                *sample *= 1.0 - reduction_strength;
            } else {
                // Preserve speech with gentle processing
                let reduction_factor = 1.0 - (reduction_strength * (1.0 - speech_preservation));
                *sample *= reduction_factor;
            }
        }
    }
}

impl Default for NoiseReduction {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for NoiseReduction {
    fn name(&self) -> &str {
        "Noise Reduction"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Advanced noise reduction for speech enhancement"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl AudioEffect for NoiseReduction {
    async fn process_audio(&self, audio: &AudioBuffer) -> Result<AudioBuffer> {
        let mut processed = audio.clone();
        self.apply_noise_reduction(processed.samples_mut());
        Ok(processed)
    }

    fn get_parameters(&self) -> HashMap<String, ParameterValue> {
        let mut params = HashMap::new();
        params.insert(
            "noise_floor".to_string(),
            ParameterValue::Float(*self.noise_floor.read()),
        );
        params.insert(
            "reduction_strength".to_string(),
            ParameterValue::Float(*self.reduction_strength.read()),
        );
        params.insert(
            "smoothing".to_string(),
            ParameterValue::Float(*self.smoothing.read()),
        );
        params.insert(
            "speech_preservation".to_string(),
            ParameterValue::Float(*self.speech_preservation.read()),
        );
        params
    }

    fn set_parameter(&self, name: &str, value: ParameterValue) -> Result<()> {
        match name {
            "noise_floor" => {
                if let Some(v) = value.as_f32() {
                    *self.noise_floor.write() = v.clamp(-80.0, -10.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid noise_floor parameter type",
                    ))
                }
            }
            "reduction_strength" => {
                if let Some(v) = value.as_f32() {
                    *self.reduction_strength.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid reduction_strength parameter type",
                    ))
                }
            }
            "smoothing" => {
                if let Some(v) = value.as_f32() {
                    *self.smoothing.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid smoothing parameter type",
                    ))
                }
            }
            "speech_preservation" => {
                if let Some(v) = value.as_f32() {
                    *self.speech_preservation.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid speech_preservation parameter type",
                    ))
                }
            }
            _ => Err(VoirsError::internal(
                "plugins",
                format!("Unknown parameter: {name}"),
            )),
        }
    }

    fn get_parameter_definition(&self, name: &str) -> Option<ParameterDefinition> {
        match name {
            "noise_floor" => Some(ParameterDefinition {
                name: "noise_floor".to_string(),
                description: "Noise floor threshold in dB".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(-40.0),
                min_value: Some(ParameterValue::Float(-80.0)),
                max_value: Some(ParameterValue::Float(-10.0)),
                step_size: Some(1.0),
                realtime_safe: true,
            }),
            "reduction_strength" => Some(ParameterDefinition {
                name: "reduction_strength".to_string(),
                description: "Noise reduction strength".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.7),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "smoothing" => Some(ParameterDefinition {
                name: "smoothing".to_string(),
                description: "Spectral smoothing factor".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.8),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: false,
            }),
            "speech_preservation" => Some(ParameterDefinition {
                name: "speech_preservation".to_string(),
                description: "Speech clarity preservation".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.9),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            _ => None,
        }
    }
}

/// Speech enhancement plugin for intelligibility improvement
pub struct SpeechEnhancement {
    /// Formant enhancement strength
    pub formant_enhancement: RwLock<f32>,

    /// Clarity boost (0.0 - 1.0)
    pub clarity_boost: RwLock<f32>,

    /// Presence enhancement for voice
    pub presence: RwLock<f32>,

    /// Sibilance control (0.0 - 1.0)
    pub sibilance_control: RwLock<f32>,
}

impl SpeechEnhancement {
    pub fn new() -> Self {
        Self {
            formant_enhancement: RwLock::new(0.3),
            clarity_boost: RwLock::new(0.5),
            presence: RwLock::new(0.4),
            sibilance_control: RwLock::new(0.7),
        }
    }

    /// Apply speech enhancement processing
    fn enhance_speech(&self, samples: &mut [f32], _sample_rate: u32) {
        let formant_enhancement = *self.formant_enhancement.read();
        let clarity_boost = *self.clarity_boost.read();
        let presence = *self.presence.read();

        // Simple speech enhancement using frequency-domain processing
        // In a real implementation, this would use proper filter banks
        for sample in samples.iter_mut() {
            // Enhance mid frequencies (speech formants)
            let enhanced = *sample * (1.0 + formant_enhancement * 0.3);

            // Add clarity boost
            let clarity_enhanced = enhanced + (*sample * clarity_boost * 0.1);

            // Apply presence boost for voice frequencies
            let presence_enhanced = clarity_enhanced * (1.0 + presence * 0.2);

            *sample = presence_enhanced.clamp(-1.0, 1.0);
        }
    }
}

impl Default for SpeechEnhancement {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for SpeechEnhancement {
    fn name(&self) -> &str {
        "Speech Enhancement"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Intelligibility and clarity enhancement for speech"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl AudioEffect for SpeechEnhancement {
    async fn process_audio(&self, audio: &AudioBuffer) -> Result<AudioBuffer> {
        let mut processed = audio.clone();
        self.enhance_speech(processed.samples_mut(), audio.sample_rate());
        Ok(processed)
    }

    fn get_parameters(&self) -> HashMap<String, ParameterValue> {
        let mut params = HashMap::new();
        params.insert(
            "formant_enhancement".to_string(),
            ParameterValue::Float(*self.formant_enhancement.read()),
        );
        params.insert(
            "clarity_boost".to_string(),
            ParameterValue::Float(*self.clarity_boost.read()),
        );
        params.insert(
            "presence".to_string(),
            ParameterValue::Float(*self.presence.read()),
        );
        params.insert(
            "sibilance_control".to_string(),
            ParameterValue::Float(*self.sibilance_control.read()),
        );
        params
    }

    fn set_parameter(&self, name: &str, value: ParameterValue) -> Result<()> {
        match name {
            "formant_enhancement" => {
                if let Some(v) = value.as_f32() {
                    *self.formant_enhancement.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid formant_enhancement parameter type",
                    ))
                }
            }
            "clarity_boost" => {
                if let Some(v) = value.as_f32() {
                    *self.clarity_boost.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid clarity_boost parameter type",
                    ))
                }
            }
            "presence" => {
                if let Some(v) = value.as_f32() {
                    *self.presence.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid presence parameter type",
                    ))
                }
            }
            "sibilance_control" => {
                if let Some(v) = value.as_f32() {
                    *self.sibilance_control.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid sibilance_control parameter type",
                    ))
                }
            }
            _ => Err(VoirsError::internal(
                "plugins",
                format!("Unknown parameter: {name}"),
            )),
        }
    }

    fn get_parameter_definition(&self, name: &str) -> Option<ParameterDefinition> {
        match name {
            "formant_enhancement" => Some(ParameterDefinition {
                name: "formant_enhancement".to_string(),
                description: "Formant frequency enhancement".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.3),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "clarity_boost" => Some(ParameterDefinition {
                name: "clarity_boost".to_string(),
                description: "Speech clarity boost".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.5),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "presence" => Some(ParameterDefinition {
                name: "presence".to_string(),
                description: "Voice presence enhancement".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.4),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "sibilance_control" => Some(ParameterDefinition {
                name: "sibilance_control".to_string(),
                description: "Sibilance reduction control".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.7),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            _ => None,
        }
    }
}

/// Quality upsampling plugin for sample rate enhancement
pub struct QualityUpsampler {
    /// Target sample rate multiplier (2x, 4x, etc.)
    pub upsample_factor: RwLock<u32>,

    /// Anti-aliasing filter strength
    pub anti_aliasing: RwLock<f32>,

    /// Interpolation quality (0.0 - 1.0)
    pub interpolation_quality: RwLock<f32>,

    /// High-frequency restoration
    pub hf_restoration: RwLock<f32>,
}

impl QualityUpsampler {
    pub fn new() -> Self {
        Self {
            upsample_factor: RwLock::new(2),
            anti_aliasing: RwLock::new(0.8),
            interpolation_quality: RwLock::new(0.9),
            hf_restoration: RwLock::new(0.5),
        }
    }

    /// Simple linear interpolation upsampling
    fn upsample_audio(&self, samples: &[f32]) -> Vec<f32> {
        let factor = *self.upsample_factor.read() as usize;
        let quality = *self.interpolation_quality.read();
        let hf_restoration = *self.hf_restoration.read();

        let mut upsampled = Vec::with_capacity(samples.len() * factor);

        for i in 0..samples.len() {
            upsampled.push(samples[i]);

            // Add interpolated samples
            for j in 1..factor {
                let next_sample = if i + 1 < samples.len() {
                    samples[i + 1]
                } else {
                    samples[i]
                };

                let alpha = j as f32 / factor as f32;
                let interpolated = samples[i] * (1.0 - alpha) + next_sample * alpha;

                // Apply quality enhancement
                let enhanced = interpolated * (1.0 + quality * 0.1);

                // Add high-frequency restoration
                let with_hf = enhanced + (enhanced * hf_restoration * 0.05);

                upsampled.push(with_hf.clamp(-1.0, 1.0));
            }
        }

        upsampled
    }
}

impl Default for QualityUpsampler {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for QualityUpsampler {
    fn name(&self) -> &str {
        "Quality Upsampler"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "High-quality sample rate upsampling with interpolation"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl AudioEffect for QualityUpsampler {
    async fn process_audio(&self, audio: &AudioBuffer) -> Result<AudioBuffer> {
        let factor = *self.upsample_factor.read();
        let upsampled_samples = self.upsample_audio(audio.samples());
        let new_sample_rate = audio.sample_rate() * factor;

        let processed = AudioBuffer::new(upsampled_samples, new_sample_rate, audio.channels());

        Ok(processed)
    }

    fn get_parameters(&self) -> HashMap<String, ParameterValue> {
        let mut params = HashMap::new();
        params.insert(
            "upsample_factor".to_string(),
            ParameterValue::Integer(*self.upsample_factor.read() as i64),
        );
        params.insert(
            "anti_aliasing".to_string(),
            ParameterValue::Float(*self.anti_aliasing.read()),
        );
        params.insert(
            "interpolation_quality".to_string(),
            ParameterValue::Float(*self.interpolation_quality.read()),
        );
        params.insert(
            "hf_restoration".to_string(),
            ParameterValue::Float(*self.hf_restoration.read()),
        );
        params
    }

    fn set_parameter(&self, name: &str, value: ParameterValue) -> Result<()> {
        match name {
            "upsample_factor" => {
                if let Some(v) = value.as_i64() {
                    *self.upsample_factor.write() = (v as u32).clamp(2, 8);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid upsample_factor parameter type",
                    ))
                }
            }
            "anti_aliasing" => {
                if let Some(v) = value.as_f32() {
                    *self.anti_aliasing.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid anti_aliasing parameter type",
                    ))
                }
            }
            "interpolation_quality" => {
                if let Some(v) = value.as_f32() {
                    *self.interpolation_quality.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid interpolation_quality parameter type",
                    ))
                }
            }
            "hf_restoration" => {
                if let Some(v) = value.as_f32() {
                    *self.hf_restoration.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid hf_restoration parameter type",
                    ))
                }
            }
            _ => Err(VoirsError::internal(
                "plugins",
                format!("Unknown parameter: {name}"),
            )),
        }
    }

    fn get_parameter_definition(&self, name: &str) -> Option<ParameterDefinition> {
        match name {
            "upsample_factor" => Some(ParameterDefinition {
                name: "upsample_factor".to_string(),
                description: "Upsampling factor (2x, 4x, etc.)".to_string(),
                parameter_type: ParameterType::Integer,
                default_value: ParameterValue::Integer(2),
                min_value: Some(ParameterValue::Integer(2)),
                max_value: Some(ParameterValue::Integer(8)),
                step_size: Some(1.0),
                realtime_safe: false,
            }),
            "anti_aliasing" => Some(ParameterDefinition {
                name: "anti_aliasing".to_string(),
                description: "Anti-aliasing filter strength".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.8),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: false,
            }),
            "interpolation_quality" => Some(ParameterDefinition {
                name: "interpolation_quality".to_string(),
                description: "Interpolation quality level".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.9),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: false,
            }),
            "hf_restoration" => Some(ParameterDefinition {
                name: "hf_restoration".to_string(),
                description: "High-frequency restoration".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.5),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            _ => None,
        }
    }
}

/// Artifact removal plugin for cleaning synthesis artifacts
pub struct ArtifactRemoval {
    /// Click and pop removal strength
    pub click_removal: RwLock<f32>,

    /// Glitch detection sensitivity
    pub glitch_sensitivity: RwLock<f32>,

    /// Smoothing factor for artifact removal
    pub smoothing: RwLock<f32>,

    /// Preserve transients (0.0 - 1.0)
    pub transient_preservation: RwLock<f32>,
}

impl ArtifactRemoval {
    pub fn new() -> Self {
        Self {
            click_removal: RwLock::new(0.8),
            glitch_sensitivity: RwLock::new(0.7),
            smoothing: RwLock::new(0.5),
            transient_preservation: RwLock::new(0.9),
        }
    }

    /// Remove clicks, pops, and other artifacts
    fn remove_artifacts(&self, samples: &mut [f32]) {
        let click_removal = *self.click_removal.read();
        let glitch_sensitivity = *self.glitch_sensitivity.read();
        let smoothing = *self.smoothing.read();
        let transient_preservation = *self.transient_preservation.read();

        // Simple artifact detection and removal
        for i in 1..samples.len() - 1 {
            let current = samples[i];
            let prev = samples[i - 1];
            let next = samples[i + 1];

            // Detect sudden amplitude changes (clicks/pops)
            let change_from_prev = (current - prev).abs();
            let change_to_next = (current - next).abs();
            let avg_change = (change_from_prev + change_to_next) / 2.0;

            // Threshold for artifact detection
            let threshold = glitch_sensitivity * 0.1;

            if avg_change > threshold {
                // Apply artifact removal with transient preservation
                let artifact_strength = (avg_change - threshold) / threshold;
                let removal_factor =
                    click_removal * artifact_strength * (1.0 - transient_preservation);

                // Smooth interpolation between neighboring samples
                let interpolated = (prev + next) / 2.0;
                let smoothed = current * (1.0 - smoothing) + interpolated * smoothing;

                samples[i] = current * (1.0 - removal_factor) + smoothed * removal_factor;
            }
        }
    }
}

impl Default for ArtifactRemoval {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for ArtifactRemoval {
    fn name(&self) -> &str {
        "Artifact Removal"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Removes clicks, pops, and synthesis artifacts"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl AudioEffect for ArtifactRemoval {
    async fn process_audio(&self, audio: &AudioBuffer) -> Result<AudioBuffer> {
        let mut processed = audio.clone();
        self.remove_artifacts(processed.samples_mut());
        Ok(processed)
    }

    fn get_parameters(&self) -> HashMap<String, ParameterValue> {
        let mut params = HashMap::new();
        params.insert(
            "click_removal".to_string(),
            ParameterValue::Float(*self.click_removal.read()),
        );
        params.insert(
            "glitch_sensitivity".to_string(),
            ParameterValue::Float(*self.glitch_sensitivity.read()),
        );
        params.insert(
            "smoothing".to_string(),
            ParameterValue::Float(*self.smoothing.read()),
        );
        params.insert(
            "transient_preservation".to_string(),
            ParameterValue::Float(*self.transient_preservation.read()),
        );
        params
    }

    fn set_parameter(&self, name: &str, value: ParameterValue) -> Result<()> {
        match name {
            "click_removal" => {
                if let Some(v) = value.as_f32() {
                    *self.click_removal.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid click_removal parameter type",
                    ))
                }
            }
            "glitch_sensitivity" => {
                if let Some(v) = value.as_f32() {
                    *self.glitch_sensitivity.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid glitch_sensitivity parameter type",
                    ))
                }
            }
            "smoothing" => {
                if let Some(v) = value.as_f32() {
                    *self.smoothing.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid smoothing parameter type",
                    ))
                }
            }
            "transient_preservation" => {
                if let Some(v) = value.as_f32() {
                    *self.transient_preservation.write() = v.clamp(0.0, 1.0);
                    Ok(())
                } else {
                    Err(VoirsError::internal(
                        "plugins",
                        "Invalid transient_preservation parameter type",
                    ))
                }
            }
            _ => Err(VoirsError::internal(
                "plugins",
                format!("Unknown parameter: {name}"),
            )),
        }
    }

    fn get_parameter_definition(&self, name: &str) -> Option<ParameterDefinition> {
        match name {
            "click_removal" => Some(ParameterDefinition {
                name: "click_removal".to_string(),
                description: "Click and pop removal strength".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.8),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "glitch_sensitivity" => Some(ParameterDefinition {
                name: "glitch_sensitivity".to_string(),
                description: "Glitch detection sensitivity".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.7),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "smoothing" => Some(ParameterDefinition {
                name: "smoothing".to_string(),
                description: "Artifact smoothing factor".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.5),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            "transient_preservation" => Some(ParameterDefinition {
                name: "transient_preservation".to_string(),
                description: "Preserve important transients".to_string(),
                parameter_type: ParameterType::Float,
                default_value: ParameterValue::Float(0.9),
                min_value: Some(ParameterValue::Float(0.0)),
                max_value: Some(ParameterValue::Float(1.0)),
                step_size: Some(0.01),
                realtime_safe: true,
            }),
            _ => None,
        }
    }
}

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

    #[tokio::test]
    async fn test_noise_reduction() {
        let nr = NoiseReduction::new();

        // Test parameter setting
        nr.set_parameter("noise_floor", ParameterValue::Float(-50.0))
            .unwrap();
        nr.set_parameter("reduction_strength", ParameterValue::Float(0.8))
            .unwrap();

        assert_eq!(*nr.noise_floor.read(), -50.0);
        assert_eq!(*nr.reduction_strength.read(), 0.8);

        // Test audio processing
        let audio = crate::AudioBuffer::sine_wave(440.0, 0.1, 44100, 0.5); // Quiet signal
        let processed = nr.process_audio(&audio).await.unwrap();

        assert_eq!(processed.len(), audio.len());
        assert_eq!(processed.sample_rate(), audio.sample_rate());
    }

    #[tokio::test]
    async fn test_speech_enhancement() {
        let se = SpeechEnhancement::new();

        // Test parameter setting
        se.set_parameter("formant_enhancement", ParameterValue::Float(0.5))
            .unwrap();
        se.set_parameter("clarity_boost", ParameterValue::Float(0.7))
            .unwrap();

        assert_eq!(*se.formant_enhancement.read(), 0.5);
        assert_eq!(*se.clarity_boost.read(), 0.7);

        // Test audio processing
        let audio = crate::AudioBuffer::sine_wave(1000.0, 0.5, 44100, 0.5);
        let processed = se.process_audio(&audio).await.unwrap();

        assert_eq!(processed.len(), audio.len());
        assert_eq!(processed.sample_rate(), audio.sample_rate());
    }

    #[tokio::test]
    async fn test_quality_upsampler() {
        let upsampler = QualityUpsampler::new();

        // Test parameter setting
        upsampler
            .set_parameter("upsample_factor", ParameterValue::Integer(4))
            .unwrap();

        assert_eq!(*upsampler.upsample_factor.read(), 4);

        // Test audio processing - should increase sample rate
        let audio = crate::AudioBuffer::sine_wave(440.0, 0.1, 22050, 0.5);
        let processed = upsampler.process_audio(&audio).await.unwrap();

        assert_eq!(processed.len(), audio.len() * 4); // 4x upsampling
        assert_eq!(processed.sample_rate(), audio.sample_rate() * 4);
    }

    #[tokio::test]
    async fn test_artifact_removal() {
        let ar = ArtifactRemoval::new();

        // Test parameter setting
        ar.set_parameter("click_removal", ParameterValue::Float(0.9))
            .unwrap();
        ar.set_parameter("glitch_sensitivity", ParameterValue::Float(0.6))
            .unwrap();

        assert_eq!(*ar.click_removal.read(), 0.9);
        assert_eq!(*ar.glitch_sensitivity.read(), 0.6);

        // Test audio processing
        let audio = crate::AudioBuffer::sine_wave(440.0, 0.5, 44100, 0.5);
        let processed = ar.process_audio(&audio).await.unwrap();

        assert_eq!(processed.len(), audio.len());
        assert_eq!(processed.sample_rate(), audio.sample_rate());
    }

    #[test]
    fn test_enhancement_plugin_metadata() {
        let nr = NoiseReduction::new();
        assert_eq!(nr.name(), "Noise Reduction");
        assert_eq!(nr.version(), "1.0.0");
        assert_eq!(nr.author(), "VoiRS Team");

        let se = SpeechEnhancement::new();
        assert_eq!(se.name(), "Speech Enhancement");

        let upsampler = QualityUpsampler::new();
        assert_eq!(upsampler.name(), "Quality Upsampler");

        let ar = ArtifactRemoval::new();
        assert_eq!(ar.name(), "Artifact Removal");
    }
}