whisper-macos-cli 0.1.0

Transcribe audio files locally on Apple Silicon via whisper.cpp with Metal GPU acceleration, exposing a strict stdin/stdout JSON contract for AI agents and Unix pipelines.
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
use std::io::{Cursor, Read, Seek, SeekFrom};
use std::path::Path;

use symphonia::core::audio::{AudioBufferRef, Signal};
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;

const OPUS_PRESKIP_SAMPLES: usize = 3840;
const STDIN_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;

pub struct PcmData {
    pub samples: Vec<i16>,
    pub sample_rate: u32,
    pub channels: usize,
}

impl PcmData {
    pub fn duration_seconds(&self) -> f64 {
        if self.sample_rate == 0 || self.channels == 0 {
            return 0.0;
        }
        self.samples.len() as f64 / (self.sample_rate as f64 * self.channels as f64)
    }
}

pub fn decode_file(path: &Path) -> Result<PcmData, crate::error::Error> {
    let file = std::fs::File::open(path).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            crate::error::Error::InputNotFound {
                path: path.display().to_string(),
            }
        } else {
            crate::error::Error::Io(e)
        }
    })?;

    let mut header = [0u8; 12];
    let header_len = match (&file).read(&mut header) {
        Ok(n) => n,
        Err(e) => return Err(crate::error::Error::Io(e)),
    };
    if let Err(e) = (&file).seek(SeekFrom::Start(0)) {
        return Err(crate::error::Error::Io(e));
    }

    if header_len >= 4 && is_ogg_opus_magic(&header[..header_len]) {
        return decode_ogg_opus(file);
    }

    let source = MediaSourceStream::new(Box::new(file), Default::default());

    let mut hint = Hint::new();
    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
        hint.with_extension(ext);
    }

    match decode_stream(source, hint) {
        Ok(pcm) => Ok(pcm),
        Err(crate::error::Error::AudioDecode(ref e))
            if e.to_string().contains("unsupported codec") =>
        {
            tracing::info!("symphonia unsupported codec, trying OGG/Opus fallback");
            let file2 = std::fs::File::open(path).map_err(|e| {
                if e.kind() == std::io::ErrorKind::NotFound {
                    crate::error::Error::InputNotFound {
                        path: path.display().to_string(),
                    }
                } else {
                    crate::error::Error::Io(e)
                }
            })?;
            decode_ogg_opus(file2)
        }
        Err(e) => Err(e),
    }
}

pub fn decode_stdin(format_hint: Option<&str>) -> Result<PcmData, crate::error::Error> {
    let mut buf = Vec::new();
    let mut handle = std::io::stdin().take(STDIN_MAX_BYTES + 1);
    handle
        .read_to_end(&mut buf)
        .map_err(crate::error::Error::Io)?;

    if buf.is_empty() {
        return Err(crate::error::Error::NoInput);
    }
    if buf.len() as u64 > STDIN_MAX_BYTES {
        return Err(crate::error::Error::Config(format!(
            "stdin input exceeds maximum size of {STDIN_MAX_BYTES} bytes"
        )));
    }

    if is_ogg_opus_magic(&buf[..buf.len().min(12)]) {
        return decode_ogg_opus(Cursor::new(buf));
    }

    let source = MediaSourceStream::new(Box::new(Cursor::new(buf.clone())), Default::default());

    let mut hint = Hint::new();
    if let Some(fmt) = format_hint {
        hint.with_extension(fmt);
    }

    match decode_stream(source, hint) {
        Ok(pcm) => Ok(pcm),
        Err(crate::error::Error::AudioDecode(ref e))
            if e.to_string().contains("unsupported codec") =>
        {
            tracing::info!("symphonia unsupported codec, trying OGG/Opus fallback");
            decode_ogg_opus(Cursor::new(buf))
        }
        Err(e) => Err(e),
    }
}

pub fn is_ogg_opus_magic(header: &[u8]) -> bool {
    if header.len() < 4 {
        return false;
    }
    &header[..4] == b"OggS"
}

fn decode_stream(source: MediaSourceStream, hint: Hint) -> Result<PcmData, crate::error::Error> {
    let probed = symphonia::default::get_probe()
        .format(
            &hint,
            source,
            &FormatOptions::default(),
            &MetadataOptions::default(),
        )
        .map_err(|e| crate::error::Error::AudioDecode(anyhow::anyhow!("probe failed: {e}")))?;

    let mut reader = probed.format;

    let track = reader
        .tracks()
        .iter()
        .find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
        .ok_or_else(|| crate::error::Error::AudioDecode(anyhow::anyhow!("no audio track found")))?;

    let track_id = track.id;
    let codec_params = track.codec_params.clone();

    let sample_rate = codec_params
        .sample_rate
        .ok_or_else(|| crate::error::Error::AudioDecode(anyhow::anyhow!("unknown sample rate")))?;

    let channels = codec_params.channels.map(|c| c.count()).unwrap_or(2);

    let mut decoder = symphonia::default::get_codecs()
        .make(&codec_params, &DecoderOptions::default())
        .map_err(|e| crate::error::Error::AudioDecode(anyhow::anyhow!("codec init failed: {e}")))?;

    let mut all_samples: Vec<i16> = Vec::new();

    loop {
        let packet = match reader.next_packet() {
            Ok(p) => p,
            Err(symphonia::core::errors::Error::IoError(e))
                if e.kind() == std::io::ErrorKind::UnexpectedEof =>
            {
                break;
            }
            Err(_) => continue,
        };

        if packet.track_id() != track_id {
            continue;
        }

        let audio_buf = match decoder.decode(&packet) {
            Ok(buf) => buf,
            Err(_) => continue,
        };

        extract_i16_samples(&audio_buf, &mut all_samples);
    }

    if all_samples.is_empty() {
        return Err(crate::error::Error::AudioDecode(anyhow::anyhow!(
            "no audio samples decoded"
        )));
    }

    Ok(PcmData {
        samples: all_samples,
        sample_rate,
        channels,
    })
}

pub fn to_mono(samples: &[i16], channels: usize) -> Vec<i16> {
    if channels == 1 {
        return samples.to_vec();
    }

    let num_frames = samples.len() / channels;
    let mut mono = Vec::with_capacity(num_frames);

    for frame in 0..num_frames {
        let mut sum: i32 = 0;
        for ch in 0..channels {
            sum += samples[frame * channels + ch] as i32;
        }
        let avg = sum / channels as i32;
        mono.push(avg.clamp(i16::MIN as i32, i16::MAX as i32) as i16);
    }

    mono
}

pub fn i16_to_f32(samples: &[i16]) -> Vec<f32> {
    samples.iter().map(|&s| s as f32 / 32768.0).collect()
}

fn decode_ogg_opus<R: Read + Seek>(mut reader: R) -> Result<PcmData, crate::error::Error> {
    use ogg::reading::PacketReader;

    let mut ogg_reader = PacketReader::new(&mut reader);
    let mut channels = 1u8;
    let mut pre_skip = OPUS_PRESKIP_SAMPLES;
    let mut header_packets = 0u8;

    while header_packets < 2 {
        let pkt = ogg_reader
            .read_packet_expected()
            .map_err(|e| crate::error::Error::AudioDecode(anyhow::anyhow!("ogg header: {e}")))?;

        if header_packets == 0 && pkt.data.len() >= 16 && &pkt.data[..8] == b"OpusHead" {
            channels = pkt.data[9];
            pre_skip = u32::from_le_bytes([pkt.data[10], pkt.data[11], pkt.data[12], pkt.data[13]])
                as usize;
        }
        header_packets += 1;
    }

    let channels_usize = channels.max(1) as usize;
    let output_rate = 48000;

    let mut decoder = opus_decoder::OpusDecoder::new(output_rate, channels_usize)
        .map_err(|e| crate::error::Error::AudioDecode(anyhow::anyhow!("opus init: {e:?}")))?;

    let max_frame = opus_decoder::OpusDecoder::MAX_FRAME_SIZE_48K;
    let mut pcm_buf = vec![0i16; max_frame * channels_usize];
    let mut all_samples: Vec<i16> = Vec::new();
    let mut samples_to_skip = pre_skip;

    loop {
        let pkt = match ogg_reader.read_packet() {
            Ok(Some(p)) => p,
            Ok(None) => break,
            Err(_) => continue,
        };

        match decoder.decode(&pkt.data, &mut pcm_buf, false) {
            Ok(samples_per_channel) => {
                let total = samples_per_channel * channels_usize;
                let slice = &pcm_buf[..total];

                if samples_to_skip >= total {
                    samples_to_skip -= total;
                } else if samples_to_skip > 0 {
                    let kept = &slice[samples_to_skip..];
                    all_samples.extend_from_slice(kept);
                    samples_to_skip = 0;
                } else {
                    all_samples.extend_from_slice(slice);
                }
            }
            Err(_) => continue,
        }
    }

    if all_samples.is_empty() {
        return Err(crate::error::Error::AudioDecode(anyhow::anyhow!(
            "no audio samples decoded from OGG/Opus"
        )));
    }

    tracing::info!(
        samples = all_samples.len(),
        channels = channels_usize,
        preskip_discarded = pre_skip,
        "OGG/Opus decoded via fallback"
    );

    Ok(PcmData {
        samples: all_samples,
        sample_rate: output_rate,
        channels: channels_usize,
    })
}

fn extract_i16_samples(buffer: &AudioBufferRef, dest: &mut Vec<i16>) {
    match buffer {
        AudioBufferRef::U8(buf) => {
            let ch = buf.spec().channels.count();
            let frames = buf.frames();
            dest.reserve(frames * ch);
            for f in 0..frames {
                for c in 0..ch {
                    dest.push(((buf.chan(c)[f] as i32 - 128) * 256) as i16);
                }
            }
        }
        AudioBufferRef::S16(buf) => {
            let ch = buf.spec().channels.count();
            let frames = buf.frames();
            dest.reserve(frames * ch);
            for f in 0..frames {
                for c in 0..ch {
                    dest.push(buf.chan(c)[f]);
                }
            }
        }
        AudioBufferRef::S32(buf) => {
            let ch = buf.spec().channels.count();
            let frames = buf.frames();
            dest.reserve(frames * ch);
            for f in 0..frames {
                for c in 0..ch {
                    dest.push((buf.chan(c)[f] >> 16) as i16);
                }
            }
        }
        AudioBufferRef::F32(buf) => {
            let ch = buf.spec().channels.count();
            let frames = buf.frames();
            dest.reserve(frames * ch);
            for f in 0..frames {
                for c in 0..ch {
                    let v = buf.chan(c)[f].clamp(-1.0, 1.0);
                    dest.push((v * 32767.0) as i16);
                }
            }
        }
        AudioBufferRef::F64(buf) => {
            let ch = buf.spec().channels.count();
            let frames = buf.frames();
            dest.reserve(frames * ch);
            for f in 0..frames {
                for c in 0..ch {
                    let v = buf.chan(c)[f].clamp(-1.0, 1.0);
                    dest.push((v * 32767.0) as i16);
                }
            }
        }
        _ => {}
    }
}

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

    #[test]
    fn to_mono_passthrough_single_channel() {
        let samples = vec![100i16, 200, 300];
        let result = to_mono(&samples, 1);
        assert_eq!(result, samples);
    }

    #[test]
    fn to_mono_averages_stereo() {
        let samples = vec![100i16, 200, 300, 400];
        let result = to_mono(&samples, 2);
        assert_eq!(result, vec![150, 350]);
    }

    #[test]
    fn i16_to_f32_converts_correctly() {
        let samples = vec![0i16, 32767, -32768];
        let result = i16_to_f32(&samples);
        assert!((result[0] - 0.0).abs() < 0.001);
        assert!((result[1] - 1.0).abs() < 0.001);
        assert!((result[2] - (-1.0)).abs() < 0.001);
    }

    #[test]
    fn opus_magic_detected() {
        let ogg = b"OggS\x00\x02\x00\x00\x00\x00\x00\x00";
        assert!(is_ogg_opus_magic(ogg));
    }

    #[test]
    fn non_opus_not_detected() {
        let wav = b"RIFF\x00\x00\x00\x00";
        assert!(!is_ogg_opus_magic(wav));
    }

    #[test]
    fn short_buffer_not_detected() {
        let short = b"Og";
        assert!(!is_ogg_opus_magic(short));
    }

    #[test]
    fn pcm_data_duration_computed_correctly() {
        let pcm = PcmData {
            samples: vec![0i16; 16000 * 2],
            sample_rate: 16000,
            channels: 1,
        };
        assert!((pcm.duration_seconds() - 2.0).abs() < 0.001);
    }
}