1use 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#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct ModelOptions {
39 pub backend: Backend,
42 pub device: Option<crate::Device>,
45 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#[derive(Debug, Clone, PartialEq)]
66#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
67pub struct Capabilities {
68 pub native_sample_rate: i32,
69 pub languages: Vec<String>,
71 pub translate_target_languages: Vec<String>,
73 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 pub max_audio_ms: i64,
81}
82
83pub(crate) struct ModelInner {
85 pub(crate) ptr: *mut sys::transcribe_model,
86 pub(crate) compute_lock: Mutex<bool>,
93}
94
95impl ModelInner {
96 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
114unsafe impl Send for ModelInner {}
118unsafe impl Sync for ModelInner {}
119
120impl Drop for ModelInner {
121 fn drop(&mut self) {
122 unsafe { sys::transcribe_model_free(self.ptr) };
124 }
125}
126
127#[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 pub fn load(path: impl AsRef<Path>) -> Result<Model> {
148 Model::load_with(path, &ModelOptions::default())
149 }
150
151 pub fn load_with(path: impl AsRef<Path>, options: &ModelOptions) -> Result<Model> {
153 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(), ¶ms, &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 pub fn session(&self) -> Result<Session> {
183 self.session_with(&SessionOptions::default())
184 }
185
186 pub fn session_with(&self, options: &SessionOptions) -> Result<Session> {
188 Session::new(self, options)
189 }
190
191 pub fn diarize_session(&self) -> Result<DiarizeSession> {
194 self.diarize_session_with(&DiarizeSessionOptions::default())
195 }
196
197 pub fn diarize_session_with(&self, options: &DiarizeSessionOptions) -> Result<DiarizeSession> {
199 DiarizeSession::new(self, options)
200 }
201
202 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 pub fn langid_session(&self) -> Result<LangIdSession> {
220 self.langid_session_with(&LangIdSessionOptions::default())
221 }
222
223 pub fn langid_session_with(&self, options: &LangIdSessionOptions) -> Result<LangIdSession> {
225 LangIdSession::new(self, options)
226 }
227
228 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 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 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 pub fn vad_session(&self) -> Result<VadSession> {
270 self.vad_session_with(&VadSessionOptions::default())
271 }
272
273 pub fn vad_session_with(&self, options: &VadSessionOptions) -> Result<VadSession> {
275 VadSession::new(self, options)
276 }
277
278 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 pub fn turn_session(&self) -> Result<TurnSession> {
296 self.turn_session_with(&TurnSessionOptions::default())
297 }
298
299 pub fn turn_session_with(&self, options: &TurnSessionOptions) -> Result<TurnSession> {
301 TurnSession::new(self, options)
302 }
303
304 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 pub fn roles(&self) -> Roles {
324 Roles(unsafe { sys::transcribe_model_roles(self.inner.ptr) })
325 }
326
327 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 pub fn supports(&self, feature: Feature) -> bool {
373 unsafe { sys::transcribe_model_supports(self.inner.ptr, feature.to_raw()) }
374 }
375
376 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 pub fn arch(&self) -> String {
383 owned_str(unsafe { sys::transcribe_model_arch_string(self.inner.ptr) })
384 }
385
386 pub fn variant(&self) -> String {
388 owned_str(unsafe { sys::transcribe_model_variant_string(self.inner.ptr) })
389 }
390
391 pub fn backend(&self) -> String {
394 owned_str(unsafe { sys::transcribe_model_backend(self.inner.ptr) })
395 }
396
397 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 pub fn tokenize(&self, text: &str) -> Result<Vec<i32>> {
419 let c_text = CString::new(text)?;
420 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#[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 pub n_threads: i32,
476 pub kv_type: crate::types::KvType,
478 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
494#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
495pub struct SessionLimits {
496 pub effective_n_ctx: i32,
498 pub effective_max_audio_ms: i64,
500 pub max_kv_bytes: i64,
502}
503
504#[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 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}