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