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;
13
14use crate::cancel::{abort_trampoline, CancelToken};
15use crate::error::{check, Error, Result};
16use crate::model::{Model, ModelInner};
17use crate::result::Timings;
18use crate::session::clamp_len;
19
20/// Static facts about an end-of-turn model ([`Model::turn_info`]).
21#[derive(Debug, Clone, Copy, PartialEq)]
22#[non_exhaustive]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct TurnInfo {
25    /// Input PCM rate (16000).
26    pub sample_rate: i32,
27    /// The longest audio [`TurnSession::run`] looks at; longer audio is scored
28    /// on its last `max_audio_ms`. 0 = no limit.
29    pub max_audio_ms: i32,
30    /// Samples per frame for streaming; 0 = the model cannot stream (the
31    /// `stream_*` calls return [`Error::NotImplemented`](crate::Error)).
32    pub frame_samples: i32,
33    /// Whether the model also returns a speech probability per frame
34    /// ([`TurnResult::speech_probs`]).
35    pub has_speech: bool,
36    /// The model's recommended cut-off: the default for
37    /// [`TurnOptions::threshold`].
38    pub threshold: f64,
39}
40
41/// Options for creating a turn session.
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
43#[cfg_attr(
44    feature = "serde",
45    derive(serde::Serialize, serde::Deserialize),
46    serde(default)
47)]
48pub struct TurnSessionOptions {
49    /// CPU threads for ops that run on CPU; 0 = library default.
50    pub n_threads: i32,
51}
52
53/// Settings for [`TurnSession::run`].
54#[derive(Debug, Clone, PartialEq)]
55#[cfg_attr(
56    feature = "serde",
57    derive(serde::Serialize, serde::Deserialize),
58    serde(default)
59)]
60pub struct TurnOptions {
61    /// Probability at or above which the turn counts as ended
62    /// ([`TurnResult::ended`]). Negative (the default, -1) uses the model's
63    /// [`TurnInfo::threshold`]; otherwise `[0, 1]`.
64    pub threshold: f64,
65}
66
67impl Default for TurnOptions {
68    fn default() -> Self {
69        TurnOptions { threshold: -1.0 }
70    }
71}
72
73/// The result of one [`TurnSession::run`], [`TurnSession::stream_feed`],
74/// [`TurnSession::stream_feed_batch`] or [`TurnSession::stream_flush`].
75#[derive(Debug, Clone, Default, PartialEq)]
76#[non_exhaustive]
77#[cfg_attr(
78    feature = "serde",
79    derive(serde::Serialize, serde::Deserialize),
80    serde(default)
81)]
82pub struct TurnResult {
83    /// After a run: the probability that the turn has ended at the end of the
84    /// clip. 0 after a feed or flush.
85    pub p: f32,
86    /// After a run: `p >= threshold`. False after a feed or flush.
87    pub ended: bool,
88    /// Per-frame turn probabilities from the call: `probs[i]` says whether the
89    /// turn has ended at the end of frame `first_frame + i`. Always empty for
90    /// models that cannot stream.
91    pub probs: Vec<f32>,
92    /// Stream position of `probs[0]`, in frames: 0 after a run; for a feed or
93    /// flush, the frames the stream had processed before the call.
94    pub first_frame: i64,
95    /// Per-frame speech probabilities from the call (empty unless
96    /// [`TurnInfo::has_speech`]). During a stream they can trail the turn
97    /// probabilities; after a run every frame has both.
98    pub speech_probs: Vec<f32>,
99    /// Stream position of `speech_probs[0]`, in frames.
100    pub speech_first_frame: i64,
101}
102
103/// An end-of-turn session.
104pub struct TurnSession {
105    ptr: *mut sys::transcribe_turn_session,
106    // Keeps the native model alive and carries the per-model compute lock.
107    model: Arc<ModelInner>,
108    // Keeps the abort callback's userdata alive while installed.
109    cancel: Option<Arc<AtomicBool>>,
110}
111
112impl std::fmt::Debug for TurnSession {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("TurnSession").finish_non_exhaustive()
115    }
116}
117
118// SAFETY: as for `Session` — `&mut self` on the mutating calls keeps use to
119// one thread at a time; deliberately NOT Sync.
120unsafe impl Send for TurnSession {}
121
122impl Drop for TurnSession {
123    fn drop(&mut self) {
124        unsafe { sys::transcribe_turn_session_free(self.ptr) };
125    }
126}
127
128const BUSY_RUN: &str = "a stream is active on this model; finish or drop it before turn run()";
129const BUSY_FEED: &str =
130    "a stream is active on this model; finish or drop it before turn stream_feed()";
131const BUSY_FEED_BATCH: &str =
132    "a stream is active on this model; finish or drop it before turn stream_feed_batch()";
133const BUSY_FLUSH: &str =
134    "a stream is active on this model; finish or drop it before turn stream_flush()";
135
136/// Copy `n` floats out of a native buffer (empty for NULL or `n <= 0`).
137fn copy_probs(p: *const f32, n: i32) -> Vec<f32> {
138    if p.is_null() || n <= 0 {
139        Vec::new()
140    } else {
141        unsafe { std::slice::from_raw_parts(p, n as usize) }.to_vec()
142    }
143}
144
145/// Copy the last call's result out; called under the compute lock.
146fn copy_result(ptr: *mut sys::transcribe_turn_session) -> Result<TurnResult> {
147    let mut res: sys::transcribe_turn_result = unsafe { std::mem::zeroed() };
148    unsafe { sys::transcribe_turn_result_init(&mut res) };
149    check(
150        unsafe { sys::transcribe_turn_get_result(ptr, &mut res) },
151        "turn result",
152    )?;
153    Ok(TurnResult {
154        p: res.p,
155        ended: res.ended,
156        probs: copy_probs(unsafe { sys::transcribe_turn_probs(ptr) }, res.n_probs),
157        first_frame: res.first_frame,
158        speech_probs: copy_probs(
159            unsafe { sys::transcribe_turn_speech_probs(ptr) },
160            res.n_speech_probs,
161        ),
162        speech_first_frame: res.speech_first_frame,
163    })
164}
165
166impl TurnSession {
167    pub(crate) fn new(model: &Model, options: &TurnSessionOptions) -> Result<TurnSession> {
168        let mut params: sys::transcribe_turn_session_params = unsafe { std::mem::zeroed() };
169        unsafe { sys::transcribe_turn_session_params_init(&mut params) };
170        params.n_threads = options.n_threads;
171
172        let mut out: *mut sys::transcribe_turn_session = std::ptr::null_mut();
173        let status =
174            unsafe { sys::transcribe_turn_session_init(model.inner.ptr, &params, &mut out) };
175        check(status, "turn session init")?;
176        debug_assert!(!out.is_null());
177
178        Ok(TurnSession {
179            ptr: out,
180            model: Arc::clone(&model.inner),
181            cancel: None,
182        })
183    }
184
185    /// Install a [`CancelToken`] so an in-flight run, feed or flush can be aborted
186    /// from another thread (the call then returns
187    /// [`Error::Aborted`](crate::Error)). Replaces any previously installed token.
188    /// A batch feed checks the token of every session in the batch.
189    pub fn set_cancel_token(&mut self, token: &CancelToken) {
190        let flag = Arc::clone(&token.flag);
191        let userdata = Arc::as_ptr(&flag) as *mut c_void;
192        unsafe {
193            sys::transcribe_turn_set_abort_callback(self.ptr, Some(abort_trampoline), userdata)
194        };
195        self.cancel = Some(flag);
196    }
197
198    /// Remove any installed cancel token.
199    pub fn clear_cancel_token(&mut self) {
200        unsafe { sys::transcribe_turn_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
201        self.cancel = None;
202    }
203
204    /// Score one clip of 16 kHz mono float32 PCM (the audio of the current
205    /// turn, from where the speaker started): has the turn ended at its end?
206    /// Starts fresh and discards any stream in progress. Audio longer than
207    /// [`TurnInfo::max_audio_ms`] is scored on its tail. Models that can stream
208    /// also return every frame's turn (and speech) probability.
209    /// [`Error::InvalidArgument`](crate::Error) (empty or non-finite input, a
210    /// threshold above 1) leaves the stream and last result unchanged.
211    pub fn run(&mut self, pcm: &[f32], options: &TurnOptions) -> Result<TurnResult> {
212        let n = clamp_len(pcm.len())?;
213        let mut params: sys::transcribe_turn_params = unsafe { std::mem::zeroed() };
214        unsafe { sys::transcribe_turn_params_init(&mut params) };
215        params.threshold = options.threshold;
216
217        // Results are copied out under the compute lock, like every other
218        // binding, so a concurrent call on the same model cannot interleave.
219        let ptr = self.ptr;
220        self.model
221            .with_compute(Some(BUSY_RUN), |_| -> Result<TurnResult> {
222                check(
223                    unsafe { sys::transcribe_turn_run(ptr, pcm.as_ptr(), n, &params) },
224                    "turn run",
225                )?;
226                copy_result(ptr)
227            })?
228    }
229
230    /// Append audio to the stream and return the turn probabilities of the
231    /// frames it completed and the speech probabilities of the frames the model
232    /// judged; a partial frame waits for the next call. On CPU the stream's
233    /// probabilities equal a [`run`](Self::run) over the same audio.
234    /// [`Error::NotImplemented`](crate::Error) if the model cannot stream
235    /// ([`TurnInfo::frame_samples`] is 0). [`Error::InvalidArgument`](crate::Error)
236    /// (e.g. NaN input) leaves the stream intact; an abort or processing error
237    /// resets it to frame 0.
238    pub fn stream_feed(&mut self, pcm: &[f32]) -> Result<TurnResult> {
239        let n = clamp_len(pcm.len())?;
240        let ptr = self.ptr;
241        self.model
242            .with_compute(Some(BUSY_FEED), |_| -> Result<TurnResult> {
243                check(
244                    unsafe { sys::transcribe_turn_stream_feed(ptr, pcm.as_ptr(), n) },
245                    "turn stream feed",
246                )?;
247                copy_result(ptr)
248            })?
249    }
250
251    /// Feed several streams of one model in one compute, much faster than one
252    /// feed per session: each `(session, pcm)` ends up as after
253    /// `session.stream_feed(pcm)`, and result `i` is that session's. Uses the
254    /// first session's thread count and checks every session's cancel token.
255    /// [`Error::InvalidArgument`](crate::Error) for an empty batch, or from the
256    /// library for sessions of different models (every stream unchanged);
257    /// otherwise errors as
258    /// [`stream_feed`](Self::stream_feed), an abort or processing error
259    /// resetting every listed stream.
260    pub fn stream_feed_batch<'s, 'p, I>(batch: I) -> Result<Vec<TurnResult>>
261    where
262        I: IntoIterator<Item = (&'s mut TurnSession, &'p [f32])>,
263    {
264        // `&mut` borrows make the sessions distinct and unused elsewhere; the
265        // library rejects mixed models before touching any, so the first
266        // session's model lock suffices.
267        let batch: Vec<(&'s mut TurnSession, &'p [f32])> = batch.into_iter().collect();
268        let Some((first, _)) = batch.first() else {
269            return Err(Error::InvalidArgument(
270                "turn stream_feed_batch: empty batch".into(),
271            ));
272        };
273        let model = Arc::clone(&first.model);
274        let n = clamp_len(batch.len())?;
275        let ptrs: Vec<*mut sys::transcribe_turn_session> =
276            batch.iter().map(|(s, _)| s.ptr).collect();
277        let pcms: Vec<*const f32> = batch.iter().map(|(_, p)| p.as_ptr()).collect();
278        let lens = batch
279            .iter()
280            .map(|(_, p)| clamp_len(p.len()))
281            .collect::<Result<Vec<i32>>>()?;
282
283        model.with_compute(Some(BUSY_FEED_BATCH), |_| -> Result<Vec<TurnResult>> {
284            check(
285                unsafe {
286                    sys::transcribe_turn_stream_feed_batch(
287                        ptrs.as_ptr(),
288                        pcms.as_ptr(),
289                        lens.as_ptr(),
290                        n,
291                    )
292                },
293                "turn stream feed batch",
294            )?;
295            ptrs.iter().map(|&p| copy_result(p)).collect()
296        })?
297    }
298
299    /// End the stream: process the buffered partial frame, zero padded (one
300    /// turn probability, or none), and return the speech probabilities of
301    /// every frame not yet judged. The next feed starts at frame 0; a
302    /// processing error also resets the stream.
303    pub fn stream_flush(&mut self) -> Result<TurnResult> {
304        let ptr = self.ptr;
305        self.model
306            .with_compute(Some(BUSY_FLUSH), |_| -> Result<TurnResult> {
307                check(
308                    unsafe { sys::transcribe_turn_stream_flush(ptr) },
309                    "turn stream flush",
310                )?;
311                copy_result(ptr)
312            })?
313    }
314
315    /// Drop the stream without processing it; the next feed starts at frame 0.
316    /// Keeps the last result.
317    pub fn stream_reset(&mut self) {
318        let ptr = self.ptr;
319        let _ = self
320            .model
321            .with_compute(None, |_| unsafe { sys::transcribe_turn_stream_reset(ptr) });
322    }
323
324    /// Model load time plus the last call's stage timings.
325    pub fn timings(&self) -> Timings {
326        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
327        unsafe { sys::transcribe_timings_init(&mut raw) };
328        let _ = unsafe { sys::transcribe_turn_get_timings(self.ptr, &mut raw) };
329        Timings::from_raw(&raw)
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use std::sync::Mutex;
337
338    fn null_session(model: &Arc<ModelInner>) -> TurnSession {
339        // Null native handles (the frees are NULL no-ops).
340        TurnSession {
341            ptr: std::ptr::null_mut(),
342            model: Arc::clone(model),
343            cancel: None,
344        }
345    }
346
347    #[test]
348    fn calls_are_busy_while_a_stream_holds_the_lease() {
349        // The Busy check runs under the lock before any native call.
350        let model = Arc::new(ModelInner {
351            ptr: std::ptr::null_mut(),
352            compute_lock: Mutex::new(true),
353        });
354        let mut session = null_session(&model);
355        let mut other = null_session(&model);
356        let pcm = [0.0; 160];
357        for (r, msg) in [
358            (session.run(&pcm, &TurnOptions::default()), BUSY_RUN),
359            (session.stream_feed(&pcm), BUSY_FEED),
360            (session.stream_flush(), BUSY_FLUSH),
361        ] {
362            assert!(matches!(r, Err(Error::Busy(ref m)) if m == msg), "{r:?}");
363        }
364        let r = TurnSession::stream_feed_batch([(&mut session, &pcm[..]), (&mut other, &pcm[..])]);
365        assert!(
366            matches!(r, Err(Error::Busy(ref m)) if m == BUSY_FEED_BATCH),
367            "{r:?}"
368        );
369    }
370
371    #[test]
372    fn batch_rejects_empty_and_mixed_models() {
373        let a = Arc::new(ModelInner {
374            ptr: std::ptr::null_mut(),
375            compute_lock: Mutex::new(false),
376        });
377        let b = Arc::new(ModelInner {
378            ptr: std::ptr::null_mut(),
379            compute_lock: Mutex::new(false),
380        });
381        let r = TurnSession::stream_feed_batch(std::iter::empty());
382        assert!(matches!(r, Err(Error::InvalidArgument(_))), "{r:?}");
383        let (mut sa, mut sb) = (null_session(&a), null_session(&b));
384        let pcm = [0.0; 16];
385        let r = TurnSession::stream_feed_batch([(&mut sa, &pcm[..]), (&mut sb, &pcm[..])]);
386        assert!(matches!(r, Err(Error::InvalidArgument(_))), "{r:?}");
387    }
388
389    #[test]
390    fn defaults_match_the_c_init() {
391        let mut p: sys::transcribe_turn_params = unsafe { std::mem::zeroed() };
392        unsafe { sys::transcribe_turn_params_init(&mut p) };
393        assert_eq!(TurnOptions::default().threshold, p.threshold);
394        let mut s: sys::transcribe_turn_session_params = unsafe { std::mem::zeroed() };
395        unsafe { sys::transcribe_turn_session_params_init(&mut s) };
396        assert_eq!(TurnSessionOptions::default().n_threads, s.n_threads);
397    }
398}