timestretch 0.7.0

Pure Rust audio time stretching library optimized for EDM
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
//! Integration tests for sub-bass band-split processing.
//!
//! Verifies that `band_split` correctly separates sub-bass for independent
//! PV processing while the remainder goes through the hybrid algorithm.
//! Tests exercise the public `stretch()` API end-to-end.

use timestretch::{stretch, EdmPreset, StretchParams};

fn sine_wave(freq: f32, sample_rate: u32, num_samples: usize) -> Vec<f32> {
    (0..num_samples)
        .map(|i| (2.0 * std::f32::consts::PI * freq * i as f32 / sample_rate as f32).sin())
        .collect()
}

fn rms(signal: &[f32]) -> f32 {
    if signal.is_empty() {
        return 0.0;
    }
    (signal.iter().map(|x| x * x).sum::<f32>() / signal.len() as f32).sqrt()
}

/// Creates a signal with both sub-bass and mid-range content,
/// similar to an EDM track with kick drum and synth pad.
fn edm_like_signal(sample_rate: u32, duration_secs: f64) -> Vec<f32> {
    let num_samples = (sample_rate as f64 * duration_secs) as usize;
    let beat_interval = (sample_rate as f64 * 0.5) as usize; // 120 BPM

    let mut signal = vec![0.0f32; num_samples];

    for (i, sample) in signal.iter_mut().enumerate() {
        let t = i as f32 / sample_rate as f32;

        // Sub-bass: 50 Hz sine (constant)
        *sample += 0.4 * (2.0 * std::f32::consts::PI * 50.0 * t).sin();

        // Mid-range synth pad: 400 Hz
        *sample += 0.3 * (2.0 * std::f32::consts::PI * 400.0 * t).sin();

        // Hi-hat: 6000 Hz
        *sample += 0.1 * (2.0 * std::f32::consts::PI * 6000.0 * t).sin();
    }

    // Add kick-like transients every beat
    for beat in 0..(num_samples / beat_interval) {
        let pos = beat * beat_interval;
        for j in 0..20.min(num_samples - pos) {
            signal[pos + j] += if j < 5 { 0.5 } else { -0.2 };
        }
    }

    // Clamp to [-1, 1]
    for s in &mut signal {
        *s = s.clamp(-1.0, 1.0);
    }

    signal
}

#[test]
fn test_band_split_enabled_by_default_with_presets() {
    // All EDM presets should enable either band_split or multi_resolution.
    // Presets with multi_resolution=true set band_split=false to avoid
    // redundant sub-bass processing paths.
    let presets = [
        EdmPreset::DjBeatmatch,
        EdmPreset::HouseLoop,
        EdmPreset::Halftime,
        EdmPreset::Ambient,
        EdmPreset::VocalChop,
    ];

    for preset in presets {
        let params = StretchParams::new(1.5).with_preset(preset);
        assert!(
            params.band_split || params.multi_resolution,
            "Preset {:?} should enable band_split or multi_resolution",
            preset
        );
    }
}

#[test]
fn test_band_split_disabled_by_default_without_preset() {
    let params = StretchParams::new(1.5);
    assert!(!params.band_split);
}

#[test]
fn test_band_split_can_be_toggled_after_preset() {
    let params = StretchParams::new(1.5)
        .with_preset(EdmPreset::HouseLoop)
        .with_band_split(false);
    assert!(!params.band_split);

    let params = StretchParams::new(1.5).with_band_split(true);
    assert!(params.band_split);
}

#[test]
fn test_band_split_stretch_edm_signal() {
    let sample_rate = 44100u32;
    let input = edm_like_signal(sample_rate, 2.0);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::HouseLoop);

    let output = stretch(&input, &params).unwrap();

    // Output should be ~1.5x longer
    let ratio = output.len() as f64 / input.len() as f64;
    assert!(
        (ratio - 1.5).abs() < 0.4,
        "EDM signal stretch ratio {} too far from 1.5",
        ratio
    );

    // No NaN/Inf
    assert!(
        output.iter().all(|s| s.is_finite()),
        "Output contains NaN/Inf"
    );

    // RMS should be preserved within a reasonable range
    let input_rms = rms(&input);
    let output_rms = rms(&output);
    let rms_ratio = output_rms / input_rms;
    assert!(
        (0.3..=2.0).contains(&rms_ratio),
        "RMS ratio {} out of range (input={}, output={})",
        rms_ratio,
        input_rms,
        output_rms
    );
}

#[test]
fn test_band_split_preserves_sub_bass_energy() {
    // A pure sub-bass signal should be well-preserved by band-split processing
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;
    let input = sine_wave(60.0, sample_rate, num_samples);
    let input_rms = rms(&input);

    // With band_split (via preset)
    let params_split = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::HouseLoop);
    let output_split = stretch(&input, &params_split).unwrap();
    let output_rms_split = rms(&output_split);

    // Without band_split
    let params_no_split = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::HouseLoop)
        .with_band_split(false);
    let output_no_split = stretch(&input, &params_no_split).unwrap();
    let output_rms_no_split = rms(&output_no_split);

    // Both should preserve sub-bass energy reasonably
    assert!(
        output_rms_split > input_rms * 0.3,
        "Band-split sub-bass RMS {} too low (input={})",
        output_rms_split,
        input_rms
    );
    assert!(
        output_rms_no_split > input_rms * 0.3,
        "Non-split sub-bass RMS {} too low (input={})",
        output_rms_no_split,
        input_rms
    );
}

#[test]
fn test_band_split_preserves_high_freq_content() {
    // A 1000 Hz signal should pass through band-split processing intact
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;
    let input = sine_wave(1000.0, sample_rate, num_samples);
    let input_rms = rms(&input);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_band_split(true);

    let output = stretch(&input, &params).unwrap();
    let output_rms = rms(&output);

    // High-freq content should be preserved
    assert!(
        output_rms > input_rms * 0.2,
        "1 kHz signal RMS {} too low after band-split stretch (input={})",
        output_rms,
        input_rms
    );
}

#[test]
fn test_band_split_dj_beatmatch_small_ratio() {
    // DJ use case: 126 -> 128 BPM (ratio ~0.984)
    let sample_rate = 44100u32;
    let input = edm_like_signal(sample_rate, 2.0);

    let params = StretchParams::new(126.0 / 128.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::DjBeatmatch);

    let output = stretch(&input, &params).unwrap();

    // Small compression: output should be slightly shorter
    assert!(
        output.len() < input.len(),
        "126->128 BPM should produce shorter output"
    );

    // No clipping
    assert!(
        output.iter().all(|s| s.abs() <= 1.5),
        "Output exceeds ±1.5 (clipping)"
    );
}

#[test]
fn test_band_split_halftime_stretch() {
    // Halftime: 2x stretch
    let sample_rate = 44100u32;
    let input = edm_like_signal(sample_rate, 2.0);

    let params = StretchParams::new(2.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::Halftime);

    let output = stretch(&input, &params).unwrap();

    let ratio = output.len() as f64 / input.len() as f64;
    assert!(
        (ratio - 2.0).abs() < 0.5,
        "Halftime stretch ratio {} too far from 2.0",
        ratio
    );

    assert!(
        output.iter().all(|s| s.is_finite()),
        "Output contains NaN/Inf"
    );
}

#[test]
fn test_band_split_compression() {
    // Compression: 0.75x (speed up from 120 to 160 BPM)
    let sample_rate = 44100u32;
    let input = edm_like_signal(sample_rate, 2.0);

    let params = StretchParams::new(0.75)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::HouseLoop);

    let output = stretch(&input, &params).unwrap();

    assert!(
        output.len() < input.len(),
        "Compression should produce shorter output"
    );
    assert!(
        output.iter().all(|s| s.is_finite()),
        "Output contains NaN/Inf"
    );
}

#[test]
fn test_band_split_stereo() {
    // Stereo signal: both channels should work with band-split
    let sample_rate = 44100u32;
    let num_frames = sample_rate as usize * 2;
    let mut input = vec![0.0f32; num_frames * 2];

    for i in 0..num_frames {
        let t = i as f32 / sample_rate as f32;
        // Left: sub-bass + mid
        input[i * 2] = 0.4 * (2.0 * std::f32::consts::PI * 50.0 * t).sin()
            + 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
        // Right: sub-bass + high
        input[i * 2 + 1] = 0.4 * (2.0 * std::f32::consts::PI * 50.0 * t).sin()
            + 0.2 * (2.0 * std::f32::consts::PI * 2000.0 * t).sin();
    }

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(2)
        .with_preset(EdmPreset::HouseLoop);

    let output = stretch(&input, &params).unwrap();

    assert!(!output.is_empty());
    assert_eq!(output.len() % 2, 0, "Stereo output must have even length");
    assert!(
        output.iter().all(|s| s.is_finite()),
        "Stereo output contains NaN/Inf"
    );
}

#[test]
fn test_band_split_48khz() {
    // Ensure band-split works at 48 kHz sample rate
    let sample_rate = 48000u32;
    let num_samples = sample_rate as usize * 2;
    let input = sine_wave(60.0, sample_rate, num_samples);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::HouseLoop);

    let output = stretch(&input, &params).unwrap();

    assert!(!output.is_empty());
    assert!(
        output.iter().all(|s| s.is_finite()),
        "48 kHz output contains NaN/Inf"
    );
}

#[test]
fn test_band_split_ambient_extreme_stretch() {
    // Extreme stretch: 3x with Ambient preset
    let sample_rate = 44100u32;
    let input = edm_like_signal(sample_rate, 2.0);

    let params = StretchParams::new(3.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::Ambient);

    let output = stretch(&input, &params).unwrap();

    let ratio = output.len() as f64 / input.len() as f64;
    assert!(
        (ratio - 3.0).abs() < 1.0,
        "Ambient 3x stretch ratio {} too far from 3.0",
        ratio
    );

    assert!(
        output.iter().all(|s| s.is_finite()),
        "Ambient output contains NaN/Inf"
    );
}

#[test]
fn test_band_split_vocal_chop_preset() {
    // VocalChop preset with a mid-range signal
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;
    let input = sine_wave(300.0, sample_rate, num_samples);

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::VocalChop);

    let output = stretch(&input, &params).unwrap();

    assert!(!output.is_empty());
    assert!(
        output.iter().all(|s| s.is_finite()),
        "VocalChop output contains NaN/Inf"
    );

    let output_rms = rms(&output);
    let input_rms = rms(&input);
    assert!(
        output_rms > input_rms * 0.2,
        "VocalChop should preserve energy: input_rms={}, output_rms={}",
        input_rms,
        output_rms
    );
}

#[test]
fn test_band_split_with_custom_cutoff() {
    // Custom sub-bass cutoff (200 Hz instead of default 120 Hz)
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;

    // Mix of 100 Hz and 500 Hz
    let input: Vec<f32> = (0..num_samples)
        .map(|i| {
            let t = i as f32 / sample_rate as f32;
            0.5 * (2.0 * std::f32::consts::PI * 100.0 * t).sin()
                + 0.5 * (2.0 * std::f32::consts::PI * 500.0 * t).sin()
        })
        .collect();

    let params = StretchParams::new(1.5)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_band_split(true)
        .with_sub_bass_cutoff(200.0);

    let output = stretch(&input, &params).unwrap();

    assert!(!output.is_empty());
    assert!(
        output.iter().all(|s| s.is_finite()),
        "Custom cutoff output contains NaN/Inf"
    );
}

#[test]
fn test_band_split_pitch_shift() {
    // Band-split should also work when used via pitch_shift
    let sample_rate = 44100u32;
    let num_samples = sample_rate as usize * 2;
    let input = sine_wave(440.0, sample_rate, num_samples);

    let params = StretchParams::new(1.0)
        .with_sample_rate(sample_rate)
        .with_channels(1)
        .with_preset(EdmPreset::HouseLoop);

    let output = timestretch::pitch_shift(&input, &params, 1.5).unwrap();

    // Pitch shift preserves length
    assert_eq!(output.len(), input.len());
    assert!(
        output.iter().all(|s| s.is_finite()),
        "Pitch shift output contains NaN/Inf"
    );
}

/// The Linkwitz-Riley crossover is stateful IIR: splitting a signal in
/// small chunks (streaming) must produce exactly the same band signals as
/// splitting the whole buffer in one call.
#[test]
fn test_three_band_splitter_chunked_matches_whole() {
    use timestretch::core::crossover::ThreeBandSplitter;

    let sample_rate = 44100u32;
    let input = edm_like_signal(sample_rate, 2.0);
    let len = input.len();

    let mut whole = ThreeBandSplitter::new(200.0, 4000.0, sample_rate);
    let mut whole_sub = vec![0.0f32; len];
    let mut whole_mid = vec![0.0f32; len];
    let mut whole_high = vec![0.0f32; len];
    whole.process(&input, &mut whole_sub, &mut whole_mid, &mut whole_high);

    let mut chunked = ThreeBandSplitter::new(200.0, 4000.0, sample_rate);
    let mut chunk_sub = vec![0.0f32; len];
    let mut chunk_mid = vec![0.0f32; len];
    let mut chunk_high = vec![0.0f32; len];
    let mut pos = 0usize;
    // Irregular chunk sizes to catch any per-call state assumptions.
    for &chunk_len in [1usize, 7, 64, 250, 512, 1000, 4096].iter().cycle() {
        if pos >= len {
            break;
        }
        let end = (pos + chunk_len).min(len);
        chunked.process(
            &input[pos..end],
            &mut chunk_sub[pos..end],
            &mut chunk_mid[pos..end],
            &mut chunk_high[pos..end],
        );
        pos = end;
    }

    for (name, whole_band, chunk_band) in [
        ("sub", &whole_sub, &chunk_sub),
        ("mid", &whole_mid, &chunk_mid),
        ("high", &whole_high, &chunk_high),
    ] {
        let max_diff = whole_band
            .iter()
            .zip(chunk_band.iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0f32, f32::max);
        assert!(
            max_diff < 1e-6,
            "{name} band: chunked split diverged from whole-buffer split by {max_diff}"
        );
    }
}