Skip to main content

transcribe_cpp/
model.rs

1//! [`Model`] — a loaded GGUF, shareable across threads.
2//!
3//! A `Model` is `Arc`-backed and `Send + Sync`: cloning it is cheap and hands
4//! out another handle to the same native model. The native model is freed when
5//! the last handle AND every [`Session`](crate::Session) /
6//! [`DiarizeSession`](crate::DiarizeSession) derived from it have been dropped
7//! — Rust ownership gives the C "model must outlive its sessions" contract (and
8//! close-ordering safety) for free, in any drop order.
9//!
10//! The `Arc` also carries the per-model compute lock that enforces the C
11//! library's 0.x concurrency limitation: at most one `run` / `run_batch` /
12//! diarize run / active stream may be in flight across ALL sessions of a model.
13//! One-shot runs/batches queue on the lock (serialized); an *active stream*
14//! spans many native calls (`begin`→`feed`*→`finalize`), so the lock also
15//! carries a flag marking a stream in flight — any run/batch/stream that would
16//! overlap it is refused with [`Error::Busy`](crate::Error) rather than allowed
17//! to race.
18
19use std::ffi::CString;
20use std::path::Path;
21use std::sync::{Arc, Mutex};
22
23use transcribe_cpp_sys as sys;
24use transcribe_cpp_types::{
25    Backend, Capabilities, DiarizeInfo, DiarizeSessionOptions, ExtSlot, Feature, LangIdInfo,
26    LangIdSessionOptions, Roles, SessionOptions, TimestampKind, TurnInfo, TurnSessionOptions,
27    VadInfo, VadSessionOptions,
28};
29
30use crate::backend::Device;
31use crate::diarize::DiarizeSession;
32use crate::error::{check, Error, Result};
33use crate::langid::LangIdSession;
34use crate::result::owned_str;
35use crate::session::Session;
36use crate::turn::TurnSession;
37use crate::types::{FromRaw, ToRaw};
38use crate::vad::VadSession;
39use crate::version;
40
41/// Options for loading a model.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ModelOptions {
44    /// Which backend to request. Default [`Backend::Auto`]. An explicit device
45    /// must match a non-Auto backend request.
46    pub backend: Backend,
47    /// Exact process-local compute device. `None` applies the backend's
48    /// automatic policy; `Some` selects that device or fails without fallback.
49    pub device: Option<crate::Device>,
50    /// Copy the weights into memory instead of memory-mapping the model file.
51    /// Default `false`: where the device can use host memory (CPU, Metal on
52    /// Apple silicon) the weights are served from the file's page cache, which
53    /// the OS can reclaim. Don't truncate or rewrite a mapped model file in
54    /// place; write a new file and rename it over the old one. The
55    /// `TRANSCRIBE_NO_MMAP=1` environment variable forces `true`.
56    pub no_mmap: bool,
57}
58
59impl Default for ModelOptions {
60    fn default() -> Self {
61        ModelOptions {
62            backend: Backend::Auto,
63            device: None,
64            no_mmap: false,
65        }
66    }
67}
68
69/// The native model handle plus the per-model compute lock, shared via `Arc`.
70pub(crate) struct ModelInner {
71    pub(crate) ptr: *mut sys::transcribe_model,
72    /// Serializes the compute path across all sessions of this model. The bool
73    /// is `true` while a stream is ACTIVE (from `begin` until the earliest of
74    /// `finalize` / `reset` / the `Stream` being dropped); a held lock plus a
75    /// `true` flag is how `run`/`run_batch`/`stream` detect and refuse an
76    /// overlapping compute. Only taken through [`ModelInner::with_compute`].
77    /// See the module docs.
78    pub(crate) compute_lock: Mutex<bool>,
79}
80
81impl ModelInner {
82    /// Run `f` under the model's compute lock; every native compute call goes
83    /// through here. With `Some(msg)`, returns `Error::Busy(msg)` instead if a
84    /// stream holds the lease. `f` gets the lease flag to take or release it.
85    pub(crate) fn with_compute<R>(
86        &self,
87        refuse_if_streaming: Option<&str>,
88        f: impl FnOnce(&mut bool) -> R,
89    ) -> Result<R> {
90        let mut lease = self.compute_lock.lock().unwrap_or_else(|e| e.into_inner());
91        if let Some(msg) = refuse_if_streaming {
92            if *lease {
93                return Err(Error::Busy(msg.into()));
94            }
95        }
96        Ok(f(&mut lease))
97    }
98}
99
100// SAFETY: the native model is documented thread-safe for query + session
101// creation; the compute path is serialized by `compute_lock`. The raw pointer
102// is only ever used behind `&ModelInner`, never mutated through aliasing.
103unsafe impl Send for ModelInner {}
104unsafe impl Sync for ModelInner {}
105
106impl Drop for ModelInner {
107    fn drop(&mut self) {
108        // Only reached once every Session (each holding an Arc clone) is gone.
109        unsafe { sys::transcribe_model_free(self.ptr) };
110    }
111}
112
113/// A loaded transcription model.
114#[derive(Clone)]
115pub struct Model {
116    pub(crate) inner: Arc<ModelInner>,
117}
118
119impl std::fmt::Debug for Model {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("Model")
122            .field("arch", &self.arch())
123            .field("variant", &self.variant())
124            .field("backend", &self.backend())
125            .finish()
126    }
127}
128
129impl Model {
130    /// Load a model from disk with default options: a GGUF, or a supported
131    /// whisper.cpp `.bin` (Whisper, or Silero VAD v5.1.2 / v6.2.0). The format
132    /// is detected from the file header, not the extension.
133    pub fn load(path: impl AsRef<Path>) -> Result<Model> {
134        Model::load_with(path, &ModelOptions::default())
135    }
136
137    /// Load a model from disk with explicit options (formats as for [`Model::load`]).
138    pub fn load_with(path: impl AsRef<Path>, options: &ModelOptions) -> Result<Model> {
139        // Pre-1.0 base-version lock against the loaded library (once).
140        version::ensure_compatible()?;
141
142        let path = path.as_ref();
143        let c_path = CString::new(path_bytes(path)?)?;
144
145        let mut params: sys::transcribe_model_load_params = unsafe { std::mem::zeroed() };
146        unsafe { sys::transcribe_model_load_params_init(&mut params) };
147        params.backend = options.backend.to_raw();
148        params.device = options
149            .device
150            .as_ref()
151            .map_or(std::ptr::null_mut(), |device| device.handle);
152        params.no_mmap = options.no_mmap;
153
154        let mut out: *mut sys::transcribe_model = std::ptr::null_mut();
155        let status = unsafe { sys::transcribe_model_load_file(c_path.as_ptr(), &params, &mut out) };
156        check_model_load(status, &format!("load {}", path.display()))?;
157        debug_assert!(!out.is_null());
158
159        Ok(Model {
160            inner: Arc::new(ModelInner {
161                ptr: out,
162                compute_lock: Mutex::new(false),
163            }),
164        })
165    }
166
167    /// Open a session bound to this model with default session options.
168    pub fn session(&self) -> Result<Session> {
169        self.session_with(&SessionOptions::default())
170    }
171
172    /// Open a session bound to this model with explicit options.
173    pub fn session_with(&self, options: &SessionOptions) -> Result<Session> {
174        Session::new(self, options)
175    }
176
177    /// Open a diarization session with default options. Errors with
178    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Diarize`](crate::Role).
179    pub fn diarize_session(&self) -> Result<DiarizeSession> {
180        self.diarize_session_with(&DiarizeSessionOptions::default())
181    }
182
183    /// Open a diarization session with explicit options.
184    pub fn diarize_session_with(&self, options: &DiarizeSessionOptions) -> Result<DiarizeSession> {
185        DiarizeSession::new(self, options)
186    }
187
188    /// Static facts about a diarization model. Errors with
189    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Diarize`](crate::Role).
190    pub fn diarize_info(&self) -> Result<DiarizeInfo> {
191        let mut raw: sys::transcribe_diarize_info = unsafe { std::mem::zeroed() };
192        unsafe { sys::transcribe_diarize_info_init(&mut raw) };
193        check(
194            unsafe { sys::transcribe_diarize_get_info(self.inner.ptr, &mut raw) },
195            "diarize info",
196        )?;
197        let mut info = DiarizeInfo::default();
198        info.sample_rate = raw.sample_rate;
199        info.max_speakers = raw.max_speakers;
200        Ok(info)
201    }
202
203    /// Open a language ID session with default options. Errors with
204    /// [`Error::UnsupportedRole`] unless the model serves [`Role::LangId`](crate::Role).
205    pub fn langid_session(&self) -> Result<LangIdSession> {
206        self.langid_session_with(&LangIdSessionOptions::default())
207    }
208
209    /// Open a language ID session with explicit options.
210    pub fn langid_session_with(&self, options: &LangIdSessionOptions) -> Result<LangIdSession> {
211        LangIdSession::new(self, options)
212    }
213
214    /// Static facts about a language ID model. Errors with
215    /// [`Error::UnsupportedRole`] unless the model serves [`Role::LangId`](crate::Role).
216    pub fn langid_info(&self) -> Result<LangIdInfo> {
217        let mut raw: sys::transcribe_langid_info = unsafe { std::mem::zeroed() };
218        unsafe { sys::transcribe_langid_info_init(&mut raw) };
219        check(
220            unsafe { sys::transcribe_langid_get_info(self.inner.ptr, &mut raw) },
221            "langid info",
222        )?;
223        let mut info = LangIdInfo::default();
224        info.sample_rate = raw.sample_rate;
225        info.n_labels = raw.n_labels;
226        info.min_audio_ms = raw.min_audio_ms;
227        info.max_audio_ms = raw.max_audio_ms;
228        Ok(info)
229    }
230
231    /// `(code, name)` per label index. Errors with [`Error::UnsupportedRole`]
232    /// unless the model serves [`Role::LangId`](crate::Role).
233    pub fn langid_labels(&self) -> Result<Vec<(String, String)>> {
234        let n = self.langid_info()?.n_labels;
235        Ok((0..n)
236            .map(|i| unsafe {
237                (
238                    owned_str(sys::transcribe_langid_label_code(self.inner.ptr, i)),
239                    owned_str(sys::transcribe_langid_label_name(self.inner.ptr, i)),
240                )
241            })
242            .collect())
243    }
244
245    /// Label index of a code or alias (`"he"` and `"iw"` name the same label);
246    /// `None` when unknown or the model does not serve the LANGID role.
247    pub fn langid_label_index(&self, code: &str) -> Option<i32> {
248        let c = CString::new(code).ok()?;
249        let i = unsafe { sys::transcribe_langid_label_index(self.inner.ptr, c.as_ptr()) };
250        (i >= 0).then_some(i)
251    }
252
253    /// Open a VAD session with default options. Errors with
254    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Vad`](crate::Role).
255    pub fn vad_session(&self) -> Result<VadSession> {
256        self.vad_session_with(&VadSessionOptions::default())
257    }
258
259    /// Open a VAD session with explicit options.
260    pub fn vad_session_with(&self, options: &VadSessionOptions) -> Result<VadSession> {
261        VadSession::new(self, options)
262    }
263
264    /// Static facts about a VAD model. Errors with
265    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Vad`](crate::Role).
266    pub fn vad_info(&self) -> Result<VadInfo> {
267        let mut raw: sys::transcribe_vad_info = unsafe { std::mem::zeroed() };
268        unsafe { sys::transcribe_vad_info_init(&mut raw) };
269        check(
270            unsafe { sys::transcribe_vad_get_info(self.inner.ptr, &mut raw) },
271            "vad info",
272        )?;
273        let mut info = VadInfo::default();
274        info.sample_rate = raw.sample_rate;
275        info.frame_samples = raw.frame_samples;
276        Ok(info)
277    }
278
279    /// Open an end-of-turn session with default options. Errors with
280    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Turn`](crate::Role).
281    pub fn turn_session(&self) -> Result<TurnSession> {
282        self.turn_session_with(&TurnSessionOptions::default())
283    }
284
285    /// Open an end-of-turn session with explicit options.
286    pub fn turn_session_with(&self, options: &TurnSessionOptions) -> Result<TurnSession> {
287        TurnSession::new(self, options)
288    }
289
290    /// Static facts about an end-of-turn model. Errors with
291    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Turn`](crate::Role).
292    pub fn turn_info(&self) -> Result<TurnInfo> {
293        let mut raw: sys::transcribe_turn_info = unsafe { std::mem::zeroed() };
294        unsafe { sys::transcribe_turn_info_init(&mut raw) };
295        check(
296            unsafe { sys::transcribe_turn_get_info(self.inner.ptr, &mut raw) },
297            "turn info",
298        )?;
299        let mut info = TurnInfo::default();
300        info.sample_rate = raw.sample_rate;
301        info.max_audio_ms = raw.max_audio_ms;
302        info.frame_samples = raw.frame_samples;
303        info.has_speech = raw.has_speech;
304        info.threshold = raw.threshold;
305        Ok(info)
306    }
307
308    /// The roles (kinds of work) this model serves.
309    pub fn roles(&self) -> Roles {
310        Roles::from_bits(unsafe { sys::transcribe_model_roles(self.inner.ptr) })
311    }
312
313    /// The model's immutable ASR capabilities. Errors with
314    /// [`Error::UnsupportedRole`] unless the model serves [`Role::Asr`](crate::Role).
315    pub fn capabilities(&self) -> Result<Capabilities> {
316        let mut caps: sys::transcribe_capabilities = unsafe { std::mem::zeroed() };
317        unsafe { sys::transcribe_capabilities_init(&mut caps) };
318        check(
319            unsafe { sys::transcribe_model_get_capabilities(self.inner.ptr, &mut caps) },
320            "capabilities",
321        )?;
322
323        let mut languages = Vec::new();
324        if !caps.languages.is_null() && caps.n_languages > 0 {
325            let slice =
326                unsafe { std::slice::from_raw_parts(caps.languages, caps.n_languages as usize) };
327            for &lang in slice {
328                languages.push(owned_str(lang));
329            }
330        }
331        let mut translate_target_languages = Vec::new();
332        if !caps.translate_target_languages.is_null() && caps.n_translate_target_languages > 0 {
333            let slice = unsafe {
334                std::slice::from_raw_parts(
335                    caps.translate_target_languages,
336                    caps.n_translate_target_languages as usize,
337                )
338            };
339            for &lang in slice {
340                translate_target_languages.push(owned_str(lang));
341            }
342        }
343
344        Ok(Capabilities {
345            native_sample_rate: caps.native_sample_rate,
346            languages,
347            translate_target_languages,
348            max_timestamp_kind: TimestampKind::from_raw(caps.max_timestamp_kind),
349            supports_language_detect: caps.supports_language_detect,
350            supports_translate: caps.supports_translate,
351            supports_streaming: caps.supports_streaming,
352            supports_spec_decode: caps.supports_spec_decode,
353            max_audio_ms: caps.max_audio_ms,
354        })
355    }
356
357    /// Probe a yes/no feature.
358    pub fn supports(&self, feature: Feature) -> bool {
359        unsafe { sys::transcribe_model_supports(self.inner.ptr, feature.to_raw()) }
360    }
361
362    /// Whether this model accepts the given family-extension `kind` in `slot`.
363    pub fn accepts_ext(&self, slot: ExtSlot, kind: u32) -> bool {
364        unsafe { sys::transcribe_model_accepts_ext_kind(self.inner.ptr, slot.to_raw(), kind) }
365    }
366
367    /// The `general.architecture` string, e.g. "parakeet".
368    pub fn arch(&self) -> String {
369        owned_str(unsafe { sys::transcribe_model_arch_string(self.inner.ptr) })
370    }
371
372    /// The `stt.variant` string, e.g. "tdt-0.6b-v2" (may be empty).
373    pub fn variant(&self) -> String {
374        owned_str(unsafe { sys::transcribe_model_variant_string(self.inner.ptr) })
375    }
376
377    /// The runtime backend bound to this model, e.g. "cpu", "metal" — the way
378    /// to detect CPU fallback after requesting a GPU.
379    pub fn backend(&self) -> String {
380        owned_str(unsafe { sys::transcribe_model_backend(self.inner.ptr) })
381    }
382
383    /// The compute [`Device`] this model is running on — the one that owns its
384    /// weights. Its `memory_free` is a live snapshot, so re-call to poll how
385    /// much memory is left on the device after the model loaded. Errors with
386    /// [`Error::Backend`](crate::Error) if the model has no resolved device.
387    pub fn device(&self) -> Result<Device> {
388        let handle = unsafe { sys::transcribe_model_device(self.inner.ptr) };
389        if handle.is_null() {
390            return Err(crate::Error::Backend(
391                "model has no resolved device".to_string(),
392            ));
393        }
394        let mut raw: sys::transcribe_device_info = unsafe { std::mem::zeroed() };
395        unsafe { sys::transcribe_device_info_init(&mut raw) };
396        let status = unsafe { sys::transcribe_device_get_info(handle, &mut raw) };
397        check(status, "device_get_info")?;
398        Ok(Device::from_raw(&raw, handle, None))
399    }
400
401    /// Tokenize plain UTF-8 text into the model's vocabulary (no BOS/EOS, no
402    /// special tags). Errors with [`Error::NotImplemented`](crate::Error) for
403    /// families whose tokenizer has no encode path (e.g. SentencePiece today).
404    pub fn tokenize(&self, text: &str) -> Result<Vec<i32>> {
405        let c_text = CString::new(text)?;
406        // Grow-and-retry on the negative-N "buffer too small" signal.
407        let mut buf = vec![0i32; text.len().max(16)];
408        loop {
409            let n = unsafe {
410                sys::transcribe_tokenize(
411                    self.inner.ptr,
412                    c_text.as_ptr(),
413                    buf.as_mut_ptr(),
414                    buf.len(),
415                )
416            };
417            if n == i32::MIN {
418                return Err(crate::error::Error::NotImplemented(
419                    "model tokenizer has no encode path".to_string(),
420                ));
421            }
422            if n < 0 {
423                buf.resize((-n) as usize, 0);
424                continue;
425            }
426            buf.truncate(n as usize);
427            return Ok(buf);
428        }
429    }
430}
431
432fn check_model_load(status: sys::transcribe_status, context: &str) -> Result<()> {
433    #[cfg(feature = "dynamic-backends")]
434    {
435        if status == sys::transcribe_status::TRANSCRIBE_ERR_BACKEND
436            && crate::backend::device_count() == 0
437        {
438            let code = status.0 as i32;
439            let base = crate::error::status_string(code);
440            return Err(crate::error::Error::Backend(format!(
441                "{context}: {base} (status {code}); dynamic-backends builds \
442                 require backend modules to be loaded before model load. Call \
443                 transcribe_cpp::init_backends_default() when modules are \
444                 bundled next to libtranscribe, or init_backends(dir) for a \
445                 custom provider directory."
446            )));
447        }
448    }
449    check(status, context)
450}
451
452/// Convert a filesystem path to the bytes the C API's `const char *` expects.
453/// On Unix paths are arbitrary bytes, passed through verbatim; elsewhere the
454/// API takes UTF-8, so a non-UTF-8 path is rejected rather than lossily mangled
455/// (`to_string_lossy` would silently substitute U+FFFD). Shared with
456/// [`crate::backend::init_backends`].
457#[cfg(unix)]
458pub(crate) fn path_bytes(path: &Path) -> Result<Vec<u8>> {
459    use std::os::unix::ffi::OsStrExt;
460    Ok(path.as_os_str().as_bytes().to_vec())
461}
462
463#[cfg(not(unix))]
464pub(crate) fn path_bytes(path: &Path) -> Result<Vec<u8>> {
465    // The C API takes a UTF-8 `const char *`; require a UTF-8-representable path.
466    path.to_str().map(|s| s.as_bytes().to_vec()).ok_or_else(|| {
467        crate::error::Error::InvalidArgument(format!("non-UTF-8 path: {}", path.display()))
468    })
469}