1use std::os::raw::c_void;
9use std::sync::atomic::AtomicBool;
10use std::sync::Arc;
11
12use transcribe_cpp_sys as sys;
13use transcribe_cpp_types::{Timings, TurnOptions, TurnResult, TurnSessionOptions};
14
15use crate::cancel::{abort_trampoline, CancelToken};
16use crate::error::{check, Error, Result};
17use crate::model::{Model, ModelInner};
18use crate::session::clamp_len;
19use crate::types::FromRaw;
20
21pub struct TurnSession {
23 ptr: *mut sys::transcribe_turn_session,
24 model: Arc<ModelInner>,
26 cancel: Option<Arc<AtomicBool>>,
28}
29
30impl std::fmt::Debug for TurnSession {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.debug_struct("TurnSession").finish_non_exhaustive()
33 }
34}
35
36unsafe impl Send for TurnSession {}
39
40impl Drop for TurnSession {
41 fn drop(&mut self) {
42 unsafe { sys::transcribe_turn_session_free(self.ptr) };
43 }
44}
45
46const BUSY_RUN: &str = "a stream is active on this model; finish or drop it before turn run()";
47const BUSY_FEED: &str =
48 "a stream is active on this model; finish or drop it before turn stream_feed()";
49const BUSY_FEED_BATCH: &str =
50 "a stream is active on this model; finish or drop it before turn stream_feed_batch()";
51const BUSY_FLUSH: &str =
52 "a stream is active on this model; finish or drop it before turn stream_flush()";
53
54fn copy_probs(p: *const f32, n: i32) -> Vec<f32> {
56 if p.is_null() || n <= 0 {
57 Vec::new()
58 } else {
59 unsafe { std::slice::from_raw_parts(p, n as usize) }.to_vec()
60 }
61}
62
63fn copy_result(ptr: *mut sys::transcribe_turn_session) -> Result<TurnResult> {
65 let mut res: sys::transcribe_turn_result = unsafe { std::mem::zeroed() };
66 unsafe { sys::transcribe_turn_result_init(&mut res) };
67 check(
68 unsafe { sys::transcribe_turn_get_result(ptr, &mut res) },
69 "turn result",
70 )?;
71 let mut result = TurnResult::default();
72 result.p = res.p;
73 result.ended = res.ended;
74 result.probs = copy_probs(unsafe { sys::transcribe_turn_probs(ptr) }, res.n_probs);
75 result.first_frame = res.first_frame;
76 result.speech_probs = copy_probs(
77 unsafe { sys::transcribe_turn_speech_probs(ptr) },
78 res.n_speech_probs,
79 );
80 result.speech_first_frame = res.speech_first_frame;
81 Ok(result)
82}
83
84impl TurnSession {
85 pub(crate) fn new(model: &Model, options: &TurnSessionOptions) -> Result<TurnSession> {
86 let mut params: sys::transcribe_turn_session_params = unsafe { std::mem::zeroed() };
87 unsafe { sys::transcribe_turn_session_params_init(&mut params) };
88 params.n_threads = options.n_threads;
89
90 let mut out: *mut sys::transcribe_turn_session = std::ptr::null_mut();
91 let status =
92 unsafe { sys::transcribe_turn_session_init(model.inner.ptr, ¶ms, &mut out) };
93 check(status, "turn session init")?;
94 debug_assert!(!out.is_null());
95
96 Ok(TurnSession {
97 ptr: out,
98 model: Arc::clone(&model.inner),
99 cancel: None,
100 })
101 }
102
103 pub fn set_cancel_token(&mut self, token: &CancelToken) {
108 let flag = Arc::clone(&token.flag);
109 let userdata = Arc::as_ptr(&flag) as *mut c_void;
110 unsafe {
111 sys::transcribe_turn_set_abort_callback(self.ptr, Some(abort_trampoline), userdata)
112 };
113 self.cancel = Some(flag);
114 }
115
116 pub fn clear_cancel_token(&mut self) {
118 unsafe { sys::transcribe_turn_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
119 self.cancel = None;
120 }
121
122 pub fn run(&mut self, pcm: &[f32], options: &TurnOptions) -> Result<TurnResult> {
130 let n = clamp_len(pcm.len())?;
131 let mut params: sys::transcribe_turn_params = unsafe { std::mem::zeroed() };
132 unsafe { sys::transcribe_turn_params_init(&mut params) };
133 params.threshold = options.threshold;
134
135 let ptr = self.ptr;
138 self.model
139 .with_compute(Some(BUSY_RUN), |_| -> Result<TurnResult> {
140 check(
141 unsafe { sys::transcribe_turn_run(ptr, pcm.as_ptr(), n, ¶ms) },
142 "turn run",
143 )?;
144 copy_result(ptr)
145 })?
146 }
147
148 pub fn stream_feed(&mut self, pcm: &[f32]) -> Result<TurnResult> {
157 let n = clamp_len(pcm.len())?;
158 let ptr = self.ptr;
159 self.model
160 .with_compute(Some(BUSY_FEED), |_| -> Result<TurnResult> {
161 check(
162 unsafe { sys::transcribe_turn_stream_feed(ptr, pcm.as_ptr(), n) },
163 "turn stream feed",
164 )?;
165 copy_result(ptr)
166 })?
167 }
168
169 pub fn stream_feed_batch<'s, 'p, I>(batch: I) -> Result<Vec<TurnResult>>
179 where
180 I: IntoIterator<Item = (&'s mut TurnSession, &'p [f32])>,
181 {
182 let batch: Vec<(&'s mut TurnSession, &'p [f32])> = batch.into_iter().collect();
186 let Some((first, _)) = batch.first() else {
187 return Err(Error::InvalidArgument(
188 "turn stream_feed_batch: empty batch".into(),
189 ));
190 };
191 let model = Arc::clone(&first.model);
192 let n = clamp_len(batch.len())?;
193 let ptrs: Vec<*mut sys::transcribe_turn_session> =
194 batch.iter().map(|(s, _)| s.ptr).collect();
195 let pcms: Vec<*const f32> = batch.iter().map(|(_, p)| p.as_ptr()).collect();
196 let lens = batch
197 .iter()
198 .map(|(_, p)| clamp_len(p.len()))
199 .collect::<Result<Vec<i32>>>()?;
200
201 model.with_compute(Some(BUSY_FEED_BATCH), |_| -> Result<Vec<TurnResult>> {
202 check(
203 unsafe {
204 sys::transcribe_turn_stream_feed_batch(
205 ptrs.as_ptr(),
206 pcms.as_ptr(),
207 lens.as_ptr(),
208 n,
209 )
210 },
211 "turn stream feed batch",
212 )?;
213 ptrs.iter().map(|&p| copy_result(p)).collect()
214 })?
215 }
216
217 pub fn stream_flush(&mut self) -> Result<TurnResult> {
222 let ptr = self.ptr;
223 self.model
224 .with_compute(Some(BUSY_FLUSH), |_| -> Result<TurnResult> {
225 check(
226 unsafe { sys::transcribe_turn_stream_flush(ptr) },
227 "turn stream flush",
228 )?;
229 copy_result(ptr)
230 })?
231 }
232
233 pub fn stream_reset(&mut self) {
236 let ptr = self.ptr;
237 let _ = self
238 .model
239 .with_compute(None, |_| unsafe { sys::transcribe_turn_stream_reset(ptr) });
240 }
241
242 pub fn timings(&self) -> Timings {
244 let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
245 unsafe { sys::transcribe_timings_init(&mut raw) };
246 let _ = unsafe { sys::transcribe_turn_get_timings(self.ptr, &mut raw) };
247 Timings::from_raw(&raw)
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use std::sync::Mutex;
255
256 fn null_session(model: &Arc<ModelInner>) -> TurnSession {
257 TurnSession {
259 ptr: std::ptr::null_mut(),
260 model: Arc::clone(model),
261 cancel: None,
262 }
263 }
264
265 #[test]
266 fn calls_are_busy_while_a_stream_holds_the_lease() {
267 let model = Arc::new(ModelInner {
269 ptr: std::ptr::null_mut(),
270 compute_lock: Mutex::new(true),
271 });
272 let mut session = null_session(&model);
273 let mut other = null_session(&model);
274 let pcm = [0.0; 160];
275 for (r, msg) in [
276 (session.run(&pcm, &TurnOptions::default()), BUSY_RUN),
277 (session.stream_feed(&pcm), BUSY_FEED),
278 (session.stream_flush(), BUSY_FLUSH),
279 ] {
280 assert!(matches!(r, Err(Error::Busy(ref m)) if m == msg), "{r:?}");
281 }
282 let r = TurnSession::stream_feed_batch([(&mut session, &pcm[..]), (&mut other, &pcm[..])]);
283 assert!(
284 matches!(r, Err(Error::Busy(ref m)) if m == BUSY_FEED_BATCH),
285 "{r:?}"
286 );
287 }
288
289 #[test]
290 fn batch_rejects_empty_and_mixed_models() {
291 let a = Arc::new(ModelInner {
292 ptr: std::ptr::null_mut(),
293 compute_lock: Mutex::new(false),
294 });
295 let b = Arc::new(ModelInner {
296 ptr: std::ptr::null_mut(),
297 compute_lock: Mutex::new(false),
298 });
299 let r = TurnSession::stream_feed_batch(std::iter::empty());
300 assert!(matches!(r, Err(Error::InvalidArgument(_))), "{r:?}");
301 let (mut sa, mut sb) = (null_session(&a), null_session(&b));
302 let pcm = [0.0; 16];
303 let r = TurnSession::stream_feed_batch([(&mut sa, &pcm[..]), (&mut sb, &pcm[..])]);
304 assert!(matches!(r, Err(Error::InvalidArgument(_))), "{r:?}");
305 }
306
307 #[test]
308 fn defaults_match_the_c_init() {
309 let mut p: sys::transcribe_turn_params = unsafe { std::mem::zeroed() };
310 unsafe { sys::transcribe_turn_params_init(&mut p) };
311 assert_eq!(TurnOptions::default().threshold, p.threshold);
312 let mut s: sys::transcribe_turn_session_params = unsafe { std::mem::zeroed() };
313 unsafe { sys::transcribe_turn_session_params_init(&mut s) };
314 assert_eq!(TurnSessionOptions::default().n_threads, s.n_threads);
315 }
316}