scal-runtime 1.3.1

Runtime for SCAL- easy animation system focused on code.
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
use crate::{anim_op::AnimOperation, types::Seconds};
use anyhow::{Context, Result};
use ffmpeg_next as ffmpeg;
use log::debug;

pub const OUTPUT_SAMPLE_RATE: u32 = 48000;
const MAX_AUDIO_DURATION: Seconds = 3600.0;

#[derive(Clone, Debug)]
pub struct ScheduledSound {
    pub path: String,
    pub volume: f32,
    pub pitch: f32,
    pub start_time: Seconds,
    pub seek_offset: Seconds,
    pub duration: Seconds,
    pub source_loc: Option<scal_core::SourceLoc>,
}

pub struct AudioEngine {
    sounds: Vec<ScheduledSound>,
}

impl AudioEngine {
    pub fn new(sounds: Vec<ScheduledSound>) -> Self {
        Self { sounds }
    }

    pub fn is_empty(&self) -> bool {
        self.sounds.is_empty()
    }

    pub fn mix(&self) -> Result<Vec<f32>> {
        if self.sounds.is_empty() {
            return Ok(vec![]);
        }

        let mut decoded_sounds: Vec<(Vec<f32>, Seconds, f32)> = vec![];
        let mut total_duration = 0.0_f32;

        for sound in &self.sounds {
            debug!("mixing sound: {} at t={}", sound.path, sound.start_time);
            let samples = self.decode_and_transform(sound)?;
            let peak = samples.iter().map(|s| s.abs()).fold(0.0_f32, f32::max);
            debug!("  decoded peak={}, len={}", peak, samples.len());
            if samples.is_empty() {
                debug!("  -> decoded empty, skipping");
                continue;
            }
            let actual_duration = (samples.len() / 2) as Seconds / OUTPUT_SAMPLE_RATE as Seconds;
            let end = sound.start_time + actual_duration;
            if end > total_duration {
                total_duration = end;
            }
            decoded_sounds.push((samples, sound.start_time.max(0.0), sound.volume));
            debug!(
                "  scheduled at t={} with volume={}",
                sound.start_time.max(0.0),
                sound.volume
            );
        }

        if total_duration <= 0.0 {
            return Ok(vec![]);
        }
        total_duration = total_duration.min(MAX_AUDIO_DURATION);
        let total_samples = (total_duration * OUTPUT_SAMPLE_RATE as f32).ceil() as usize;
        let mut mix_buffer = vec![0.0_f32; total_samples * 2];

        for (samples, start_time, volume) in &decoded_sounds {
            let start_frame = (start_time * OUTPUT_SAMPLE_RATE as f32) as usize;
            if start_frame >= total_samples {
                continue;
            }
            let start_sample = start_frame * 2;
            for (i, &sample) in samples.iter().enumerate() {
                let mix_idx = start_sample + i;
                if mix_idx >= total_samples * 2 {
                    break;
                }
                mix_buffer[mix_idx] = (mix_buffer[mix_idx] + sample * volume).clamp(-1.0, 1.0);
            }
        }

        Ok(mix_buffer)
    }

    fn decode_and_transform(&self, sound: &ScheduledSound) -> Result<Vec<f32>> {
        let mut ictx = ffmpeg::format::input(&sound.path)
            .with_context(|| format!("failed to open audio file: {}", sound.path))?;

        let input_stream = ictx
            .streams()
            .best(ffmpeg::media::Type::Audio)
            .context("no audio stream found")?;

        let input_stream_index = input_stream.index();
        let codec = ffmpeg::codec::context::Context::from_parameters(input_stream.parameters())?;
        let mut decoder = codec
            .decoder()
            .audio()
            .context("failed to create audio decoder")?;

        let mut pcm_stereo: Vec<f32> = vec![];
        let codec_name = input_stream.parameters().id().name();
        let is_pcm = codec_name.starts_with("pcm_");

        if is_pcm {
            let mut src_f32: Vec<f32> = vec![];
            let src_rate = decoder.rate();
            let channels = decoder.channels() as usize;

            for (stream, packet) in ictx.packets() {
                if stream.index() != input_stream_index {
                    continue;
                }
                decoder.send_packet(&packet)?;

                let mut decoded = ffmpeg::frame::Audio::empty();
                while decoder.receive_frame(&mut decoded).is_ok() {
                    push_pcm_samples_as_f32(&decoded, &mut src_f32)?;
                }
            }

            decoder.send_eof()?;
            let mut remaining = ffmpeg::frame::Audio::empty();
            while decoder.receive_frame(&mut remaining).is_ok() {
                push_pcm_samples_as_f32(&remaining, &mut src_f32)?;
            }

            pcm_stereo = resample_linear(&src_f32, src_rate, OUTPUT_SAMPLE_RATE, channels);
        } else {
            let mut resampler: Option<ffmpeg::software::resampling::Context> = None;

            for (stream, packet) in ictx.packets() {
                if stream.index() != input_stream_index {
                    continue;
                }
                decoder.send_packet(&packet)?;

                let mut decoded = ffmpeg::frame::Audio::empty();
                loop {
                    match decoder.receive_frame(&mut decoded) {
                        Ok(()) => {
                            if resampler.is_none() {
                                let input_ch_layout = if decoded.channel_layout().is_empty() {
                                    ffmpeg::ChannelLayout::default(decoded.channels() as i32)
                                } else {
                                    decoded.channel_layout()
                                };
                                resampler = Some(ffmpeg::software::resampling::Context::get(
                                    decoded.format(),
                                    input_ch_layout,
                                    decoded.rate(),
                                    ffmpeg::format::Sample::F32(
                                        ffmpeg::format::sample::Type::Packed,
                                    ),
                                    ffmpeg::ChannelLayout::default(2),
                                    OUTPUT_SAMPLE_RATE,
                                )?);
                            }
                            let rsmpl = resampler
                                .as_mut()
                                .expect("resampler was just initialized above");
                            let mut converted = ffmpeg::frame::Audio::empty();
                            let converted_valid = match rsmpl.run(&decoded, &mut converted) {
                                Ok(_) => true,
                                Err(ffmpeg::Error::InputChanged) => {
                                    let input_ch_layout = if decoded.channel_layout().is_empty() {
                                        ffmpeg::ChannelLayout::default(decoded.channels() as i32)
                                    } else {
                                        decoded.channel_layout()
                                    };
                                    if let Ok(new_rsmpl) =
                                        ffmpeg::software::resampling::Context::get(
                                            decoded.format(),
                                            input_ch_layout,
                                            decoded.rate(),
                                            ffmpeg::format::Sample::F32(
                                                ffmpeg::format::sample::Type::Packed,
                                            ),
                                            ffmpeg::ChannelLayout::default(2),
                                            OUTPUT_SAMPLE_RATE,
                                        )
                                    {
                                        *rsmpl = new_rsmpl;
                                        rsmpl.run(&decoded, &mut converted).is_ok()
                                    } else {
                                        false
                                    }
                                }
                                Err(_) => false,
                            };

                            if converted_valid {
                                let n = converted.samples();
                                let data = converted.data(0);
                                let float_data = unsafe {
                                    std::slice::from_raw_parts(data.as_ptr() as *const f32, n * 2)
                                };
                                pcm_stereo.extend_from_slice(float_data);
                            }
                        }
                        Err(ffmpeg::Error::Eof) => break,
                        Err(_) => break,
                    }
                }
            }

            decoder.send_eof()?;
            let mut remaining = ffmpeg::frame::Audio::empty();
            loop {
                match decoder.receive_frame(&mut remaining) {
                    Ok(()) => {
                        if let Some(rsmpl) = resampler.as_mut() {
                            let mut converted = ffmpeg::frame::Audio::empty();
                            let converted_valid = match rsmpl.run(&remaining, &mut converted) {
                                Ok(_) => true,
                                Err(ffmpeg::Error::InputChanged) => {
                                    let input_ch_layout = if remaining.channel_layout().is_empty() {
                                        ffmpeg::ChannelLayout::default(remaining.channels() as i32)
                                    } else {
                                        remaining.channel_layout()
                                    };
                                    if let Ok(new_rsmpl) =
                                        ffmpeg::software::resampling::Context::get(
                                            remaining.format(),
                                            input_ch_layout,
                                            remaining.rate(),
                                            ffmpeg::format::Sample::F32(
                                                ffmpeg::format::sample::Type::Packed,
                                            ),
                                            ffmpeg::ChannelLayout::default(2),
                                            OUTPUT_SAMPLE_RATE,
                                        )
                                    {
                                        *rsmpl = new_rsmpl;
                                        rsmpl.run(&remaining, &mut converted).is_ok()
                                    } else {
                                        false
                                    }
                                }
                                Err(_) => false,
                            };

                            if converted_valid {
                                let n = converted.samples();
                                let data = converted.data(0);
                                let float_data = unsafe {
                                    std::slice::from_raw_parts(data.as_ptr() as *const f32, n * 2)
                                };
                                pcm_stereo.extend_from_slice(float_data);
                            }
                        }
                    }
                    Err(ffmpeg::Error::Eof) => break,
                    Err(_) => break,
                }
            }
        }

        if pcm_stereo.is_empty() {
            return Ok(vec![]);
        }

        let total_frames = pcm_stereo.len() / 2;
        if sound.seek_offset > 0.0 {
            let seek_frames = (sound.seek_offset * OUTPUT_SAMPLE_RATE as f32) as usize;
            if seek_frames >= total_frames {
                return Ok(vec![]);
            }
            if sound.duration > 0.0 {
                let dur_frames = (sound.duration * OUTPUT_SAMPLE_RATE as f32) as usize;
                if seek_frames + dur_frames > total_frames {
                    return Ok(vec![]);
                }
            }
            let skip = seek_frames * 2;
            pcm_stereo.drain(0..skip);
        }

        let mut pcm_stereo = apply_pitch_and_volume(pcm_stereo, sound.pitch, 1.0);

        if sound.duration > 0.0 {
            let target_samples = (sound.duration * OUTPUT_SAMPLE_RATE as f32) as usize * 2;
            if pcm_stereo.len() > target_samples {
                pcm_stereo.truncate(target_samples);
            }
        }

        Ok(pcm_stereo)
    }
}

fn pcm_integer_scale(format: ffmpeg::format::Sample) -> f32 {
    let bits = match format {
        ffmpeg::format::Sample::I16(_) => 16,
        ffmpeg::format::Sample::I32(_) => 32,
        ffmpeg::format::Sample::I64(_) => 64,
        ffmpeg::format::Sample::U8(_) => 8,
        _ => 32,
    };
    let max = if bits == 64 {
        (1_i64 << (bits - 1)) as f32
    } else {
        (1_i32 << (bits - 1)) as f32
    };
    1.0 / max
}

fn push_pcm_samples_as_f32(decoded: &ffmpeg::frame::Audio, out: &mut Vec<f32>) -> Result<()> {
    let n = decoded.samples();
    let channels = decoded.channels() as usize;
    let format = decoded.format();

    if channels == 0 || n == 0 {
        return Ok(());
    }

    if format.is_planar() {
        let scale = pcm_integer_scale(format);
        for i in 0..n {
            for ch in 0..channels {
                let data = decoded.data(ch);
                let sample = match format {
                    ffmpeg::format::Sample::I16(_) => {
                        let slice =
                            unsafe { std::slice::from_raw_parts(data.as_ptr() as *const i16, n) };
                        slice[i] as f32 * scale
                    }
                    ffmpeg::format::Sample::I32(_) => {
                        let slice =
                            unsafe { std::slice::from_raw_parts(data.as_ptr() as *const i32, n) };
                        slice[i] as f32 * scale
                    }
                    ffmpeg::format::Sample::I64(_) => {
                        let slice =
                            unsafe { std::slice::from_raw_parts(data.as_ptr() as *const i64, n) };
                        slice[i] as f32 * scale
                    }
                    ffmpeg::format::Sample::U8(_) => {
                        let slice =
                            unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, n) };
                        (slice[i] as f32 - 128.0) / 128.0
                    }
                    ffmpeg::format::Sample::F32(_) => {
                        let slice =
                            unsafe { std::slice::from_raw_parts(data.as_ptr() as *const f32, n) };
                        slice[i]
                    }
                    ffmpeg::format::Sample::F64(_) => {
                        let slice =
                            unsafe { std::slice::from_raw_parts(data.as_ptr() as *const f64, n) };
                        slice[i] as f32
                    }
                    _ => anyhow::bail!("unsupported planar PCM sample format: {:?}", format),
                };
                out.push(sample);
            }
        }
    } else {
        let data = decoded.data(0);
        match format {
            ffmpeg::format::Sample::I16(_) => {
                let scale = pcm_integer_scale(format);
                let samples = unsafe {
                    std::slice::from_raw_parts(data.as_ptr() as *const i16, n * channels)
                };
                for &s in samples {
                    out.push(s as f32 * scale);
                }
            }
            ffmpeg::format::Sample::I32(_) => {
                let scale = pcm_integer_scale(format);
                let samples = unsafe {
                    std::slice::from_raw_parts(data.as_ptr() as *const i32, n * channels)
                };
                for &s in samples {
                    out.push(s as f32 * scale);
                }
            }
            ffmpeg::format::Sample::I64(_) => {
                let scale = pcm_integer_scale(format);
                let samples = unsafe {
                    std::slice::from_raw_parts(data.as_ptr() as *const i64, n * channels)
                };
                for &s in samples {
                    out.push(s as f32 * scale);
                }
            }
            ffmpeg::format::Sample::U8(_) => {
                let samples =
                    unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, n * channels) };
                for &s in samples {
                    out.push((s as f32 - 128.0) / 128.0);
                }
            }
            ffmpeg::format::Sample::F32(_) => {
                let samples = unsafe {
                    std::slice::from_raw_parts(data.as_ptr() as *const f32, n * channels)
                };
                out.extend_from_slice(samples);
            }
            ffmpeg::format::Sample::F64(_) => {
                let samples = unsafe {
                    std::slice::from_raw_parts(data.as_ptr() as *const f64, n * channels)
                };
                for &s in samples {
                    out.push(s as f32);
                }
            }
            _ => anyhow::bail!("unsupported packed PCM sample format: {:?}", format),
        }
    }

    Ok(())
}

fn resample_linear(src: &[f32], src_rate: u32, dst_rate: u32, channels: usize) -> Vec<f32> {
    if src_rate == dst_rate || src.is_empty() || channels == 0 {
        return src.to_vec();
    }
    let src_frames = src.len() / channels;
    let dst_frames = (src_frames as f64 * dst_rate as f64 / src_rate as f64).ceil() as usize;
    let mut dst = vec![0.0_f32; dst_frames * channels];
    for i in 0..dst_frames {
        let t = i as f64 * src_rate as f64 / dst_rate as f64;
        let src_i = t as usize;
        let frac = (t - src_i as f64) as f32;
        let src_i = src_i.min(src_frames.saturating_sub(1));
        let src_j = (src_i + 1).min(src_frames.saturating_sub(1));
        for ch in 0..channels {
            let a = src[src_i * channels + ch];
            let b = src[src_j * channels + ch];
            dst[i * channels + ch] = a + (b - a) * frac;
        }
    }
    dst
}

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

    #[test]
    fn pitch_volume_identity() {
        let samples = vec![0.5, -0.3, 0.1, 0.0];
        let result = apply_pitch_and_volume(samples.clone(), 1.0, 1.0);
        assert_eq!(result, samples);
    }

    #[test]
    fn volume_only() {
        let samples = vec![0.5, -0.3];
        let result = apply_pitch_and_volume(samples, 1.0, 0.5);
        assert_eq!(result, vec![0.25, -0.15]);
    }

    #[test]
    fn zero_volume() {
        let samples = vec![1.0, -1.0, 0.5, -0.5];
        let result = apply_pitch_and_volume(samples, 1.0, 0.0);
        assert_eq!(result, vec![0.0, 0.0, 0.0, 0.0]);
    }

    #[test]
    fn pitch_double_speed_half_frames() {
        let samples = vec![1.0, 0.0, 0.0, 1.0, 0.5, 0.5];
        let result = apply_pitch_and_volume(samples, 2.0, 1.0);
        assert_eq!(result.len(), 2);
        assert!((result[0] - 1.0).abs() < f32::EPSILON);
        assert!((result[1] - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn pitch_half_speed_interpolates() {
        let samples = vec![1.0, 0.0, 0.0, 1.0, 0.5, 0.5];
        let result = apply_pitch_and_volume(samples, 0.5, 1.0);
        assert_eq!(
            result.len(),
            8,
            "expected 4 stereo frames, got {}",
            result.len()
        );
        assert!((result[0] - 1.0).abs() < f32::EPSILON);
        assert!((result[1] - 0.0).abs() < f32::EPSILON);
        assert!((result[2] - 0.5).abs() < f32::EPSILON);
        assert!((result[3] - 0.5).abs() < f32::EPSILON);
        assert!((result[4] - 0.0).abs() < f32::EPSILON);
        assert!((result[5] - 1.0).abs() < f32::EPSILON);
        assert!((result[6] - 0.25).abs() < f32::EPSILON);
        assert!((result[7] - 0.75).abs() < 0.01);
    }

    #[test]
    fn pitch_and_volume_combined() {
        let samples = vec![1.0, -1.0];
        let result = apply_pitch_and_volume(samples, 1.0, 0.5);
        assert_eq!(result, vec![0.5, -0.5]);
    }

    #[test]
    fn empty_input() {
        let result = apply_pitch_and_volume(vec![], 1.0, 1.0);
        assert!(result.is_empty());
        let result = apply_pitch_and_volume(vec![], 0.5, 2.0);
        assert!(result.is_empty());
    }
}

/// Downsample PCM stereo data to `num_samples` amplitude values (0.0–1.0).
/// Each output value is the peak absolute amplitude in its corresponding time slice.
pub fn compute_waveform(pcm: &[f32], num_samples: usize) -> Vec<f32> {
    if pcm.is_empty() || num_samples == 0 {
        return vec![];
    }
    let total_frames = pcm.len() / 2;
    let mut waveform = Vec::with_capacity(num_samples);
    for i in 0..num_samples {
        let start_frame = (i as f64 * total_frames as f64 / num_samples as f64) as usize;
        let end_frame = ((i + 1) as f64 * total_frames as f64 / num_samples as f64) as usize;
        let mut peak = 0.0_f32;
        for f in start_frame..end_frame.min(total_frames) {
            let l = pcm[f * 2].abs();
            let r = pcm[f * 2 + 1].abs();
            let max = l.max(r);
            if max > peak {
                peak = max;
            }
        }
        waveform.push(peak);
    }
    waveform
}

/// Collect [`ScheduledSound`]s from a list of [`AnimOperation`]s.
/// Applies pitch variation when `pitch_variation > 0`.
pub fn collect_sounds_from_ops(ops: &[AnimOperation]) -> Vec<ScheduledSound> {
    fn end_time(op: &AnimOperation, t: f32, out: &mut Vec<ScheduledSound>) -> f32 {
        match op {
            AnimOperation::PlaySound(sfx, delay, source_loc) => {
                let abs_time = t + delay;
                let pitch = if sfx.pitch_variation > 0.0 {
                    use rand::Rng;
                    let mut rng = rand::thread_rng();
                    let variation = rng.gen_range(-sfx.pitch_variation..sfx.pitch_variation);
                    sfx.pitch * (1.0 + variation)
                } else {
                    sfx.pitch
                };
                let scheduled = ScheduledSound {
                    path: sfx.path.clone(),
                    volume: sfx.volume,
                    pitch,
                    start_time: abs_time,
                    seek_offset: sfx.time_offset,
                    duration: sfx.duration,
                    source_loc: source_loc.clone(),
                };
                out.push(scheduled);
                t
            }
            AnimOperation::All(children, _) => {
                let mut max_end = t;
                for child in children {
                    let end = end_time(child, t, out);
                    if end > max_end {
                        max_end = end;
                    }
                }
                max_end
            }
            AnimOperation::Sequence(children, _) => {
                let mut time = t;
                for child in children {
                    time = end_time(child, time, out);
                }
                time
            }
            AnimOperation::Wait(d, _) => t + d,
            AnimOperation::TransformMovePos(_, _, d, _, _)
            | AnimOperation::TransformMoveToObj(_, _, _, d, _, _)
            | AnimOperation::TransformRotate(_, _, d, _, _)
            | AnimOperation::TransformScale(_, _, d, _, _)
            | AnimOperation::CodeAddLines(_, _, _, d, _, _, _)
            | AnimOperation::CodeModifyLine(_, _, _, d, _, _, _)
            | AnimOperation::CodeRemoveLines(_, _, d, _, _, _)
            | AnimOperation::TerminalTypeInput(_, _, _, _, _, d, _, _, _)
            | AnimOperation::TerminalOutput(_, _, d, _, _, _)
            | AnimOperation::ObjectColor(_, _, d, _, _) => t + d,
            AnimOperation::MathPartColor(_, _, _, d, _, _) => t + d,
            AnimOperation::MathHighlight(_, _, _, _, d, _, _) => t + d,
            AnimOperation::ScrollOffset(_, _, d, _, _) => t + d,
            AnimOperation::NumberTo(_, _, _, d, _, _) => t + d,
            AnimOperation::CodeHighlight(_, action, _) => t + action.duration_and_curve().0,
            AnimOperation::Instantiate(..) => t,
        }
    }
    let mut sounds = vec![];
    let mut t = 0.0;
    for op in ops {
        t = end_time(op, t, &mut sounds);
    }
    sounds
}

fn apply_pitch_and_volume(samples: Vec<f32>, pitch: f32, volume: f32) -> Vec<f32> {
    if (pitch - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON {
        return samples;
    }

    if (pitch - 1.0).abs() < f32::EPSILON {
        return samples.iter().map(|&s| s * volume).collect();
    }

    let input_len = samples.len() / 2;
    let ratio = 1.0 / pitch;
    let output_len = (input_len as f32 * ratio) as usize;
    let mut out = Vec::with_capacity(output_len * 2);

    for i in 0..output_len {
        let src_f = i as f32 * pitch;
        let src_i = src_f as usize;
        let frac = src_f - src_i as f32;

        if src_i + 1 >= input_len {
            break;
        }

        let si = src_i * 2;
        let l = samples[si] * (1.0 - frac) + samples[si + 2] * frac;
        let r = samples[si + 1] * (1.0 - frac) + samples[si + 3] * frac;
        out.push(l * volume);
        out.push(r * volume);
    }

    out
}