1use 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#[derive(Debug, Clone, Copy, PartialEq)]
22#[non_exhaustive]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct TurnInfo {
25 pub sample_rate: i32,
27 pub max_audio_ms: i32,
30 pub frame_samples: i32,
33 pub has_speech: bool,
36 pub threshold: f64,
39}
40
41#[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 pub n_threads: i32,
51}
52
53#[derive(Debug, Clone, PartialEq)]
55#[cfg_attr(
56 feature = "serde",
57 derive(serde::Serialize, serde::Deserialize),
58 serde(default)
59)]
60pub struct TurnOptions {
61 pub threshold: f64,
65}
66
67impl Default for TurnOptions {
68 fn default() -> Self {
69 TurnOptions { threshold: -1.0 }
70 }
71}
72
73#[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 pub p: f32,
86 pub ended: bool,
88 pub probs: Vec<f32>,
92 pub first_frame: i64,
95 pub speech_probs: Vec<f32>,
99 pub speech_first_frame: i64,
101}
102
103pub struct TurnSession {
105 ptr: *mut sys::transcribe_turn_session,
106 model: Arc<ModelInner>,
108 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
118unsafe 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
136fn 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
145fn 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, ¶ms, &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 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 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 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 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, ¶ms) },
224 "turn run",
225 )?;
226 copy_result(ptr)
227 })?
228 }
229
230 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 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 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 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 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 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 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 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}