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
//! Integration tests for AudioBuffer utility methods in real stretch workflows.
//!
//! These tests combine slice, concatenate, normalize, fade, trim_silence,
//! peak, rms, and frames() with the time-stretching pipeline to validate
//! that the utilities work correctly in practice.

use timestretch::{AudioBuffer, Channels, EdmPreset, StretchParams};

/// Generate a mono sine wave at the given frequency.
fn sine_mono(freq: f32, sample_rate: u32, num_frames: usize) -> AudioBuffer {
    let data: Vec<f32> = (0..num_frames)
        .map(|i| (2.0 * std::f32::consts::PI * freq * i as f32 / sample_rate as f32).sin())
        .collect();
    AudioBuffer::from_mono(data, sample_rate)
}

/// Generate a stereo sine wave (same frequency both channels).
fn sine_stereo(freq: f32, sample_rate: u32, num_frames: usize) -> AudioBuffer {
    let mut data = Vec::with_capacity(num_frames * 2);
    for i in 0..num_frames {
        let s = (2.0 * std::f32::consts::PI * freq * i as f32 / sample_rate as f32).sin();
        data.push(s);
        data.push(s);
    }
    AudioBuffer::from_stereo(data, sample_rate)
}

// ==================== SLICE + STRETCH ====================

#[test]
fn test_slice_then_stretch() {
    // Take a longer buffer, slice a portion, stretch it
    let full = sine_mono(440.0, 44100, 44100); // 1 second
    let portion = full.slice(10000, 20000); // middle ~0.45s
    assert_eq!(portion.num_frames(), 20000);

    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch_buffer(&portion, &params).unwrap();

    // Output should be roughly 1.5x the input length
    let ratio = output.num_frames() as f64 / portion.num_frames() as f64;
    assert!(
        (ratio - 1.5).abs() < 0.15,
        "Expected ~1.5x, got {:.3}x",
        ratio
    );
    assert!(output.peak() > 0.01, "Output should not be silent");
}

#[test]
fn test_stretch_then_slice() {
    // Stretch a full buffer, then slice the output
    let input = sine_mono(220.0, 44100, 22050); // 0.5s
    let params = StretchParams::new(2.0)
        .with_sample_rate(44100)
        .with_channels(1)
        .with_preset(EdmPreset::Halftime);
    let stretched = timestretch::stretch_buffer(&input, &params).unwrap();

    // Slice first and second half
    let half_len = stretched.num_frames() / 2;
    let first_half = stretched.slice(0, half_len);
    let second_half = stretched.slice(half_len, half_len);

    assert!(first_half.peak() > 0.01);
    assert!(second_half.peak() > 0.01);
    assert_eq!(
        first_half.num_frames() + second_half.num_frames(),
        half_len * 2
    );
}

// ==================== CONCATENATE + STRETCH ====================

#[test]
fn test_concatenate_then_stretch() {
    // Join two different-frequency segments, then stretch
    let low = sine_mono(110.0, 44100, 11025); // 0.25s at 110 Hz
    let high = sine_mono(880.0, 44100, 11025); // 0.25s at 880 Hz
    let combined = AudioBuffer::concatenate(&[&low, &high]);
    assert_eq!(combined.num_frames(), 22050);

    let params = StretchParams::new(1.2)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch_buffer(&combined, &params).unwrap();

    assert!(!output.is_empty());
    assert!(output.peak() > 0.01);
}

#[test]
fn test_stretch_then_concatenate() {
    // Stretch two segments independently, then join
    let a = sine_mono(440.0, 44100, 22050);
    let b = sine_mono(220.0, 44100, 22050);

    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);

    let stretched_a = timestretch::stretch_buffer(&a, &params).unwrap();
    let stretched_b = timestretch::stretch_buffer(&b, &params).unwrap();

    let combined = AudioBuffer::concatenate(&[&stretched_a, &stretched_b]);
    assert_eq!(
        combined.num_frames(),
        stretched_a.num_frames() + stretched_b.num_frames()
    );
    assert!(combined.peak() > 0.01);
}

// ==================== NORMALIZE + STRETCH ====================

#[test]
fn test_normalize_before_stretch() {
    // Normalize a quiet signal, then stretch
    let quiet = AudioBuffer::from_mono(
        (0..22050)
            .map(|i| 0.1 * (2.0 * std::f32::consts::PI * 440.0 * i as f32 / 44100.0).sin())
            .collect(),
        44100,
    );
    assert!(quiet.peak() < 0.15);

    let normalized = quiet.normalize(1.0);
    assert!((normalized.peak() - 1.0).abs() < 1e-4);

    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch_buffer(&normalized, &params).unwrap();

    assert!(!output.is_empty());
    // Output should have significant energy since input was normalized
    assert!(
        output.rms() > 0.1,
        "Normalized input should produce loud output"
    );
}

#[test]
fn test_stretch_then_normalize() {
    let input = sine_mono(440.0, 44100, 22050);
    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);
    let stretched = timestretch::stretch_buffer(&input, &params).unwrap();

    let normalized = stretched.normalize(0.5);
    assert!((normalized.peak() - 0.5).abs() < 1e-4);
}

// ==================== FADE + STRETCH ====================

#[test]
fn test_fade_in_out_then_stretch() {
    let input = sine_mono(440.0, 44100, 44100); // 1 second
    let faded = input.fade_in(4410).fade_out(4410); // 100ms fades

    // First samples should be near zero, middle should have content
    assert!(faded.data[0].abs() < 0.01);
    // Middle of faded region should have significant energy
    let mid_rms = AudioBuffer::from_mono(faded.data[20000..24000].to_vec(), 44100).rms();
    assert!(
        mid_rms > 0.3,
        "Middle region RMS should be significant: {}",
        mid_rms
    );

    let params = StretchParams::new(1.0)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch_buffer(&faded, &params).unwrap();

    assert!(!output.is_empty());
}

#[test]
fn test_stretch_then_fade() {
    let input = sine_mono(440.0, 44100, 22050);
    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);
    let stretched = timestretch::stretch_buffer(&input, &params).unwrap();

    let fade_frames = stretched.num_frames() / 10;
    let faded = stretched.fade_in(fade_frames).fade_out(fade_frames);

    // First sample should be zero (fade in starts at 0)
    assert!(faded.data[0].abs() < 1e-6);
    // Last sample should be near zero (fade out ends at 0)
    assert!(faded.data[faded.data.len() - 1].abs() < 0.1);
}

// ==================== TRIM SILENCE + STRETCH ====================

#[test]
fn test_trim_silence_after_stretch() {
    // Stretch a signal with leading/trailing silence
    let mut data = vec![0.0f32; 4410]; // 100ms silence
    data.extend(
        (0..22050).map(|i| (2.0 * std::f32::consts::PI * 440.0 * i as f32 / 44100.0).sin()),
    );
    data.extend(vec![0.0f32; 4410]); // 100ms silence
    let input = AudioBuffer::from_mono(data, 44100);

    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(1);
    let stretched = timestretch::stretch_buffer(&input, &params).unwrap();
    let trimmed = stretched.trim_silence(0.01);

    // Trimmed should be shorter (silence removed)
    assert!(
        trimmed.num_frames() < stretched.num_frames(),
        "Trimming should reduce frame count"
    );
    // But still have content
    assert!(trimmed.peak() > 0.1);
}

// ==================== PEAK / RMS + STRETCH ====================

#[test]
fn test_rms_preserved_after_identity_stretch() {
    let input = sine_mono(440.0, 44100, 22050);
    let input_rms = input.rms();

    let params = StretchParams::new(1.0)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch_buffer(&input, &params).unwrap();
    let output_rms = output.rms();

    // RMS should be roughly preserved at identity ratio
    let ratio = output_rms / input_rms;
    assert!(
        (ratio - 1.0).abs() < 0.3,
        "RMS should be roughly preserved: ratio={}",
        ratio
    );
}

#[test]
fn test_peak_gain_roundtrip() {
    let input = sine_mono(440.0, 44100, 22050);
    let original_peak = input.peak();

    // Apply -6dB, then normalize back
    let quieter = input.apply_gain(-6.0);
    assert!(quieter.peak() < original_peak);

    let restored = quieter.normalize(original_peak);
    assert!((restored.peak() - original_peak).abs() < 1e-4);
}

// ==================== FRAMES ITERATOR + STRETCH ====================

#[test]
fn test_frames_iterator_with_stereo_stretch() {
    let input = sine_stereo(440.0, 44100, 22050);
    let params = StretchParams::new(1.5)
        .with_sample_rate(44100)
        .with_channels(2);
    let output = timestretch::stretch_buffer(&input, &params).unwrap();

    // Iterate frames and verify each is stereo
    let mut frame_count = 0;
    for frame in &output {
        assert_eq!(frame.len(), 2, "Each stereo frame should have 2 samples");
        assert!(frame[0].is_finite());
        assert!(frame[1].is_finite());
        frame_count += 1;
    }
    assert_eq!(frame_count, output.num_frames());
}

#[test]
fn test_frames_iterator_peak_matches() {
    let input = sine_mono(440.0, 44100, 22050);
    let params = StretchParams::new(1.2)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch_buffer(&input, &params).unwrap();

    // Compute peak manually via frames iterator
    let manual_peak = output.frames().map(|f| f[0].abs()).fold(0.0f32, f32::max);
    assert!((manual_peak - output.peak()).abs() < 1e-6);
}

// ==================== AS_REF + PARTIAL_EQ ====================

#[test]
fn test_as_ref_interop() {
    let input = sine_mono(440.0, 44100, 22050);
    let slice: &[f32] = input.as_ref();

    // Verify we can pass the slice to stretch directly
    let params = StretchParams::new(1.0)
        .with_sample_rate(44100)
        .with_channels(1);
    let output = timestretch::stretch(slice, &params).unwrap();
    assert!(!output.is_empty());
}

#[test]
fn test_partial_eq_after_clone_and_modify() {
    let a = sine_mono(440.0, 44100, 22050);
    let b = a.clone();
    assert_eq!(a, b);

    // After applying gain, they should differ
    let c = a.apply_gain(6.0);
    assert_ne!(a, c);
}

// ==================== COMPLEX WORKFLOW ====================

#[test]
fn test_dj_crossfade_workflow() {
    // Simulate a DJ crossfade: stretch two tracks, fade them, merge
    let track_a = sine_mono(440.0, 44100, 44100); // 1s at 440 Hz
    let track_b = sine_mono(330.0, 44100, 44100); // 1s at 330 Hz

    let params = StretchParams::new(126.0 / 128.0) // slight tempo adjust
        .with_sample_rate(44100)
        .with_channels(1)
        .with_preset(EdmPreset::DjBeatmatch);

    let a_stretched = timestretch::stretch_buffer(&track_a, &params).unwrap();
    let b_stretched = timestretch::stretch_buffer(&track_b, &params).unwrap();

    // Fade out track A, fade in track B
    let crossfade_frames = a_stretched.num_frames().min(b_stretched.num_frames()) / 4;
    let a_faded = a_stretched.fade_out(crossfade_frames);
    let b_faded = b_stretched.fade_in(crossfade_frames);

    assert!(a_faded.peak() > 0.01);
    assert!(b_faded.peak() > 0.01);
}

#[test]
fn test_sample_chop_workflow() {
    // Simulate chopping a sample: slice, stretch, normalize, fade
    let full_sample = sine_mono(220.0, 44100, 88200); // 2 seconds

    // Chop out 4 equal slices
    let frames_per_chop = full_sample.num_frames() / 4;
    let chops: Vec<AudioBuffer> = (0..4)
        .map(|i| full_sample.slice(i * frames_per_chop, frames_per_chop))
        .collect();

    // Stretch each chop to 2x (halftime effect)
    let params = StretchParams::new(2.0)
        .with_sample_rate(44100)
        .with_channels(1)
        .with_preset(EdmPreset::Halftime);

    let stretched_chops: Vec<AudioBuffer> = chops
        .iter()
        .map(|c| timestretch::stretch_buffer(c, &params).unwrap())
        .collect();

    // Normalize each to 0.8 peak
    let normalized: Vec<AudioBuffer> = stretched_chops.iter().map(|c| c.normalize(0.8)).collect();

    // Add fades
    let faded: Vec<AudioBuffer> = normalized
        .iter()
        .map(|c| {
            let fade = c.num_frames() / 20; // 5% fade
            c.fade_in(fade).fade_out(fade)
        })
        .collect();

    // Concatenate back together
    let refs: Vec<&AudioBuffer> = faded.iter().collect();
    let result = AudioBuffer::concatenate(&refs);

    assert!(result.num_frames() > full_sample.num_frames()); // Stretched 2x
                                                             // Peak should be <= 0.8 (normalized) but may be lower due to fade placement.
                                                             // The exact peak depends on where the strongest sample falls relative to
                                                             // fade regions, which varies with transient detection weights.
    assert!(
        result.peak() > 0.1 && result.peak() <= 0.81,
        "Peak {} should be in (0.1, 0.81]",
        result.peak()
    );
    assert!(result.rms() > 0.01); // Has content
}

#[test]
fn test_channels_from_count_in_params() {
    // Use Channels::from_count in a real workflow
    let channels = Channels::from_count(2).unwrap();
    assert_eq!(channels, Channels::Stereo);

    let params = StretchParams::new(1.0)
        .with_sample_rate(44100)
        .with_channels(channels.count() as u32);
    assert_eq!(params.channels, Channels::Stereo);
}