neteq 0.8.3

NetEQ-inspired adaptive jitter buffer for audio decoding
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
/*
 * Copyright 2025 Security Union LLC
 *
 * Licensed under either of
 *
 * * Apache License, Version 2.0
 *   (http://www.apache.org/licenses/LICENSE-2.0)
 * * MIT license
 *   (http://opensource.org/licenses/MIT)
 *
 * at your option.
 *
 * Unless you explicitly state otherwise, any contribution intentionally
 * submitted for inclusion in the work by you, as defined in the Apache-2.0
 * license, shall be dual licensed as above, without any additional terms or
 * conditions.
 */

const ENERGY_THRESHOLD_DECREASE_FACTOR: f32 = 0.995;
const ENERGY_THRESHOLD_INCREASE_FACTOR: f32 = 1.002;

/// Return codes for time-stretching operations
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimeStretchResult {
    Success,
    SuccessLowEnergy,
    NoStretch,
    Error,
}

/// Audio time-stretching processor
pub trait TimeStretcher {
    /// Process audio samples and return the result
    fn process(&mut self, input: &[f32], output: &mut [f32], fast_mode: bool) -> TimeStretchResult;

    // Returns the number of input samples used in the last operation
    fn get_used_input_samples(&self) -> usize;

    /// Reset the time stretcher state
    fn reset(&mut self);
}

/// Accelerate algorithm - removes audio samples to speed up playback
#[derive(Debug)]
pub struct Accelerate {
    _sample_rate: u32,
    _channels: u8,
    used_input_samples: usize,
    overlap_length: usize,
    _max_change_rate: f32,
    low_energy_threshold: f32,
}

impl Accelerate {
    /// Create a new accelerate processor
    pub fn new(sample_rate: u32, channels: u8) -> Self {
        Self {
            _sample_rate: sample_rate,
            _channels: channels,
            used_input_samples: 0,
            overlap_length: Self::calculate_overlap_length(sample_rate),
            _max_change_rate: 0.25, // Maximum 25% reduction
            low_energy_threshold: 0.0001,
        }
    }

    fn calculate_overlap_length(sample_rate: u32) -> usize {
        // Calculate overlap length based on sample rate (typically 4-6ms)
        ((sample_rate as f32 * 0.003) as usize).max(32) // Minimum 32 samples
    }

    /// Accelerate the audio by removing samples
    fn accelerate_internal(
        &mut self,
        input: &[f32],
        output: &mut [f32],
        fast_mode: bool,
    ) -> TimeStretchResult {
        if input.len() <= output.len() {
            // Input should always be longer then output for accelerate
            output[..input.len()].copy_from_slice(input);
            self.used_input_samples = input.len();
            return TimeStretchResult::NoStretch;
        }

        if output.len() < self.overlap_length * 2 {
            // Not enough samples to accelerate
            output.copy_from_slice(&input[..output.len()]);
            self.used_input_samples = output.len();
            return TimeStretchResult::NoStretch;
        }

        let max_remove_low_energy = if fast_mode {
            self.max_samples_to_remove(input, output, 0.4)
        } else {
            self.max_samples_to_remove(input, output, 0.2)
        };
        let max_remove_high_energy = if fast_mode {
            self.max_samples_to_remove(input, output, 0.25)
        } else {
            // Don't use high energy remove in normal mode
            0
        };

        let (mut best_pos, mut samples_to_remove) =
            self.find_low_energy_to_remove(input, output, max_remove_low_energy);

        let mut is_low_energy = true;
        if !fast_mode {
            if samples_to_remove == 0 {
                // If no low-energy zone found, don't remove anything in normal mode
                output.copy_from_slice(&input[..output.len()]);
                self.used_input_samples = output.len();
                return TimeStretchResult::NoStretch;
            }
        } else if samples_to_remove < max_remove_high_energy {
            // In fast mode, always remove at least max_remove_high_energy samples
            is_low_energy = false;
            samples_to_remove = max_remove_high_energy;

            // Find the best location to remove samples (lowest energy region)
            best_pos = self.find_best_removal_point(
                &input[..output.len() + samples_to_remove],
                samples_to_remove,
            );
        }

        let usable_input = &input[..output.len() + samples_to_remove];

        // original samples: 12346789
        // samples_to_remove = 4, overlap_length = 2
        // original:     |123456789|
        // head+overlap: |1234 | // head_length = 2
        // overlap+tail: |  789| // tail_start = 6
        // result:       |12**9| // 2 samples overlapped
        // head_length+overlap_length+(usable_input.len()-tail_start-overlap_length) = output.len()
        // head_length+usable_input.len()-tail_start = output.len()
        // tail_start= head_length+usable_input.len()-output.len() = head_length+(output.len()+samples_to_remove)-output.len() = head_length+samples_to_remove

        // Copy the first part
        output[..best_pos].copy_from_slice(&usable_input[..best_pos]);

        crate::signal::crossfade(
            &usable_input[best_pos..best_pos + self.overlap_length],
            &usable_input
                [best_pos + samples_to_remove..best_pos + samples_to_remove + self.overlap_length],
            self.overlap_length,
            &mut output[best_pos..best_pos + self.overlap_length],
        );

        // Copy the rest
        output[best_pos + self.overlap_length..]
            .copy_from_slice(&usable_input[best_pos + samples_to_remove + self.overlap_length..]);

        self.used_input_samples = usable_input.len();

        if is_low_energy {
            TimeStretchResult::SuccessLowEnergy
        } else {
            TimeStretchResult::Success
        }
    }

    fn max_samples_to_remove(
        &mut self,
        input: &[f32],
        output: &[f32],
        acceleration_factor: f32,
    ) -> usize {
        let max_remove = (output.len() as f32 * acceleration_factor) as usize;
        let max_remove = max_remove.min(output.len() / 2); // Don't remove more than 1/3 of input (= 1/2 of output)
        let max_remove = max_remove.min(input.len() - output.len());
        max_remove.max(self.overlap_length)
    }

    fn find_low_energy_to_remove(
        &mut self,
        input: &[f32],
        output: &mut [f32],
        max_remove: usize,
    ) -> (usize, usize) {
        let usable_input = &input[..output.len() + max_remove];

        let (best_pos, best_len) = Self::longest_low_energy_region(
            usable_input,
            self.low_energy_threshold,
            |i: usize, len: usize| -> bool {
                i + len.saturating_sub(self.overlap_length).min(max_remove) <= output.len()
            },
        );

        if best_len > max_remove {
            // we have more than enough to remove, lower the energy threshold
            self.low_energy_threshold *= ENERGY_THRESHOLD_DECREASE_FACTOR;
        } else if best_len < max_remove / 2 {
            // not enough to remove, slowly increase the energy threshold
            self.low_energy_threshold *= ENERGY_THRESHOLD_INCREASE_FACTOR;
        }

        let samples_to_remove = best_len.saturating_sub(self.overlap_length).min(max_remove);

        if samples_to_remove < self.overlap_length {
            return (0, 0);
        }

        (best_pos, samples_to_remove)
    }

    fn calculate_energy(&self, samples: &[f32]) -> f32 {
        let sum_squares: f32 = samples.iter().map(|x| x * x).sum();
        sum_squares / samples.len() as f32
    }

    fn find_best_removal_point(&self, input: &[f32], removal_length: usize) -> usize {
        let mut best_position = input.len() / 3; // Default to middle-ish
        let mut lowest_energy = f32::MAX;

        // Search for the lowest energy region to remove
        let search_start = self.overlap_length;
        let search_end = input
            .len()
            .saturating_sub(removal_length + self.overlap_length);

        for pos in (search_start..search_end).step_by(self.overlap_length / 2) {
            let end_pos = (pos + removal_length).min(input.len());
            let region_energy = self.calculate_energy(&input[pos..end_pos]);

            if region_energy < lowest_energy {
                lowest_energy = region_energy;
                best_position = pos;
            }
        }

        best_position
    }

    fn longest_low_energy_region<F>(
        input: &[f32],
        threshold: f32,
        validate_candidate: F,
    ) -> (usize, usize)
    where
        F: Fn(usize, usize) -> bool, // closure type
    {
        // Step 1: define energy as x^2. Compute the rolling sum of the energy deviation from
        // threshold. In this rolling sum, if rolling_sum[j] - rolling_sum[j] <= 0, that means
        // that the sum of the deviation from threshold between i and j is less then 0,
        // which means that AVG(a[i..j]) <= threshold
        // This algorithm finds the the largest range where that stands. The constainst
        // validate_candidate is used to make sure that the final output size is correct.
        let mut energy_deviation_rolling_sum = Vec::with_capacity(input.len() + 1);
        energy_deviation_rolling_sum.push(0.0);
        for &x in input {
            energy_deviation_rolling_sum
                .push(energy_deviation_rolling_sum.last().unwrap() + x * x - threshold);
        }

        // Step 2: build increasing peaks stack
        // Rationale: if the range [i..j] statisfies the condition that rolling_sum[j] - rolling_sum[j] <= 0
        // then any i' < i, where rolling_sum[i'] > rolling_sum[i] will also statisfy the condition.
        // In other words, we need to find candidates that do not have a previous higher value.
        let mut stack = Vec::new(); // stores indices of rolling_sum
        for (i, &val) in energy_deviation_rolling_sum.iter().enumerate() {
            if stack.is_empty() || val > energy_deviation_rolling_sum[*stack.last().unwrap()] {
                stack.push(i);
            }
        }

        // Step 3: reverse scan to find longest valid subarray
        let mut max_len = 0;
        let mut best_i = 0;

        for j in (0..energy_deviation_rolling_sum.len()).rev() {
            while !stack.is_empty() && stack[stack.len() - 1] >= j {
                stack.pop();
            }
            if stack.is_empty() {
                break;
            }
            let mut si = stack.len();
            while si > 0 {
                si -= 1;
                let i = stack[si];
                // Find the smallest i where the condition holds
                if energy_deviation_rolling_sum[j] <= energy_deviation_rolling_sum[i] {
                    let len = j - i;
                    if len > max_len && validate_candidate(i, len) {
                        max_len = len;
                        best_i = i;
                        stack.truncate(si);
                    }
                } else {
                    break;
                }
            }
        }

        (best_i, max_len)
    }
}

// Allow Accelerate to be moved across threads (contains only primitive data, no interior mutability).
unsafe impl Send for Accelerate {}

impl TimeStretcher for Accelerate {
    fn process(&mut self, input: &[f32], output: &mut [f32], fast_mode: bool) -> TimeStretchResult {
        self.accelerate_internal(input, output, fast_mode)
    }

    fn get_used_input_samples(&self) -> usize {
        self.used_input_samples
    }

    fn reset(&mut self) {
        self.used_input_samples = 0;
    }
}

/// Preemptive Expand algorithm - adds audio samples to slow down playback
#[derive(Debug)]
pub struct PreemptiveExpand {
    _sample_rate: u32,
    _channels: u8,
    used_input_samples: usize,
    overlap_length: usize,
    corr_threshold: f32,
}

impl PreemptiveExpand {
    /// Create a new preemptive expand processor
    pub fn new(sample_rate: u32, channels: u8) -> Self {
        Self {
            _sample_rate: sample_rate,
            _channels: channels,
            used_input_samples: 0,
            overlap_length: Self::calculate_overlap_length(sample_rate),
            corr_threshold: 0.99,
        }
    }

    fn calculate_overlap_length(sample_rate: u32) -> usize {
        // Calculate overlap length based on sample rate (typically 4-6ms)
        ((sample_rate as f32 * 0.003) as usize).max(32) // Minimum 32 samples
    }

    /// Expand the audio by duplicating/stretching samples
    fn expand_internal(
        &mut self,
        input: &[f32],
        output: &mut [f32],
        _fast_mode: bool,
    ) -> TimeStretchResult {
        if input.len() < output.len() {
            // Input should always be at least the length of output
            output[..input.len()].copy_from_slice(input);
            self.used_input_samples = input.len();
            return TimeStretchResult::NoStretch;
        }

        // Calculate energy of the input signal
        let energy = self.calculate_energy(input);
        let is_low_energy = energy < 0.01; // Threshold for low energy detection

        // With 30ms input overlap_length is 3ms and max_add is about 13.5ms. Human voice
        // is around 85 to 400Hz (including children). 85Hz is about 12ms, 400Hz is about
        // 2.5ms. The correlation lag (aka: add_len) goes from overlap_length (3ms) to
        // max_add (13.5ms), which mostly covers the range of the human voice.
        let max_add = (output.len() - self.overlap_length) / 2;
        if max_add < self.overlap_length {
            // Not enough samples to expand
            output.copy_from_slice(&input[..output.len()]);
            self.used_input_samples = output.len();
            return TimeStretchResult::NoStretch;
        }

        let mut best_corr = -1.0f32;
        let mut best_pos = 0;
        let mut best_add_len = 0;
        for add_len in self.overlap_length..max_add {
            let correlation_len = output.len() - add_len * 2;
            let (pos, corr) = crate::signal::best_normalized_correlation(
                &input[add_len..correlation_len + add_len],
                &input[..correlation_len],
                self.overlap_length,
            );
            if corr > best_corr {
                best_corr = corr;
                best_pos = pos;
                best_add_len = add_len;
            }
        }

        if best_corr < self.corr_threshold {
            self.corr_threshold *= 0.98;

            // Correlation is too low
            output.copy_from_slice(&input[..output.len()]);
            self.used_input_samples = output.len();
            return TimeStretchResult::NoStretch;
        } else {
            self.corr_threshold = self.corr_threshold.max(best_corr * 0.95);
        }

        let usable_input = &input[..output.len() - best_add_len];

        // Copy first part
        output[..best_add_len + best_pos].copy_from_slice(&usable_input[..best_add_len + best_pos]);

        // Crossfade duplicate region
        crate::signal::crossfade(
            &usable_input[best_add_len + best_pos..best_add_len + best_pos + self.overlap_length],
            &usable_input[best_pos..best_pos + self.overlap_length],
            self.overlap_length,
            &mut output[best_add_len + best_pos..best_add_len + best_pos + self.overlap_length],
        );

        // Append rest
        output[best_add_len + best_pos + self.overlap_length..]
            .copy_from_slice(&usable_input[best_pos + self.overlap_length..]);

        self.used_input_samples = usable_input.len();

        if is_low_energy {
            TimeStretchResult::SuccessLowEnergy
        } else {
            TimeStretchResult::Success
        }
    }

    fn calculate_energy(&self, samples: &[f32]) -> f32 {
        let sum_squares: f32 = samples.iter().map(|x| x * x).sum();
        sum_squares / samples.len() as f32
    }
}

// Safe because PreemptiveExpand only contains owned numeric data.
unsafe impl Send for PreemptiveExpand {}

impl TimeStretcher for PreemptiveExpand {
    fn process(&mut self, input: &[f32], output: &mut [f32], fast_mode: bool) -> TimeStretchResult {
        self.expand_internal(input, output, fast_mode)
    }

    fn get_used_input_samples(&self) -> usize {
        self.used_input_samples
    }

    fn reset(&mut self) {
        self.used_input_samples = 0;
    }
}

/// Time stretch factory for creating time stretchers
pub struct TimeStretchFactory;

impl TimeStretchFactory {
    /// Create an accelerate processor
    pub fn create_accelerate(sample_rate: u32, channels: u8) -> Box<dyn TimeStretcher + Send> {
        Box::new(Accelerate::new(sample_rate, channels))
    }

    /// Create a preemptive expand processor  
    pub fn create_preemptive_expand(
        sample_rate: u32,
        channels: u8,
    ) -> Box<dyn TimeStretcher + Send> {
        Box::new(PreemptiveExpand::new(sample_rate, channels))
    }
}

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

    fn generate_test_signal(length: usize, frequency: f32, sample_rate: u32) -> Vec<f32> {
        (0..length)
            .map(|i| {
                let t = i as f32 / sample_rate as f32;
                (2.0 * std::f32::consts::PI * frequency * t).sin() * 0.5
            })
            .collect()
    }

    #[test]
    fn test_accelerate_creation() {
        let accelerate = Accelerate::new(16000, 1);
        assert_eq!(accelerate._sample_rate, 16000);
        assert_eq!(accelerate._channels, 1);
    }

    #[test]
    fn test_accelerate_processing() {
        let mut accelerate = Accelerate::new(16000, 1);
        let input = generate_test_signal(1600, 440.0, 16000); // 100ms of 440Hz tone
        let mut output = vec![0.0; 800];

        let result = accelerate.process(&input, &mut output, true);

        // Should successfully accelerate
        assert!(matches!(
            result,
            TimeStretchResult::Success | TimeStretchResult::SuccessLowEnergy
        ));
        // Should have recorder the number of used samples
        assert!(accelerate.get_used_input_samples() > 0);
        // Output should be shorter than used samples
        assert!(output.len() < accelerate.get_used_input_samples());
    }

    #[test]
    fn test_preemptive_expand_creation() {
        let expand = PreemptiveExpand::new(16000, 1);
        assert_eq!(expand._sample_rate, 16000);
        assert_eq!(expand._channels, 1);
    }

    #[test]
    fn test_preemptive_expand_processing() {
        let mut expand = PreemptiveExpand::new(16000, 1);
        let input = generate_test_signal(1600, 440.0, 16000); // 100ms of 440Hz tone
        let mut output = vec![0.0; 800];

        let result = expand.process(&input, &mut output, false);

        // Should successfully expand
        assert!(matches!(
            result,
            TimeStretchResult::Success | TimeStretchResult::SuccessLowEnergy
        ));
        // Should have recorder the number of used samples
        assert!(expand.get_used_input_samples() > 0);
        // Should have used less samples than the output size
        assert!(expand.get_used_input_samples() < output.len());
    }

    #[test]
    fn test_insufficient_input() {
        let mut accelerate = Accelerate::new(16000, 1);
        let input = vec![1.0; 10]; // Very short input
        let mut output = vec![0.0; 20];

        let result = accelerate.process(&input, &mut output, false);

        // Should not stretch due to insufficient input
        assert_eq!(result, TimeStretchResult::NoStretch);
        assert_eq!(output[..10], input);
        assert_eq!(output[10..], vec![0.0; 10]);
    }

    #[test]
    fn test_time_stretch_factory() {
        let accelerate = TimeStretchFactory::create_accelerate(16000, 1);
        let expand = TimeStretchFactory::create_preemptive_expand(16000, 1);

        // Should create valid processors
        assert_eq!(accelerate.get_used_input_samples(), 0);
        assert_eq!(expand.get_used_input_samples(), 0);
    }

    #[test]
    fn test_reset_functionality() {
        let mut accelerate = Accelerate::new(16000, 1);
        let input = generate_test_signal(1600, 440.0, 16000);
        let mut output = vec![0.0; 800];

        // Process to change state
        accelerate.process(&input, &mut output, false);
        assert!(accelerate.get_used_input_samples() > 0);

        // Reset should clear state
        accelerate.reset();
        assert_eq!(accelerate.get_used_input_samples(), 0);
    }

    #[test]
    fn test_longest_low_energy_region() {
        let mut best_i: usize;
        let mut best_len: usize;

        let mut input: Vec<f32>;
        // energy:
        // 0.04, 0.01, 0.09, 0.01, 0.04, 0.04, 0.01, 0.09, 0.25, 0.25, 0.01
        // threshold avg: 0.03
        // expected energy: 0.01, 0.04, 0.04, 0.01
        // i = 3, len = 4
        input = vec![0.2, -0.1, 0.3, 0.1, 0.2, -0.2, 0.1, 0.3, 0.5, -0.5, 0.1];
        (best_i, best_len) =
            Accelerate::longest_low_energy_region(&input, 0.03, |_i: usize, _len: usize| -> bool {
                true
            });
        assert_eq!(best_i, 3);
        assert_eq!(best_len, 4);

        input = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
        (best_i, best_len) =
            Accelerate::longest_low_energy_region(&input, 0.03, |_i: usize, _len: usize| -> bool {
                true
            });
        assert_eq!(best_i, 0);
        assert_eq!(best_len, 8);

        input = vec![
            0.2, -0.1, 0.3, 0.1, 0.2, -0.2, 0.1, 0.3, 0.5, -0.5, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
        ];
        (best_i, best_len) =
            Accelerate::longest_low_energy_region(&input, 0.03, |_i: usize, _len: usize| -> bool {
                true
            });
        assert_eq!(best_i, 10);
        assert_eq!(best_len, 7);

        (best_i, best_len) =
            Accelerate::longest_low_energy_region(&input, 0.03, |i: usize, len: usize| -> bool {
                let max_output_len = 15;
                i + len <= max_output_len
            });
        assert_eq!(best_i, 10);
        assert_eq!(best_len, 5);

        (best_i, best_len) =
            Accelerate::longest_low_energy_region(&input, 0.03, |i: usize, len: usize| -> bool {
                let max_output_len = 13;
                i + len <= max_output_len
            });
        assert_eq!(best_i, 3);
        assert_eq!(best_len, 4);
    }
}