Skip to main content

transcribe_cpp/
diarize.rs

1//! [`DiarizeSession`] — the DIARIZE role (who spoke when), from [`Model::diarize_session`].
2//! Threading, lifetime, and compute-lock rules are those of [`Session`](crate::Session).
3
4use std::os::raw::c_void;
5use std::sync::atomic::AtomicBool;
6use std::sync::Arc;
7
8use transcribe_cpp_sys as sys;
9use transcribe_cpp_types::{DiarizeOptions, DiarizeSessionOptions, SpeakerSegment, Timings};
10
11use crate::cancel::{abort_trampoline, CancelToken};
12use crate::error::{check, Result};
13use crate::family::Materialize;
14use crate::model::{Model, ModelInner};
15use crate::session::clamp_len;
16use crate::types::FromRaw;
17
18/// A diarization session.
19pub struct DiarizeSession {
20    ptr: *mut sys::transcribe_diarize_session,
21    // Keeps the native model alive and carries the per-model compute lock.
22    model: Arc<ModelInner>,
23    // Keeps the abort callback's userdata alive while installed.
24    cancel: Option<Arc<AtomicBool>>,
25}
26
27impl std::fmt::Debug for DiarizeSession {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.debug_struct("DiarizeSession").finish_non_exhaustive()
30    }
31}
32
33// SAFETY: as for `Session` — `&mut self` on the mutating calls keeps use to
34// one thread at a time; deliberately NOT Sync.
35unsafe impl Send for DiarizeSession {}
36
37impl Drop for DiarizeSession {
38    fn drop(&mut self) {
39        unsafe { sys::transcribe_diarize_session_free(self.ptr) };
40    }
41}
42
43impl DiarizeSession {
44    pub(crate) fn new(model: &Model, options: &DiarizeSessionOptions) -> Result<DiarizeSession> {
45        let mut params: sys::transcribe_diarize_session_params = unsafe { std::mem::zeroed() };
46        unsafe { sys::transcribe_diarize_session_params_init(&mut params) };
47        params.n_threads = options.n_threads;
48
49        let mut out: *mut sys::transcribe_diarize_session = std::ptr::null_mut();
50        let status =
51            unsafe { sys::transcribe_diarize_session_init(model.inner.ptr, &params, &mut out) };
52        check(status, "diarize session init")?;
53        debug_assert!(!out.is_null());
54
55        Ok(DiarizeSession {
56            ptr: out,
57            model: Arc::clone(&model.inner),
58            cancel: None,
59        })
60    }
61
62    /// Install a [`CancelToken`] so an in-flight run can be aborted from
63    /// another thread (the run then returns [`Error::Aborted`](crate::Error)).
64    /// Replaces any previously installed token.
65    pub fn set_cancel_token(&mut self, token: &CancelToken) {
66        let flag = Arc::clone(&token.flag);
67        let userdata = Arc::as_ptr(&flag) as *mut c_void;
68        unsafe {
69            sys::transcribe_diarize_set_abort_callback(self.ptr, Some(abort_trampoline), userdata)
70        };
71        self.cancel = Some(flag);
72    }
73
74    /// Remove any installed cancel token.
75    pub fn clear_cancel_token(&mut self) {
76        unsafe { sys::transcribe_diarize_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
77        self.cancel = None;
78    }
79
80    /// Diarize one recording of 16 kHz mono float32 PCM. Returns the speaker
81    /// segments, grouped by speaker and time-ordered within a speaker;
82    /// segments of different speakers may overlap.
83    pub fn run(&mut self, pcm: &[f32], options: &DiarizeOptions) -> Result<Vec<SpeakerSegment>> {
84        let n = clamp_len(pcm.len())?;
85        let family = options
86            .family
87            .as_ref()
88            .map(Materialize::materialize)
89            .transpose()?;
90        let mut params: sys::transcribe_diarize_params = unsafe { std::mem::zeroed() };
91        unsafe { sys::transcribe_diarize_params_init(&mut params) };
92        params.family = family.as_ref().map_or(std::ptr::null(), |f| f.ext_ptr());
93
94        let status = self.model.with_compute(
95            Some("a stream is active on this model; finish or drop it before diarize run()"),
96            |_| unsafe { sys::transcribe_diarize_run(self.ptr, pcm.as_ptr(), n, &params) },
97        )?;
98        check(status, "diarize run")?;
99
100        let count = unsafe { sys::transcribe_diarize_n_segments(self.ptr) };
101        Ok((0..count)
102            .map(|i| {
103                let mut raw: sys::transcribe_speaker_segment = unsafe { std::mem::zeroed() };
104                unsafe { sys::transcribe_speaker_segment_init(&mut raw) };
105                let _ = unsafe { sys::transcribe_diarize_get_segment(self.ptr, i, &mut raw) };
106                SpeakerSegment::from_raw(&raw)
107            })
108            .collect())
109    }
110
111    /// Model load time plus the last run's stage timings (`decode_ms` is 0).
112    pub fn timings(&self) -> Timings {
113        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
114        unsafe { sys::transcribe_timings_init(&mut raw) };
115        let _ = unsafe { sys::transcribe_diarize_get_timings(self.ptr, &mut raw) };
116        Timings::from_raw(&raw)
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use crate::Error;
124    use std::sync::Mutex;
125
126    #[test]
127    fn run_is_busy_while_a_stream_holds_the_lease() {
128        // Null native handles (both frees are NULL no-ops): the Busy check runs
129        // under the lock before any native call.
130        let mut session = DiarizeSession {
131            ptr: std::ptr::null_mut(),
132            model: Arc::new(ModelInner {
133                ptr: std::ptr::null_mut(),
134                compute_lock: Mutex::new(true),
135            }),
136            cancel: None,
137        };
138        let err = session
139            .run(&[0.0; 160], &DiarizeOptions::default())
140            .unwrap_err();
141        let Error::Busy(msg) = err else {
142            panic!("expected Busy, got {err:?}");
143        };
144        assert_eq!(
145            msg,
146            "a stream is active on this model; finish or drop it before diarize run()"
147        );
148    }
149}