Skip to main content

transcribe_cpp/
turn.rs

1//! [`TurnSession`] — the TURN role (has the speaker finished talking?), from
2//! [`Model::turn_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`, `stream_feed_batch` and `stream_flush` return
5//! [`Error::Busy`](crate::Error) while an ASR stream is active. A turn 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, TurnOptions, TurnResult, TurnSessionOptions};
14
15use crate::cancel::{abort_trampoline, CancelToken};
16use crate::error::{check, Error, Result};
17use crate::model::{Model, ModelInner};
18use crate::session::clamp_len;
19use crate::types::FromRaw;
20
21/// An end-of-turn session.
22pub struct TurnSession {
23    ptr: *mut sys::transcribe_turn_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 TurnSession {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("TurnSession").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 TurnSession {}
39
40impl Drop for TurnSession {
41    fn drop(&mut self) {
42        unsafe { sys::transcribe_turn_session_free(self.ptr) };
43    }
44}
45
46const BUSY_RUN: &str = "a stream is active on this model; finish or drop it before turn run()";
47const BUSY_FEED: &str =
48    "a stream is active on this model; finish or drop it before turn stream_feed()";
49const BUSY_FEED_BATCH: &str =
50    "a stream is active on this model; finish or drop it before turn stream_feed_batch()";
51const BUSY_FLUSH: &str =
52    "a stream is active on this model; finish or drop it before turn stream_flush()";
53
54/// Copy `n` floats out of a native buffer (empty for NULL or `n <= 0`).
55fn copy_probs(p: *const f32, n: i32) -> Vec<f32> {
56    if p.is_null() || n <= 0 {
57        Vec::new()
58    } else {
59        unsafe { std::slice::from_raw_parts(p, n as usize) }.to_vec()
60    }
61}
62
63/// Copy the last call's result out; called under the compute lock.
64fn copy_result(ptr: *mut sys::transcribe_turn_session) -> Result<TurnResult> {
65    let mut res: sys::transcribe_turn_result = unsafe { std::mem::zeroed() };
66    unsafe { sys::transcribe_turn_result_init(&mut res) };
67    check(
68        unsafe { sys::transcribe_turn_get_result(ptr, &mut res) },
69        "turn result",
70    )?;
71    let mut result = TurnResult::default();
72    result.p = res.p;
73    result.ended = res.ended;
74    result.probs = copy_probs(unsafe { sys::transcribe_turn_probs(ptr) }, res.n_probs);
75    result.first_frame = res.first_frame;
76    result.speech_probs = copy_probs(
77        unsafe { sys::transcribe_turn_speech_probs(ptr) },
78        res.n_speech_probs,
79    );
80    result.speech_first_frame = res.speech_first_frame;
81    Ok(result)
82}
83
84impl TurnSession {
85    pub(crate) fn new(model: &Model, options: &TurnSessionOptions) -> Result<TurnSession> {
86        let mut params: sys::transcribe_turn_session_params = unsafe { std::mem::zeroed() };
87        unsafe { sys::transcribe_turn_session_params_init(&mut params) };
88        params.n_threads = options.n_threads;
89
90        let mut out: *mut sys::transcribe_turn_session = std::ptr::null_mut();
91        let status =
92            unsafe { sys::transcribe_turn_session_init(model.inner.ptr, &params, &mut out) };
93        check(status, "turn session init")?;
94        debug_assert!(!out.is_null());
95
96        Ok(TurnSession {
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    /// A batch feed checks the token of every session in the batch.
107    pub fn set_cancel_token(&mut self, token: &CancelToken) {
108        let flag = Arc::clone(&token.flag);
109        let userdata = Arc::as_ptr(&flag) as *mut c_void;
110        unsafe {
111            sys::transcribe_turn_set_abort_callback(self.ptr, Some(abort_trampoline), userdata)
112        };
113        self.cancel = Some(flag);
114    }
115
116    /// Remove any installed cancel token.
117    pub fn clear_cancel_token(&mut self) {
118        unsafe { sys::transcribe_turn_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
119        self.cancel = None;
120    }
121
122    /// Score one clip of 16 kHz mono float32 PCM (the audio of the current
123    /// turn, from where the speaker started): has the turn ended at its end?
124    /// Starts fresh and discards any stream in progress. Audio longer than
125    /// [`TurnInfo::max_audio_ms`](crate::TurnInfo::max_audio_ms) is scored on its tail. Models that can stream
126    /// also return every frame's turn (and speech) probability.
127    /// [`Error::InvalidArgument`](crate::Error) (empty or non-finite input, a
128    /// threshold above 1) leaves the stream and last result unchanged.
129    pub fn run(&mut self, pcm: &[f32], options: &TurnOptions) -> Result<TurnResult> {
130        let n = clamp_len(pcm.len())?;
131        let mut params: sys::transcribe_turn_params = unsafe { std::mem::zeroed() };
132        unsafe { sys::transcribe_turn_params_init(&mut params) };
133        params.threshold = options.threshold;
134
135        // Results are copied out under the compute lock, like every other
136        // binding, so a concurrent call on the same model cannot interleave.
137        let ptr = self.ptr;
138        self.model
139            .with_compute(Some(BUSY_RUN), |_| -> Result<TurnResult> {
140                check(
141                    unsafe { sys::transcribe_turn_run(ptr, pcm.as_ptr(), n, &params) },
142                    "turn run",
143                )?;
144                copy_result(ptr)
145            })?
146    }
147
148    /// Append audio to the stream and return the turn probabilities of the
149    /// frames it completed and the speech probabilities of the frames the model
150    /// judged; a partial frame waits for the next call. On CPU the stream's
151    /// probabilities equal a [`run`](Self::run) over the same audio.
152    /// [`Error::NotImplemented`](crate::Error) if the model cannot stream
153    /// ([`TurnInfo::frame_samples`](crate::TurnInfo::frame_samples) is 0). [`Error::InvalidArgument`](crate::Error)
154    /// (e.g. NaN input) leaves the stream intact; an abort or processing error
155    /// resets it to frame 0.
156    pub fn stream_feed(&mut self, pcm: &[f32]) -> Result<TurnResult> {
157        let n = clamp_len(pcm.len())?;
158        let ptr = self.ptr;
159        self.model
160            .with_compute(Some(BUSY_FEED), |_| -> Result<TurnResult> {
161                check(
162                    unsafe { sys::transcribe_turn_stream_feed(ptr, pcm.as_ptr(), n) },
163                    "turn stream feed",
164                )?;
165                copy_result(ptr)
166            })?
167    }
168
169    /// Feed several streams of one model in one compute, much faster than one
170    /// feed per session: each `(session, pcm)` ends up as after
171    /// `session.stream_feed(pcm)`, and result `i` is that session's. Uses the
172    /// first session's thread count and checks every session's cancel token.
173    /// [`Error::InvalidArgument`](crate::Error) for an empty batch, or from the
174    /// library for sessions of different models (every stream unchanged);
175    /// otherwise errors as
176    /// [`stream_feed`](Self::stream_feed), an abort or processing error
177    /// resetting every listed stream.
178    pub fn stream_feed_batch<'s, 'p, I>(batch: I) -> Result<Vec<TurnResult>>
179    where
180        I: IntoIterator<Item = (&'s mut TurnSession, &'p [f32])>,
181    {
182        // `&mut` borrows make the sessions distinct and unused elsewhere; the
183        // library rejects mixed models before touching any, so the first
184        // session's model lock suffices.
185        let batch: Vec<(&'s mut TurnSession, &'p [f32])> = batch.into_iter().collect();
186        let Some((first, _)) = batch.first() else {
187            return Err(Error::InvalidArgument(
188                "turn stream_feed_batch: empty batch".into(),
189            ));
190        };
191        let model = Arc::clone(&first.model);
192        let n = clamp_len(batch.len())?;
193        let ptrs: Vec<*mut sys::transcribe_turn_session> =
194            batch.iter().map(|(s, _)| s.ptr).collect();
195        let pcms: Vec<*const f32> = batch.iter().map(|(_, p)| p.as_ptr()).collect();
196        let lens = batch
197            .iter()
198            .map(|(_, p)| clamp_len(p.len()))
199            .collect::<Result<Vec<i32>>>()?;
200
201        model.with_compute(Some(BUSY_FEED_BATCH), |_| -> Result<Vec<TurnResult>> {
202            check(
203                unsafe {
204                    sys::transcribe_turn_stream_feed_batch(
205                        ptrs.as_ptr(),
206                        pcms.as_ptr(),
207                        lens.as_ptr(),
208                        n,
209                    )
210                },
211                "turn stream feed batch",
212            )?;
213            ptrs.iter().map(|&p| copy_result(p)).collect()
214        })?
215    }
216
217    /// End the stream: process the buffered partial frame, zero padded (one
218    /// turn probability, or none), and return the speech probabilities of
219    /// every frame not yet judged. The next feed starts at frame 0; a
220    /// processing error also resets the stream.
221    pub fn stream_flush(&mut self) -> Result<TurnResult> {
222        let ptr = self.ptr;
223        self.model
224            .with_compute(Some(BUSY_FLUSH), |_| -> Result<TurnResult> {
225                check(
226                    unsafe { sys::transcribe_turn_stream_flush(ptr) },
227                    "turn stream flush",
228                )?;
229                copy_result(ptr)
230            })?
231    }
232
233    /// Drop the stream without processing it; the next feed starts at frame 0.
234    /// Keeps the last result.
235    pub fn stream_reset(&mut self) {
236        let ptr = self.ptr;
237        let _ = self
238            .model
239            .with_compute(None, |_| unsafe { sys::transcribe_turn_stream_reset(ptr) });
240    }
241
242    /// Model load time plus the last call's stage timings.
243    pub fn timings(&self) -> Timings {
244        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
245        unsafe { sys::transcribe_timings_init(&mut raw) };
246        let _ = unsafe { sys::transcribe_turn_get_timings(self.ptr, &mut raw) };
247        Timings::from_raw(&raw)
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use std::sync::Mutex;
255
256    fn null_session(model: &Arc<ModelInner>) -> TurnSession {
257        // Null native handles (the frees are NULL no-ops).
258        TurnSession {
259            ptr: std::ptr::null_mut(),
260            model: Arc::clone(model),
261            cancel: None,
262        }
263    }
264
265    #[test]
266    fn calls_are_busy_while_a_stream_holds_the_lease() {
267        // The Busy check runs under the lock before any native call.
268        let model = Arc::new(ModelInner {
269            ptr: std::ptr::null_mut(),
270            compute_lock: Mutex::new(true),
271        });
272        let mut session = null_session(&model);
273        let mut other = null_session(&model);
274        let pcm = [0.0; 160];
275        for (r, msg) in [
276            (session.run(&pcm, &TurnOptions::default()), BUSY_RUN),
277            (session.stream_feed(&pcm), BUSY_FEED),
278            (session.stream_flush(), BUSY_FLUSH),
279        ] {
280            assert!(matches!(r, Err(Error::Busy(ref m)) if m == msg), "{r:?}");
281        }
282        let r = TurnSession::stream_feed_batch([(&mut session, &pcm[..]), (&mut other, &pcm[..])]);
283        assert!(
284            matches!(r, Err(Error::Busy(ref m)) if m == BUSY_FEED_BATCH),
285            "{r:?}"
286        );
287    }
288
289    #[test]
290    fn batch_rejects_empty_and_mixed_models() {
291        let a = Arc::new(ModelInner {
292            ptr: std::ptr::null_mut(),
293            compute_lock: Mutex::new(false),
294        });
295        let b = Arc::new(ModelInner {
296            ptr: std::ptr::null_mut(),
297            compute_lock: Mutex::new(false),
298        });
299        let r = TurnSession::stream_feed_batch(std::iter::empty());
300        assert!(matches!(r, Err(Error::InvalidArgument(_))), "{r:?}");
301        let (mut sa, mut sb) = (null_session(&a), null_session(&b));
302        let pcm = [0.0; 16];
303        let r = TurnSession::stream_feed_batch([(&mut sa, &pcm[..]), (&mut sb, &pcm[..])]);
304        assert!(matches!(r, Err(Error::InvalidArgument(_))), "{r:?}");
305    }
306
307    #[test]
308    fn defaults_match_the_c_init() {
309        let mut p: sys::transcribe_turn_params = unsafe { std::mem::zeroed() };
310        unsafe { sys::transcribe_turn_params_init(&mut p) };
311        assert_eq!(TurnOptions::default().threshold, p.threshold);
312        let mut s: sys::transcribe_turn_session_params = unsafe { std::mem::zeroed() };
313        unsafe { sys::transcribe_turn_session_params_init(&mut s) };
314        assert_eq!(TurnSessionOptions::default().n_threads, s.n_threads);
315    }
316}