whisper-apr 0.3.1

WASM-first automatic speech recognition engine implementing OpenAI Whisper
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
//! Batch audio preprocessing (WAPR-080)
//!
//! Efficient batch processing of multiple audio segments for parallel inference.

use super::{MelConfig, MelFilterbank};
use crate::error::{WhisperError, WhisperResult};

/// Batch of audio samples for parallel processing
#[derive(Debug, Clone)]
pub struct AudioBatch {
    /// Individual audio segments (each is a Vec<f32> of samples)
    segments: Vec<Vec<f32>>,
    /// Audio configuration
    config: MelConfig,
}

impl AudioBatch {
    /// Create a new empty batch
    #[must_use]
    pub fn new(config: MelConfig) -> Self {
        Self {
            segments: Vec::new(),
            config,
        }
    }

    /// Create batch with default config
    #[must_use]
    pub fn with_default_config() -> Self {
        Self::new(MelConfig::default())
    }

    /// Add an audio segment to the batch
    pub fn add_segment(&mut self, samples: Vec<f32>) {
        self.segments.push(samples);
    }

    /// Get the number of segments in the batch
    #[must_use]
    pub fn len(&self) -> usize {
        self.segments.len()
    }

    /// Check if the batch is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.segments.is_empty()
    }

    /// Get a reference to the segments
    #[must_use]
    pub fn segments(&self) -> &[Vec<f32>] {
        &self.segments
    }

    /// Get mutable reference to segments
    pub fn segments_mut(&mut self) -> &mut Vec<Vec<f32>> {
        &mut self.segments
    }

    /// Clear all segments
    pub fn clear(&mut self) {
        self.segments.clear();
    }

    /// Get the audio configuration
    #[must_use]
    pub const fn config(&self) -> &MelConfig {
        &self.config
    }
}

/// Result of batch mel spectrogram computation
#[derive(Debug, Clone)]
pub struct BatchMelResult {
    /// Mel spectrograms for each segment (batch_size × n_mels × n_frames)
    pub mels: Vec<Vec<f32>>,
    /// Frame counts for each segment
    pub frame_counts: Vec<usize>,
    /// Maximum number of frames (for padding)
    pub max_frames: usize,
}

impl BatchMelResult {
    /// Get the batch size
    #[must_use]
    pub fn batch_size(&self) -> usize {
        self.mels.len()
    }

    /// Check if result is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.mels.is_empty()
    }

    /// Get mel spectrogram for a specific segment
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&Vec<f32>> {
        self.mels.get(index)
    }

    /// Get padded tensor for batch inference
    ///
    /// Returns a flat tensor of shape (batch_size, n_mels, max_frames) with zero-padding.
    #[must_use]
    pub fn to_padded_tensor(&self, n_mels: usize) -> Vec<f32> {
        let batch_size = self.batch_size();
        let total_size = batch_size * n_mels * self.max_frames;
        let mut tensor = vec![0.0_f32; total_size];

        for (batch_idx, mel) in self.mels.iter().enumerate() {
            let frames = self.frame_counts[batch_idx];
            for frame in 0..frames {
                for mel_idx in 0..n_mels {
                    let src_idx = frame * n_mels + mel_idx;
                    let dst_idx =
                        batch_idx * n_mels * self.max_frames + mel_idx * self.max_frames + frame;
                    if src_idx < mel.len() {
                        tensor[dst_idx] = mel[src_idx];
                    }
                }
            }
        }

        tensor
    }
}

/// Batch audio preprocessor
#[derive(Debug, Clone)]
pub struct BatchPreprocessor {
    /// Audio configuration
    config: MelConfig,
    /// Mel filterbank
    filterbank: MelFilterbank,
}

impl BatchPreprocessor {
    /// Create a new batch preprocessor
    #[must_use]
    pub fn new(config: MelConfig) -> Self {
        let filterbank = MelFilterbank::new(&config);
        Self { config, filterbank }
    }

    /// Create with default configuration
    #[must_use]
    pub fn with_default_config() -> Self {
        Self::new(MelConfig::default())
    }

    /// Process a batch of audio samples into mel spectrograms
    ///
    /// # Errors
    ///
    /// Returns error if any mel spectrogram computation fails.
    pub fn process_batch(&self, batch: &AudioBatch) -> WhisperResult<BatchMelResult> {
        let mut mels = Vec::with_capacity(batch.len());
        let mut frame_counts = Vec::with_capacity(batch.len());
        let mut max_frames = 0_usize;

        for samples in batch.segments() {
            let mel = self
                .filterbank
                .compute(samples)
                .map_err(|e| WhisperError::Audio(e.to_string()))?;
            let frames = mel.len() / self.config.n_mels;
            frame_counts.push(frames);
            max_frames = max_frames.max(frames);
            mels.push(mel);
        }

        Ok(BatchMelResult {
            mels,
            frame_counts,
            max_frames,
        })
    }

    /// Normalize a batch of audio samples
    #[must_use]
    pub fn normalize_batch(&self, batch: &AudioBatch) -> AudioBatch {
        let mut normalized = AudioBatch::new(self.config.clone());

        for samples in batch.segments() {
            let normalized_samples = normalize_audio(samples);
            normalized.add_segment(normalized_samples);
        }

        normalized
    }

    /// Get the number of mel channels
    #[must_use]
    pub fn n_mels(&self) -> usize {
        self.config.n_mels
    }
}

/// Normalize audio samples to [-1, 1] range
#[must_use]
fn normalize_audio(samples: &[f32]) -> Vec<f32> {
    if samples.is_empty() {
        return Vec::new();
    }

    let max_abs = samples
        .iter()
        .map(|x| x.abs())
        .fold(0.0_f32, |a, b| a.max(b));

    if max_abs < f32::EPSILON {
        return samples.to_vec();
    }

    samples.iter().map(|x| x / max_abs).collect()
}

/// Split audio into fixed-size chunks for batch processing
#[must_use]
pub fn split_into_chunks(samples: &[f32], chunk_size: usize, overlap: usize) -> Vec<Vec<f32>> {
    if samples.is_empty() || chunk_size == 0 {
        return Vec::new();
    }

    let step = chunk_size.saturating_sub(overlap).max(1);
    let mut chunks = Vec::new();
    let mut start = 0;

    while start < samples.len() {
        let end = (start + chunk_size).min(samples.len());
        chunks.push(samples[start..end].to_vec());
        start += step;

        // Stop if we've processed all samples
        if end >= samples.len() {
            break;
        }
    }

    chunks
}

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

    // =========================================================================
    // AudioBatch Tests
    // =========================================================================

    #[test]
    fn test_audio_batch_new() {
        let batch = AudioBatch::with_default_config();
        assert!(batch.is_empty());
        assert_eq!(batch.len(), 0);
    }

    #[test]
    fn test_audio_batch_add_segment() {
        let mut batch = AudioBatch::with_default_config();
        batch.add_segment(vec![0.1, 0.2, 0.3]);
        batch.add_segment(vec![0.4, 0.5]);

        assert_eq!(batch.len(), 2);
        assert!(!batch.is_empty());
    }

    #[test]
    fn test_audio_batch_clear() {
        let mut batch = AudioBatch::with_default_config();
        batch.add_segment(vec![0.1, 0.2, 0.3]);
        batch.clear();

        assert!(batch.is_empty());
    }

    #[test]
    fn test_audio_batch_segments() {
        let mut batch = AudioBatch::with_default_config();
        batch.add_segment(vec![1.0, 2.0]);
        batch.add_segment(vec![3.0, 4.0, 5.0]);

        let segments = batch.segments();
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0], vec![1.0, 2.0]);
        assert_eq!(segments[1], vec![3.0, 4.0, 5.0]);
    }

    #[test]
    fn test_audio_batch_segments_mut() {
        let mut batch = AudioBatch::new(MelConfig::default());
        batch.add_segment(vec![1.0, 2.0]);
        batch.segments_mut().push(vec![3.0, 4.0]);
        assert_eq!(batch.len(), 2);
        assert_eq!(batch.segments()[1], vec![3.0, 4.0]);
    }

    #[test]
    fn test_audio_batch_config() {
        let cfg = MelConfig {
            sample_rate: 44100,
            ..MelConfig::default()
        };
        let batch = AudioBatch::new(cfg.clone());
        assert_eq!(batch.config().sample_rate, 44100);
    }

    // =========================================================================
    // BatchMelResult Tests
    // =========================================================================

    #[test]
    fn test_batch_mel_result_batch_size() {
        let result = BatchMelResult {
            mels: vec![vec![0.0; 80], vec![0.0; 80]],
            frame_counts: vec![1, 1],
            max_frames: 1,
        };

        assert_eq!(result.batch_size(), 2);
    }

    #[test]
    fn test_batch_mel_result_get() {
        let result = BatchMelResult {
            mels: vec![vec![1.0; 80], vec![2.0; 80]],
            frame_counts: vec![1, 1],
            max_frames: 1,
        };

        assert!(result.get(0).is_some());
        assert!(result.get(1).is_some());
        assert!(result.get(2).is_none());
    }

    #[test]
    fn test_batch_mel_result_is_empty() {
        let empty = BatchMelResult {
            mels: Vec::new(),
            frame_counts: Vec::new(),
            max_frames: 0,
        };
        assert!(empty.is_empty());

        let non_empty = BatchMelResult {
            mels: vec![vec![0.0]],
            frame_counts: vec![1],
            max_frames: 1,
        };
        assert!(!non_empty.is_empty());
    }

    // =========================================================================
    // BatchPreprocessor Tests
    // =========================================================================

    #[test]
    fn test_batch_preprocessor_new() {
        let preprocessor = BatchPreprocessor::with_default_config();
        assert_eq!(preprocessor.n_mels(), 80);
    }

    #[test]
    fn test_batch_preprocessor_process_empty() {
        let preprocessor = BatchPreprocessor::with_default_config();
        let batch = AudioBatch::with_default_config();

        let result = preprocessor
            .process_batch(&batch)
            .expect("process empty batch");
        assert!(result.is_empty());
        assert_eq!(result.max_frames, 0);
    }

    #[test]
    fn test_batch_preprocessor_process_single() {
        let preprocessor = BatchPreprocessor::with_default_config();
        let mut batch = AudioBatch::with_default_config();

        // Add 16000 samples (1 second at 16kHz)
        let samples: Vec<f32> = (0..16000).map(|i| (i as f32 * 0.001).sin()).collect();
        batch.add_segment(samples);

        let result = preprocessor.process_batch(&batch).expect("process single");
        assert_eq!(result.batch_size(), 1);
        assert!(result.max_frames > 0);
    }

    #[test]
    fn test_batch_preprocessor_process_multiple() {
        let preprocessor = BatchPreprocessor::with_default_config();
        let mut batch = AudioBatch::with_default_config();

        // Add multiple segments of different lengths
        batch.add_segment((0..8000).map(|i| (i as f32 * 0.001).sin()).collect());
        batch.add_segment((0..16000).map(|i| (i as f32 * 0.001).sin()).collect());
        batch.add_segment((0..4000).map(|i| (i as f32 * 0.001).sin()).collect());

        let result = preprocessor
            .process_batch(&batch)
            .expect("process multiple");
        assert_eq!(result.batch_size(), 3);
        assert_eq!(result.frame_counts.len(), 3);

        // Second segment should have most frames
        assert!(result.frame_counts[1] >= result.frame_counts[0]);
        assert!(result.frame_counts[1] >= result.frame_counts[2]);
    }

    #[test]
    fn test_batch_preprocessor_normalize() {
        let preprocessor = BatchPreprocessor::with_default_config();
        let mut batch = AudioBatch::with_default_config();

        batch.add_segment(vec![-2.0, 0.0, 2.0]);
        batch.add_segment(vec![-1.0, 0.5, 1.0]);

        let normalized = preprocessor.normalize_batch(&batch);
        assert_eq!(normalized.len(), 2);

        // First segment should be normalized to [-1, 0, 1]
        let first = &normalized.segments()[0];
        assert!((first[0] - (-1.0)).abs() < f32::EPSILON);
        assert!((first[2] - 1.0).abs() < f32::EPSILON);
    }

    // =========================================================================
    // Normalization Tests
    // =========================================================================

    #[test]
    fn test_normalize_audio_empty() {
        let result = normalize_audio(&[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_normalize_audio_zeros() {
        let result = normalize_audio(&[0.0, 0.0, 0.0]);
        assert_eq!(result, vec![0.0, 0.0, 0.0]);
    }

    #[test]
    fn test_normalize_audio_positive() {
        let result = normalize_audio(&[0.0, 0.5, 1.0]);
        assert!((result[2] - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_normalize_audio_negative() {
        let result = normalize_audio(&[-0.5, 0.0, -1.0]);
        assert!((result[2] - (-1.0)).abs() < f32::EPSILON);
    }

    // =========================================================================
    // Chunk Splitting Tests
    // =========================================================================

    #[test]
    fn test_split_into_chunks_empty() {
        let result = split_into_chunks(&[], 100, 10);
        assert!(result.is_empty());
    }

    #[test]
    fn test_split_into_chunks_zero_size() {
        let result = split_into_chunks(&[1.0, 2.0, 3.0], 0, 0);
        assert!(result.is_empty());
    }

    #[test]
    fn test_split_into_chunks_no_overlap() {
        let samples: Vec<f32> = (0..10).map(|i| i as f32).collect();
        let chunks = split_into_chunks(&samples, 3, 0);

        assert_eq!(chunks.len(), 4); // 10 / 3 = 3.33, so 4 chunks
        assert_eq!(chunks[0], vec![0.0, 1.0, 2.0]);
        assert_eq!(chunks[1], vec![3.0, 4.0, 5.0]);
    }

    #[test]
    fn test_split_into_chunks_with_overlap() {
        let samples: Vec<f32> = (0..10).map(|i| i as f32).collect();
        let chunks = split_into_chunks(&samples, 4, 2);

        // Step = 4 - 2 = 2, so we get chunks starting at 0, 2, 4, 6, 8
        assert!(chunks.len() >= 3);
        assert_eq!(chunks[0], vec![0.0, 1.0, 2.0, 3.0]);
        assert_eq!(chunks[1], vec![2.0, 3.0, 4.0, 5.0]);
    }

    #[test]
    fn test_split_into_chunks_exact_fit() {
        let samples: Vec<f32> = (0..9).map(|i| i as f32).collect();
        let chunks = split_into_chunks(&samples, 3, 0);

        assert_eq!(chunks.len(), 3);
        assert_eq!(chunks[2], vec![6.0, 7.0, 8.0]);
    }

    // =========================================================================
    // Padded Tensor Tests
    // =========================================================================

    #[test]
    fn test_batch_mel_to_padded_tensor() {
        let result = BatchMelResult {
            mels: vec![vec![1.0; 160], vec![2.0; 80]], // 2 frames, 1 frame
            frame_counts: vec![2, 1],
            max_frames: 2,
        };

        let tensor = result.to_padded_tensor(80);
        // Should have shape (2, 80, 2) = 320 elements
        assert_eq!(tensor.len(), 2 * 80 * 2);
    }
}