Skip to main content

transcribe_cpp/
vad.rs

1//! [`VadSession`] — the VAD role (where there is speech), from
2//! [`Model::vad_session`]. Threading and lifetime rules are those of
3//! [`Session`](crate::Session). Each call takes the compute lock for that call
4//! only; `run`, `stream_feed` and `stream_flush` return
5//! [`Error::Busy`](crate::Error) while an ASR stream is active. A VAD stream is
6//! session state and does not take the stream lease.
7
8use std::os::raw::c_void;
9use std::sync::atomic::AtomicBool;
10use std::sync::Arc;
11
12use transcribe_cpp_sys as sys;
13use transcribe_cpp_types::{Timings, VadOptions, VadResult, VadSegment, VadSessionOptions};
14
15use crate::cancel::{abort_trampoline, CancelToken};
16use crate::error::{check, Result};
17use crate::model::{Model, ModelInner};
18use crate::session::clamp_len;
19use crate::types::FromRaw;
20
21/// A VAD session.
22pub struct VadSession {
23    ptr: *mut sys::transcribe_vad_session,
24    // Keeps the native model alive and carries the per-model compute lock.
25    model: Arc<ModelInner>,
26    // Keeps the abort callback's userdata alive while installed.
27    cancel: Option<Arc<AtomicBool>>,
28}
29
30impl std::fmt::Debug for VadSession {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("VadSession").finish_non_exhaustive()
33    }
34}
35
36// SAFETY: as for `Session` — `&mut self` on the mutating calls keeps use to
37// one thread at a time; deliberately NOT Sync.
38unsafe impl Send for VadSession {}
39
40impl Drop for VadSession {
41    fn drop(&mut self) {
42        unsafe { sys::transcribe_vad_session_free(self.ptr) };
43    }
44}
45
46const BUSY_RUN: &str = "a stream is active on this model; finish or drop it before vad run()";
47const BUSY_FEED: &str =
48    "a stream is active on this model; finish or drop it before vad stream_feed()";
49const BUSY_FLUSH: &str =
50    "a stream is active on this model; finish or drop it before vad stream_flush()";
51
52/// Copy the last call's result out; called under the compute lock.
53fn copy_result(ptr: *mut sys::transcribe_vad_session) -> Result<VadResult> {
54    let mut res: sys::transcribe_vad_result = unsafe { std::mem::zeroed() };
55    unsafe { sys::transcribe_vad_result_init(&mut res) };
56    check(
57        unsafe { sys::transcribe_vad_get_result(ptr, &mut res) },
58        "vad result",
59    )?;
60    let p = unsafe { sys::transcribe_vad_probs(ptr) };
61    let probs = if p.is_null() || res.n_probs <= 0 {
62        Vec::new()
63    } else {
64        unsafe { std::slice::from_raw_parts(p, res.n_probs as usize) }.to_vec()
65    };
66    let segments = (0..res.n_segments)
67        .map(|i| {
68            let mut raw: sys::transcribe_vad_segment = unsafe { std::mem::zeroed() };
69            unsafe { sys::transcribe_vad_segment_init(&mut raw) };
70            let _ = unsafe { sys::transcribe_vad_get_segment(ptr, i, &mut raw) };
71            let mut segment = VadSegment::default();
72            segment.start_sample = raw.start_sample;
73            segment.end_sample = raw.end_sample;
74            segment
75        })
76        .collect();
77    let mut result = VadResult::default();
78    result.probs = probs;
79    result.first_frame = res.first_frame;
80    result.segments = segments;
81    Ok(result)
82}
83
84impl VadSession {
85    pub(crate) fn new(model: &Model, options: &VadSessionOptions) -> Result<VadSession> {
86        let mut params: sys::transcribe_vad_session_params = unsafe { std::mem::zeroed() };
87        unsafe { sys::transcribe_vad_session_params_init(&mut params) };
88        params.n_threads = options.n_threads;
89
90        let mut out: *mut sys::transcribe_vad_session = std::ptr::null_mut();
91        let status =
92            unsafe { sys::transcribe_vad_session_init(model.inner.ptr, &params, &mut out) };
93        check(status, "vad session init")?;
94        debug_assert!(!out.is_null());
95
96        Ok(VadSession {
97            ptr: out,
98            model: Arc::clone(&model.inner),
99            cancel: None,
100        })
101    }
102
103    /// Install a [`CancelToken`] so an in-flight run, feed or flush can be aborted
104    /// from another thread (the call then returns
105    /// [`Error::Aborted`](crate::Error)). Replaces any previously installed token.
106    pub fn set_cancel_token(&mut self, token: &CancelToken) {
107        let flag = Arc::clone(&token.flag);
108        let userdata = Arc::as_ptr(&flag) as *mut c_void;
109        unsafe {
110            sys::transcribe_vad_set_abort_callback(self.ptr, Some(abort_trampoline), userdata)
111        };
112        self.cancel = Some(flag);
113    }
114
115    /// Remove any installed cancel token.
116    pub fn clear_cancel_token(&mut self) {
117        unsafe { sys::transcribe_vad_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
118        self.cancel = None;
119    }
120
121    /// Score one clip of 16 kHz mono float32 PCM from a fresh state and
122    /// segment it. Resets any stream in progress.
123    pub fn run(&mut self, pcm: &[f32], options: &VadOptions) -> Result<VadResult> {
124        let n = clamp_len(pcm.len())?;
125        let mut params: sys::transcribe_vad_params = unsafe { std::mem::zeroed() };
126        unsafe { sys::transcribe_vad_params_init(&mut params) };
127        params.threshold = options.threshold;
128        params.neg_threshold = options.neg_threshold;
129        params.min_speech_ms = options.min_speech_ms;
130        params.min_silence_ms = options.min_silence_ms;
131        params.speech_pad_ms = options.speech_pad_ms;
132        params.max_speech_ms = options.max_speech_ms;
133
134        // Results are copied out under the compute lock, like every other
135        // binding, so a concurrent call on the same model cannot interleave.
136        let ptr = self.ptr;
137        self.model
138            .with_compute(Some(BUSY_RUN), |_| -> Result<VadResult> {
139                check(
140                    unsafe { sys::transcribe_vad_run(ptr, pcm.as_ptr(), n, &params) },
141                    "vad run",
142                )?;
143                copy_result(ptr)
144            })?
145    }
146
147    /// Append audio to the stream and return the probabilities of the frames
148    /// it completed; a partial frame waits for the next call. On CPU the
149    /// stream's probabilities equal a [`run`](Self::run) over the same audio.
150    /// [`Error::InvalidArgument`](crate::Error) (e.g. NaN input) leaves the
151    /// stream intact; an abort or processing error resets it to frame 0.
152    pub fn stream_feed(&mut self, pcm: &[f32]) -> Result<VadResult> {
153        let n = clamp_len(pcm.len())?;
154        let ptr = self.ptr;
155        self.model
156            .with_compute(Some(BUSY_FEED), |_| -> Result<VadResult> {
157                check(
158                    unsafe { sys::transcribe_vad_stream_feed(ptr, pcm.as_ptr(), n) },
159                    "vad stream feed",
160                )?;
161                copy_result(ptr)
162            })?
163    }
164
165    /// End the stream: score the buffered partial frame, zero padded (one
166    /// probability, or none), and reset. The next feed starts at frame 0; a
167    /// processing error also resets the stream.
168    pub fn stream_flush(&mut self) -> Result<VadResult> {
169        let ptr = self.ptr;
170        self.model
171            .with_compute(Some(BUSY_FLUSH), |_| -> Result<VadResult> {
172                check(
173                    unsafe { sys::transcribe_vad_stream_flush(ptr) },
174                    "vad stream flush",
175                )?;
176                copy_result(ptr)
177            })?
178    }
179
180    /// Drop the stream without scoring; the next feed starts at frame 0.
181    pub fn stream_reset(&mut self) {
182        let ptr = self.ptr;
183        let _ = self
184            .model
185            .with_compute(None, |_| unsafe { sys::transcribe_vad_stream_reset(ptr) });
186    }
187
188    /// Model load time plus the last call's stage timings (`encode_ms`: front
189    /// end and encoder; `decode_ms`: the recurrent decoder).
190    pub fn timings(&self) -> Timings {
191        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
192        unsafe { sys::transcribe_timings_init(&mut raw) };
193        let _ = unsafe { sys::transcribe_vad_get_timings(self.ptr, &mut raw) };
194        Timings::from_raw(&raw)
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use crate::Error;
202    use std::sync::Mutex;
203
204    #[test]
205    fn calls_are_busy_while_a_stream_holds_the_lease() {
206        // Null native handles (both frees are NULL no-ops): the Busy check runs
207        // under the lock before any native call.
208        let mut session = VadSession {
209            ptr: std::ptr::null_mut(),
210            model: Arc::new(ModelInner {
211                ptr: std::ptr::null_mut(),
212                compute_lock: Mutex::new(true),
213            }),
214            cancel: None,
215        };
216        for (r, msg) in [
217            (session.run(&[0.0; 160], &VadOptions::default()), BUSY_RUN),
218            (session.stream_feed(&[0.0; 160]), BUSY_FEED),
219            (session.stream_flush(), BUSY_FLUSH),
220        ] {
221            assert!(matches!(r, Err(Error::Busy(ref m)) if m == msg), "{r:?}");
222        }
223    }
224
225    #[test]
226    fn defaults_match_the_c_init() {
227        let mut p: sys::transcribe_vad_params = unsafe { std::mem::zeroed() };
228        unsafe { sys::transcribe_vad_params_init(&mut p) };
229        let d = VadOptions::default();
230        assert_eq!(
231            (
232                d.threshold,
233                d.neg_threshold,
234                d.min_speech_ms,
235                d.min_silence_ms,
236                d.speech_pad_ms,
237                d.max_speech_ms
238            ),
239            (
240                p.threshold,
241                p.neg_threshold,
242                p.min_speech_ms,
243                p.min_silence_ms,
244                p.speech_pad_ms,
245                p.max_speech_ms
246            )
247        );
248    }
249}