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
use crate::synthesis::automation::Automation;
use crate::track::PRIORITY_NORMAL;

/// Distortion/overdrive effect
#[derive(Debug, Clone)]
pub struct Distortion {
    pub drive: f32,   // Drive amount (1.0 = no distortion, higher = more)
    pub mix: f32,     // Wet/dry mix (0.0 = dry, 1.0 = wet)
    pub priority: u8, // Processing priority (lower = earlier in signal chain)

    // Automation (optional)
    drive_automation: Option<Automation>,
    mix_automation: Option<Automation>,

    // Pre-allocated buffer for dry signal (reused across calls)
    dry_buffer: Vec<f32>,
}

impl Distortion {
    /// Create a new distortion effect
    pub fn new(drive: f32, mix: f32) -> Self {
        Self {
            drive: drive.max(1.0),
            mix: mix.clamp(0.0, 1.0),
            priority: PRIORITY_NORMAL, // Distortion in normal/middle position
            drive_automation: None,
            mix_automation: None,
            dry_buffer: Vec::new(), // Pre-allocated, grows on first use
        }
    }

    /// Set the processing priority (lower = earlier in signal chain)
    pub fn with_priority(mut self, priority: u8) -> Self {
        self.priority = priority;
        self
    }

    /// Add automation for the mix parameter
    pub fn with_mix_automation(mut self, automation: Automation) -> Self {
        self.mix_automation = Some(automation);
        self
    }

    /// Add automation for the drive parameter
    pub fn with_drive_automation(mut self, automation: Automation) -> Self {
        self.drive_automation = Some(automation);
        self
    }

    /// Process a single sample using soft clipping
    ///
    /// # Arguments
    /// * `input` - Input sample
    /// * `time` - Current time in seconds (for automation)
    /// * `sample_count` - Global sample counter (for quantized automation lookups)
    #[inline]
    pub fn process(&mut self, input: f32, time: f32, sample_count: u64) -> f32 {
        // Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
        // Use bitwise AND instead of modulo for power-of-2
        if sample_count & 63 == 0 {
            if let Some(auto) = &self.mix_automation {
                self.mix = auto.value_at(time).clamp(0.0, 1.0);
            }
            if let Some(auto) = &self.drive_automation {
                self.drive = auto.value_at(time).max(1.0);
            }
        }

        if self.mix < 0.0001 {
            return input;
        }

        let amplified = input * self.drive;

        // Soft clipping using tanh
        let distorted = amplified.tanh();

        // Compensate for gain increase
        let normalized = distorted / self.drive.sqrt();

        // Mix dry and wet using FMA
        input.mul_add(1.0 - self.mix, normalized * self.mix)
    }

    /// Process a block of samples with TRUE SIMD acceleration
    ///
    /// # Arguments
    /// * `buffer` - Buffer of samples to process in-place
    /// * `time` - Starting time in seconds (for automation)
    /// * `sample_count` - Starting sample counter (for quantized automation lookups)
    /// * `sample_rate` - Sample rate in Hz (for time advancement)
    #[inline]
    pub fn process_block(&mut self, buffer: &mut [f32], time: f32, sample_count: u64, _sample_rate: f32) {
        // Update automation params if needed (check first sample)
        if sample_count & 63 == 0 {
            if let Some(auto) = &self.mix_automation {
                self.mix = auto.value_at(time).clamp(0.0, 1.0);
            }
            if let Some(auto) = &self.drive_automation {
                self.drive = auto.value_at(time).max(1.0);
            }
        }

        // Early exit if no effect
        if self.mix < 0.0001 {
            return;
        }

        // Use true SIMD implementation (auto-dispatches to best width)
        self.process_block_simd(buffer);
    }

    /// SIMD implementation using true vector operations
    #[inline(always)]
    fn process_block_simd(&mut self, buffer: &mut [f32]) {
        use crate::synthesis::simd::SIMD;

        let drive = self.drive;
        let mix = self.mix;
        let compensation = 1.0 / drive.sqrt();

        // Reuse pre-allocated dry buffer (grows once, then reused)
        self.dry_buffer.clear();
        self.dry_buffer.extend_from_slice(buffer);

        // TRUE SIMD processing chain:
        // 1. Multiply by drive
        SIMD.multiply_const(buffer, drive);

        // 2. Apply fast tanh saturation
        SIMD.apply_fast_tanh(buffer);

        // 3. Apply compensation and mix using SIMD FMA
        // buffer = dry * (1-mix) + buffer * (compensation * mix)
        let wet_gain = compensation * mix;
        let dry_gain = 1.0 - mix;

        // SIMD-optimized wet/dry mix using FMA
        SIMD.multiply_const(buffer, wet_gain);
        for (output, &dry_sample) in buffer.iter_mut().zip(self.dry_buffer.iter()) {
            *output = dry_sample.mul_add(dry_gain, *output);
        }
    }

    // ========== PRESETS ==========

    /// Light saturation - subtle analog warmth
    pub fn saturation() -> Self {
        Self::new(1.5, 0.5)
    }

    /// Overdrive - tube-style warmth and grit
    pub fn overdrive() -> Self {
        Self::new(2.5, 0.8)
    }

    /// Crunch - classic rock distortion
    pub fn crunch() -> Self {
        Self::new(4.0, 0.9)
    }

    /// Heavy distortion - metal/high-gain
    pub fn heavy() -> Self {
        Self::new(6.0, 1.0)
    }

    /// Fuzz - extreme, compressed distortion
    pub fn fuzz() -> Self {
        Self::new(8.0, 1.0)
    }

    /// Gentle drive - barely-there warmth
    pub fn gentle() -> Self {
        Self::new(1.8, 0.4)
    }
}

/// Bit crusher - lo-fi digital degradation effect
#[derive(Debug, Clone)]
pub struct BitCrusher {
    pub bit_depth: f32,             // Bit depth (1.0 to 16.0, lower = more crushing)
    pub sample_rate_reduction: f32, // Sample rate divisor (1.0 = no reduction, higher = more lo-fi)
    pub mix: f32,                   // Wet/dry mix (0.0 = dry, 1.0 = wet)
    pub priority: u8,               // Processing priority (lower = earlier in signal chain)
    hold_sample: f32,
    sample_counter: f32,

    // Automation (optional)
    bit_depth_automation: Option<Automation>,
    sample_rate_reduction_automation: Option<Automation>,
    mix_automation: Option<Automation>,
}

impl BitCrusher {
    /// Create a new bit crusher effect
    ///
    /// # Arguments
    /// * `bit_depth` - Bit depth (1.0 to 16.0, typical: 4.0-8.0 for lo-fi)
    /// * `sample_rate_reduction` - Downsample factor (1.0 = original, 4.0 = quarter rate)
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    pub fn new(bit_depth: f32, sample_rate_reduction: f32, mix: f32) -> Self {
        Self {
            bit_depth: bit_depth.clamp(1.0, 16.0),
            sample_rate_reduction: sample_rate_reduction.max(1.0),
            mix: mix.clamp(0.0, 1.0),
            priority: PRIORITY_NORMAL, // BitCrusher in normal position
            hold_sample: 0.0,
            sample_counter: 0.0,
            bit_depth_automation: None,
            sample_rate_reduction_automation: None,
            mix_automation: None,
        }
    }

    /// Set the processing priority (lower = earlier in signal chain)
    pub fn with_priority(mut self, priority: u8) -> Self {
        self.priority = priority;
        self
    }

    /// Add automation for the mix parameter
    pub fn with_mix_automation(mut self, automation: Automation) -> Self {
        self.mix_automation = Some(automation);
        self
    }

    /// Add automation for the bit depth parameter
    pub fn with_bit_depth_automation(mut self, automation: Automation) -> Self {
        self.bit_depth_automation = Some(automation);
        self
    }

    /// Add automation for the sample rate reduction parameter
    pub fn with_sample_rate_reduction_automation(mut self, automation: Automation) -> Self {
        self.sample_rate_reduction_automation = Some(automation);
        self
    }

    /// Process a single sample
    ///
    /// # Arguments
    /// * `input` - Input sample
    /// * `time` - Current time in seconds (for automation)
    /// * `sample_count` - Global sample counter (for quantized automation lookups)
    #[inline]
    pub fn process(&mut self, input: f32, time: f32, sample_count: u64) -> f32 {
        // Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
        // Use bitwise AND instead of modulo for power-of-2
        if sample_count & 63 == 0 {
            if let Some(auto) = &self.mix_automation {
                self.mix = auto.value_at(time).clamp(0.0, 1.0);
            }
            if let Some(auto) = &self.bit_depth_automation {
                self.bit_depth = auto.value_at(time).clamp(1.0, 16.0);
            }
            if let Some(auto) = &self.sample_rate_reduction_automation {
                self.sample_rate_reduction = auto.value_at(time).max(1.0);
            }
        }

        // Sample rate reduction (sample & hold)
        self.sample_counter += 1.0;
        if self.sample_counter >= self.sample_rate_reduction {
            self.hold_sample = input.clamp(-2.0, 2.0);
            self.sample_counter = 0.0;
        }

        // Bit depth reduction (quantization)
        // Use exp2 instead of powf for 2^x (much faster)
        let levels = self.bit_depth.exp2();
        let quantized = (self.hold_sample * levels).round() / levels;

        // Mix dry and wet using FMA, clamp output
        let output = input.mul_add(1.0 - self.mix, quantized * self.mix);
        output.clamp(-2.0, 2.0)
    }

    /// Process a block of samples
    ///
    /// # Arguments
    /// * `buffer` - Buffer of samples to process in-place
    /// * `time` - Starting time in seconds (for automation)
    /// * `sample_count` - Starting sample counter (for quantized automation lookups)
    /// * `sample_rate` - Sample rate in Hz (for time advancement)
    #[inline]
    pub fn process_block(&mut self, buffer: &mut [f32], time: f32, sample_count: u64, sample_rate: f32) {
        let time_delta = 1.0 / sample_rate;
        for (i, sample) in buffer.iter_mut().enumerate() {
            let current_time = time + (i as f32 * time_delta);
            let current_sample_count = sample_count + i as u64;
            *sample = self.process(*sample, current_time, current_sample_count);
        }
    }

    /// Reset the bit crusher state
    pub fn reset(&mut self) {
        self.hold_sample = 0.0;
        self.sample_counter = 0.0;
    }

    // ========== PRESETS ==========

    /// Lo-fi effect - 8-bit style with mild downsampling
    pub fn lofi() -> Self {
        Self::new(8.0, 2.0, 0.7)
    }

    /// Game Boy - classic 4-bit handheld sound
    pub fn gameboy() -> Self {
        Self::new(4.0, 4.0, 0.85)
    }

    /// Telephone - heavily crushed, narrow bandwidth
    pub fn telephone() -> Self {
        Self::new(6.0, 8.0, 0.8)
    }

    /// Glitch - extreme digital degradation
    pub fn glitch() -> Self {
        Self::new(3.0, 12.0, 1.0)
    }

    /// Vintage - subtle lo-fi character
    pub fn vintage() -> Self {
        Self::new(10.0, 1.5, 0.4)
    }
}

/// Saturation effect - analog-style harmonic distortion
#[derive(Debug, Clone)]
pub struct Saturation {
    pub drive: f32,     // Drive amount (1.0 to 10.0)
    pub character: f32, // Saturation character (0.0 = soft, 1.0 = hard)
    pub mix: f32,       // Wet/dry mix (0.0 = dry, 1.0 = wet)
    pub priority: u8,   // Processing priority (lower = earlier in signal chain)

    // Automation (optional)
    drive_automation: Option<Automation>,
    character_automation: Option<Automation>,
    mix_automation: Option<Automation>,
}

impl Saturation {
    /// Create a new saturation effect
    ///
    /// # Arguments
    /// * `drive` - Input gain (1.0 to 10.0, typical: 2.0-4.0)
    /// * `character` - Hardness (0.0 = soft/warm, 1.0 = hard/aggressive)
    /// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
    pub fn new(drive: f32, character: f32, mix: f32) -> Self {
        Self {
            drive: drive.clamp(1.0, 20.0),
            character: character.clamp(0.0, 1.0),
            mix: mix.clamp(0.0, 1.0),
            priority: PRIORITY_NORMAL, // Saturation in normal position
            drive_automation: None,
            character_automation: None,
            mix_automation: None,
        }
    }

    /// Set the processing priority (lower = earlier in signal chain)
    pub fn with_priority(mut self, priority: u8) -> Self {
        self.priority = priority;
        self
    }

    /// Add automation for the mix parameter
    pub fn with_mix_automation(mut self, automation: Automation) -> Self {
        self.mix_automation = Some(automation);
        self
    }

    /// Add automation for the drive parameter
    pub fn with_drive_automation(mut self, automation: Automation) -> Self {
        self.drive_automation = Some(automation);
        self
    }

    /// Add automation for the character parameter
    pub fn with_character_automation(mut self, automation: Automation) -> Self {
        self.character_automation = Some(automation);
        self
    }

    /// Process a single sample
    ///
    /// # Arguments
    /// * `input` - Input sample
    /// * `time` - Current time in seconds (for automation)
    /// * `sample_count` - Global sample counter (for quantized automation lookups)
    #[inline]
    pub fn process(&mut self, input: f32, time: f32, sample_count: u64) -> f32 {
        // Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
        // Use bitwise AND instead of modulo for power-of-2
        if sample_count & 63 == 0 {
            if let Some(auto) = &self.mix_automation {
                self.mix = auto.value_at(time).clamp(0.0, 1.0);
            }
            if let Some(auto) = &self.drive_automation {
                self.drive = auto.value_at(time).clamp(1.0, 20.0);
            }
            if let Some(auto) = &self.character_automation {
                self.character = auto.value_at(time).clamp(0.0, 1.0);
            }
        }

        if self.mix < 0.0001 {
            return input;
        }

        let amplified = input * self.drive;

        // Blend between soft (tanh) and hard (cubic) saturation
        let soft = amplified.tanh();
        let hard = if amplified.abs() <= 1.0 {
            amplified.mul_add(1.5, -0.5 * amplified * amplified.abs())
        } else {
            amplified.signum()
        };

        let saturated = soft.mul_add(1.0 - self.character, hard * self.character);

        // Compensate for gain and mix using FMA
        let normalized = saturated / self.drive.sqrt();
        input.mul_add(1.0 - self.mix, normalized * self.mix)
    }

    /// Process a block of samples with TRUE SIMD acceleration
    ///
    /// # Arguments
    /// * `buffer` - Buffer of samples to process in-place
    /// * `time` - Starting time in seconds (for automation)
    /// * `sample_count` - Starting sample counter (for quantized automation lookups)
    /// * `sample_rate` - Sample rate in Hz (for time advancement)
    #[inline]
    pub fn process_block(&mut self, buffer: &mut [f32], time: f32, sample_count: u64, _sample_rate: f32) {
        // Update automation params if needed
        if sample_count & 63 == 0 {
            if let Some(auto) = &self.mix_automation {
                self.mix = auto.value_at(time).clamp(0.0, 1.0);
            }
            if let Some(auto) = &self.drive_automation {
                self.drive = auto.value_at(time).clamp(1.0, 20.0);
            }
            if let Some(auto) = &self.character_automation {
                self.character = auto.value_at(time).clamp(0.0, 1.0);
            }
        }

        // Early exit if no effect
        if self.mix < 0.0001 {
            return;
        }

        // Use true SIMD implementation
        self.process_block_simd(buffer);
    }

    /// TRUE SIMD implementation
    #[inline(always)]
    fn process_block_simd(&self, buffer: &mut [f32]) {
        use crate::synthesis::simd::SIMD;

        let drive = self.drive;
        let character = self.character;
        let mix = self.mix;
        let compensation = 1.0 / drive.sqrt();

        // Store dry signal for wet/dry mix
        let dry: Vec<f32> = buffer.to_vec();

        // SIMD processing for soft saturation (tanh) path
        // 1. Multiply by drive
        SIMD.multiply_const(buffer, drive);

        // 2. Apply fast tanh
        SIMD.apply_fast_tanh(buffer);

        // 3. If character > 0, blend with hard saturation
        //    Hard saturation has branches, so we do this part scalar for now
        if character > 0.001 {
            let one_minus_character = 1.0 - character;

            for (i, &amplified_dry) in dry.iter().enumerate() {
                let amplified = amplified_dry * drive;
                let soft = buffer[i]; // Already has tanh applied

                // Hard saturation (cubic soft clipper)
                let hard = if amplified.abs() <= 1.0 {
                    amplified.mul_add(1.5, -0.5 * amplified * amplified.abs())
                } else {
                    amplified.signum()
                };

                // Blend soft and hard
                buffer[i] = soft.mul_add(one_minus_character, hard * character);
            }
        }

        // 4. Apply compensation and wet/dry mix
        let wet_gain = compensation * mix;
        let dry_gain = 1.0 - mix;

        for (output, &dry_sample) in buffer.iter_mut().zip(dry.iter()) {
            *output = dry_sample.mul_add(dry_gain, *output * wet_gain);
        }
    }

    // ========== PRESETS ==========

    /// Tape saturation - warm analog tape character
    pub fn tape() -> Self {
        Self::new(2.0, 0.3, 0.7)
    }

    /// Tube saturation - vintage tube amp warmth
    pub fn tube() -> Self {
        Self::new(3.0, 0.5, 0.8)
    }

    /// Soft clipping - gentle harmonic enhancement
    pub fn soft() -> Self {
        Self::new(1.5, 0.2, 0.5)
    }

    /// Hard clipping - aggressive saturation
    pub fn hard() -> Self {
        Self::new(4.0, 0.8, 0.9)
    }

    /// Warmth - subtle analog color
    pub fn warmth() -> Self {
        Self::new(1.8, 0.4, 0.6)
    }

    /// Aggressive - heavy analog distortion
    pub fn aggressive() -> Self {
        Self::new(5.0, 0.9, 1.0)
    }
}