Skip to main content

transcribe_cpp/
langid.rs

1//! [`LangIdSession`] — the LANGID role (which language is spoken), from
2//! [`Model::langid_session`]. Threading, lifetime, and compute-lock rules are
3//! those of [`Session`](crate::Session).
4
5use std::ffi::CString;
6use std::os::raw::{c_char, c_void};
7use std::sync::atomic::AtomicBool;
8use std::sync::Arc;
9
10use transcribe_cpp_sys as sys;
11use transcribe_cpp_types::{
12    LangIdCandidate, LangIdOptions, LangIdResult, LangIdSessionOptions, Timings,
13};
14
15use crate::cancel::{abort_trampoline, CancelToken};
16use crate::error::{check, Error, Result};
17use crate::model::{Model, ModelInner};
18use crate::result::owned_str;
19use crate::session::clamp_len;
20use crate::types::FromRaw;
21
22/// A language ID session.
23pub struct LangIdSession {
24    ptr: *mut sys::transcribe_langid_session,
25    // Keeps the native model alive and carries the per-model compute lock.
26    model: Arc<ModelInner>,
27    // Keeps the abort callback's userdata alive while installed.
28    cancel: Option<Arc<AtomicBool>>,
29}
30
31impl std::fmt::Debug for LangIdSession {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("LangIdSession").finish_non_exhaustive()
34    }
35}
36
37// SAFETY: as for `Session` — `&mut self` on the mutating calls keeps use to
38// one thread at a time; deliberately NOT Sync.
39unsafe impl Send for LangIdSession {}
40
41impl Drop for LangIdSession {
42    fn drop(&mut self) {
43        unsafe { sys::transcribe_langid_session_free(self.ptr) };
44    }
45}
46
47impl LangIdSession {
48    pub(crate) fn new(model: &Model, options: &LangIdSessionOptions) -> Result<LangIdSession> {
49        let mut params: sys::transcribe_langid_session_params = unsafe { std::mem::zeroed() };
50        unsafe { sys::transcribe_langid_session_params_init(&mut params) };
51        params.n_threads = options.n_threads;
52
53        let mut out: *mut sys::transcribe_langid_session = std::ptr::null_mut();
54        let status =
55            unsafe { sys::transcribe_langid_session_init(model.inner.ptr, &params, &mut out) };
56        check(status, "langid session init")?;
57        debug_assert!(!out.is_null());
58
59        Ok(LangIdSession {
60            ptr: out,
61            model: Arc::clone(&model.inner),
62            cancel: None,
63        })
64    }
65
66    /// Install a [`CancelToken`] so an in-flight run can be aborted from
67    /// another thread (the run then returns [`Error::Aborted`]).
68    /// Replaces any previously installed token.
69    pub fn set_cancel_token(&mut self, token: &CancelToken) {
70        let flag = Arc::clone(&token.flag);
71        let userdata = Arc::as_ptr(&flag) as *mut c_void;
72        unsafe {
73            sys::transcribe_langid_set_abort_callback(self.ptr, Some(abort_trampoline), userdata)
74        };
75        self.cancel = Some(flag);
76    }
77
78    /// Remove any installed cancel token.
79    pub fn clear_cancel_token(&mut self) {
80        unsafe { sys::transcribe_langid_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
81        self.cancel = None;
82    }
83
84    /// Identify the language of one clip of 16 kHz mono float32 PCM. Input
85    /// longer than [`LangIdInfo::max_audio_ms`](crate::LangIdInfo::max_audio_ms) is scored on its first `max_audio_ms`.
86    pub fn run(&mut self, pcm: &[f32], options: &LangIdOptions) -> Result<LangIdResult> {
87        let n = clamp_len(pcm.len())?;
88        // The CStrings and the pointer array stay alive until the end of this
89        // call, past the native run.
90        let codes: Option<Vec<CString>> = match &options.allowed {
91            None => None,
92            Some(list) if list.is_empty() => {
93                // NULL would mean "every label", the opposite of an empty list.
94                return Err(Error::InvalidArgument(
95                    "allowed is empty; pass None for every label".into(),
96                ));
97            }
98            Some(list) => Some(
99                list.iter()
100                    .map(|c| CString::new(c.as_str()))
101                    .collect::<std::result::Result<_, _>>()?,
102            ),
103        };
104        let ptrs: Option<Vec<*const c_char>> = codes
105            .as_ref()
106            .map(|cs| cs.iter().map(|c| c.as_ptr()).collect());
107        let mut params: sys::transcribe_langid_params = unsafe { std::mem::zeroed() };
108        unsafe { sys::transcribe_langid_params_init(&mut params) };
109        if let Some(p) = &ptrs {
110            params.allowed = p.as_ptr();
111            params.n_allowed = i32::try_from(p.len())
112                .map_err(|_| Error::InvalidArgument("allowed list too long".into()))?;
113        }
114
115        // Results are copied out under the compute lock, like every other
116        // binding, so a concurrent run on the same model cannot interleave.
117        let ptr = self.ptr;
118        self.model.with_compute(
119            Some("a stream is active on this model; finish or drop it before langid run()"),
120            |_| -> Result<LangIdResult> {
121                check(
122                    unsafe { sys::transcribe_langid_run(ptr, pcm.as_ptr(), n, &params) },
123                    "langid run",
124                )?;
125                let mut res: sys::transcribe_langid_result = unsafe { std::mem::zeroed() };
126                unsafe { sys::transcribe_langid_result_init(&mut res) };
127                check(
128                    unsafe { sys::transcribe_langid_get_result(ptr, &mut res) },
129                    "langid result",
130                )?;
131                let candidates = (0..res.n_candidates)
132                    .map(|i| {
133                        let mut raw: sys::transcribe_langid_candidate =
134                            unsafe { std::mem::zeroed() };
135                        unsafe { sys::transcribe_langid_candidate_init(&mut raw) };
136                        let _ = unsafe { sys::transcribe_langid_get_candidate(ptr, i, &mut raw) };
137                        let mut candidate = LangIdCandidate::default();
138                        candidate.index = raw.index;
139                        candidate.code = owned_str(raw.code);
140                        candidate.name = owned_str(raw.name);
141                        candidate.p = raw.p;
142                        candidate.logit = raw.logit;
143                        candidate
144                    })
145                    .collect();
146                let mut result = LangIdResult::default();
147                result.candidates = candidates;
148                result.allowed_mass = res.allowed_mass;
149                Ok(result)
150            },
151        )?
152    }
153
154    /// Model load time plus the last run's stage timings (`decode_ms` is 0).
155    pub fn timings(&self) -> Timings {
156        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
157        unsafe { sys::transcribe_timings_init(&mut raw) };
158        let _ = unsafe { sys::transcribe_langid_get_timings(self.ptr, &mut raw) };
159        Timings::from_raw(&raw)
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use std::sync::Mutex;
167
168    fn null_session(streaming: bool) -> LangIdSession {
169        // Null native handles (both frees are NULL no-ops): every check below
170        // fires before any native call.
171        LangIdSession {
172            ptr: std::ptr::null_mut(),
173            model: Arc::new(ModelInner {
174                ptr: std::ptr::null_mut(),
175                compute_lock: Mutex::new(streaming),
176            }),
177            cancel: None,
178        }
179    }
180
181    #[test]
182    fn run_is_busy_while_a_stream_holds_the_lease() {
183        let err = null_session(true)
184            .run(&[0.0; 160], &LangIdOptions::default())
185            .unwrap_err();
186        let Error::Busy(msg) = err else {
187            panic!("expected Busy, got {err:?}");
188        };
189        assert_eq!(
190            msg,
191            "a stream is active on this model; finish or drop it before langid run()"
192        );
193    }
194
195    #[test]
196    fn empty_allowed_is_rejected_not_all() {
197        let opts = LangIdOptions {
198            allowed: Some(vec![]),
199        };
200        let err = null_session(false).run(&[0.0; 160], &opts).unwrap_err();
201        assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
202    }
203
204    #[test]
205    fn interior_nul_in_allowed_is_rejected() {
206        let opts = LangIdOptions {
207            allowed: Some(vec!["e\0n".into()]),
208        };
209        let err = null_session(false).run(&[0.0; 160], &opts).unwrap_err();
210        assert!(matches!(err, Error::Nul(_)), "{err:?}");
211    }
212}