Skip to main content

transcribe_cpp/
session.rs

1//! [`Session`] — a transcription context bound to a [`Model`].
2//!
3//! A session is single-threaded (`Send` but not `Sync`): `run` takes `&mut
4//! self`, so the type system enforces "one call at a time" on a given session.
5//! Across *different* sessions of one model the per-model compute lock
6//! ([`ModelInner::compute_lock`](crate::model::ModelInner)) enforces the C
7//! library's "one in-flight compute per model" rule: one-shot runs/batches
8//! serialize on it, and while a stream is in flight any overlapping
9//! run/batch/stream is refused with [`Error::Busy`].
10
11use std::ffi::CString;
12use std::os::raw::c_void;
13use std::sync::atomic::AtomicBool;
14use std::sync::Arc;
15
16use transcribe_cpp_sys as sys;
17use transcribe_cpp_types::{
18    RunOptions, Segment, SessionLimits, SessionOptions, SpeakerSegment, StreamOptions, StreamState,
19    StreamText, StreamUpdate, TimestampKind, Timings, Token, Transcript, Word,
20};
21
22use crate::cancel::{abort_trampoline, CancelToken};
23use crate::error::{check, error_for_status, Error, Result};
24use crate::family::{Materialize, RunExtRaw};
25use crate::model::{Model, ModelInner};
26use crate::result::{owned_opt_str, owned_str};
27use crate::streaming::build_stream_params;
28use crate::types::{FromRaw, ToRaw};
29
30/// A transcription session.
31pub struct Session {
32    ptr: *mut sys::transcribe_session,
33    // Keeps the native model alive (and carries the per-model run lock). The
34    // model is freed only after this Arc — and every other handle — is dropped.
35    model: Arc<ModelInner>,
36    // Retained so the abort callback's userdata pointer stays valid while
37    // installed. `None` when no cancel token is set.
38    cancel: Option<Arc<AtomicBool>>,
39}
40
41impl std::fmt::Debug for Session {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("Session").finish_non_exhaustive()
44    }
45}
46
47// SAFETY: a session may be moved between threads as long as it is used by at
48// most one at a time, which `&mut self` on the mutating calls enforces. It is
49// deliberately NOT Sync.
50unsafe impl Send for Session {}
51
52impl Drop for Session {
53    fn drop(&mut self) {
54        unsafe { sys::transcribe_session_free(self.ptr) };
55        // self.model Arc is dropped here, possibly freeing the model.
56    }
57}
58
59impl Session {
60    pub(crate) fn new(model: &Model, options: &SessionOptions) -> Result<Session> {
61        let mut params: sys::transcribe_session_params = unsafe { std::mem::zeroed() };
62        unsafe { sys::transcribe_session_params_init(&mut params) };
63        params.n_threads = options.n_threads;
64        params.kv_type = options.kv_type.to_raw();
65        params.n_ctx = options.n_ctx;
66
67        let mut out: *mut sys::transcribe_session = std::ptr::null_mut();
68        let status = unsafe { sys::transcribe_session_init(model.inner.ptr, &params, &mut out) };
69        check(status, "session init")?;
70        debug_assert!(!out.is_null());
71
72        Ok(Session {
73            ptr: out,
74            model: Arc::clone(&model.inner),
75            cancel: None,
76        })
77    }
78
79    /// Install a [`CancelToken`] so an in-flight run/stream can be aborted from
80    /// another thread. Replaces any previously installed token. The token's
81    /// flag is shared, so cancel via any clone of it. (Cancellation only takes
82    /// effect on models whose family honors the abort callback —
83    /// [`Feature::Cancellation`](crate::Feature::Cancellation).)
84    pub fn set_cancel_token(&mut self, token: &CancelToken) {
85        let flag = Arc::clone(&token.flag);
86        let userdata = Arc::as_ptr(&flag) as *mut c_void;
87        // SAFETY: single-threaded session contract — no run is in flight when
88        // this is called. The new callback is installed before the old retained
89        // Arc is dropped, so the previous userdata is never dangling-referenced.
90        unsafe { sys::transcribe_set_abort_callback(self.ptr, Some(abort_trampoline), userdata) };
91        self.cancel = Some(flag);
92    }
93
94    /// Remove any installed cancel token.
95    pub fn clear_cancel_token(&mut self) {
96        unsafe { sys::transcribe_set_abort_callback(self.ptr, None, std::ptr::null_mut()) };
97        self.cancel = None;
98    }
99
100    /// Whether the most recent run/stream was ended by cancellation.
101    pub fn was_aborted(&self) -> bool {
102        unsafe { sys::transcribe_was_aborted(self.ptr) }
103    }
104
105    /// Whether the most recent decode stopped before end-of-stream, at the
106    /// generation budget or because the output began repeating (the transcript
107    /// is incomplete).
108    pub fn was_truncated(&self) -> bool {
109        unsafe { sys::transcribe_was_truncated(self.ptr) }
110    }
111
112    /// Transcribe one buffer of 16 kHz mono float32 PCM in `[-1, 1]`.
113    ///
114    /// On an aborted, truncated, or repetition-stopped decode the partial
115    /// transcript is preserved on the returned [`Error::Aborted`] /
116    /// [`Error::OutputTruncated`] / [`Error::OutputRepetition`].
117    pub fn run(&mut self, pcm: &[f32], options: &RunOptions) -> Result<Transcript> {
118        let (params, _lang, _target, _family, _prompting) = build_run_params(options)?;
119        let n = clamp_len(pcm.len())?;
120
121        let status = self.model.with_compute(
122            Some("a stream is active on this model; finish or drop it before run()"),
123            |_| unsafe { sys::transcribe_run(self.ptr, pcm.as_ptr(), n, &params) },
124        )?;
125
126        match status {
127            s if s == sys::transcribe_status::TRANSCRIBE_OK => Ok(self.materialize_run()),
128            s if s == sys::transcribe_status::TRANSCRIBE_ERR_ABORTED
129                || s == sys::transcribe_status::TRANSCRIBE_ERR_OUTPUT_TRUNCATED
130                || s == sys::transcribe_status::TRANSCRIBE_ERR_OUTPUT_REPETITION =>
131            {
132                // Partial transcript is preserved by the C API for all three.
133                let partial = Box::new(self.materialize_run());
134                Err(attach_partial(error_for_status(s, "run"), partial))
135            }
136            s => Err(error_for_status(s, "run")),
137        }
138    }
139
140    /// Transcribe several buffers in one call (throughput path).
141    ///
142    /// Returns the whole-batch outcome as an outer `Result`; each utterance's
143    /// individual outcome is an inner `Result` in the returned vector (one per
144    /// input, in order). A malformed single utterance fails only its own slot.
145    pub fn run_batch(
146        &mut self,
147        pcms: &[&[f32]],
148        options: &RunOptions,
149    ) -> Result<Vec<Result<Transcript>>> {
150        let (params, _lang, _target, _family, _prompting) = build_run_params(options)?;
151        let ptrs: Vec<*const f32> = pcms.iter().map(|p| p.as_ptr()).collect();
152        let lens: Vec<i32> = pcms
153            .iter()
154            .map(|p| clamp_len(p.len()))
155            .collect::<Result<_>>()?;
156        let n = clamp_len(pcms.len())?;
157
158        let status = self.model.with_compute(
159            Some("a stream is active on this model; finish or drop it before run_batch()"),
160            |_| unsafe {
161                sys::transcribe_run_batch(self.ptr, ptrs.as_ptr(), lens.as_ptr(), n, &params)
162            },
163        )?;
164
165        // OK and ABORTED both populate one per-utterance slot per input; fold
166        // the batch-level abort into the per-utterance view (the C contract).
167        let ok = status == sys::transcribe_status::TRANSCRIBE_OK
168            || status == sys::transcribe_status::TRANSCRIBE_ERR_ABORTED;
169        if !ok {
170            return Err(error_for_status(status, "run_batch"));
171        }
172
173        let count = unsafe { sys::transcribe_batch_n_results(self.ptr) };
174        let mut results = Vec::with_capacity(count.max(0) as usize);
175        for i in 0..count {
176            let st = unsafe { sys::transcribe_batch_status(self.ptr, i) };
177            if st == sys::transcribe_status::TRANSCRIBE_OK {
178                results.push(Ok(self.materialize_batch(i)));
179            } else if st == sys::transcribe_status::TRANSCRIBE_ERR_ABORTED
180                || st == sys::transcribe_status::TRANSCRIBE_ERR_OUTPUT_TRUNCATED
181                || st == sys::transcribe_status::TRANSCRIBE_ERR_OUTPUT_REPETITION
182            {
183                let partial = Box::new(self.materialize_batch(i));
184                let err = attach_partial(error_for_status(st, "run_batch utterance"), partial);
185                results.push(Err(err));
186            } else {
187                results.push(Err(error_for_status(st, "run_batch utterance")));
188            }
189        }
190        Ok(results)
191    }
192
193    /// The effective per-session limits.
194    pub fn limits(&self) -> Result<SessionLimits> {
195        let mut out: sys::transcribe_session_limits = unsafe { std::mem::zeroed() };
196        unsafe { sys::transcribe_session_limits_init(&mut out) };
197        let status = unsafe { sys::transcribe_session_get_limits(self.ptr, &mut out) };
198        check(status, "session limits")?;
199        Ok(SessionLimits {
200            effective_n_ctx: out.effective_n_ctx,
201            effective_max_audio_ms: out.effective_max_audio_ms,
202            max_kv_bytes: out.max_kv_bytes,
203        })
204    }
205
206    /// The model this session is bound to.
207    pub fn model(&self) -> Model {
208        Model {
209            inner: Arc::clone(&self.model),
210        }
211    }
212
213    /// Begin a streaming run, returning a [`Stream`] that borrows this session
214    /// for its lifetime (so the session can't be used for an offline `run`
215    /// while a stream is active). `run` supplies task / language / timestamps /
216    /// vocabulary / prompt;
217    /// `stream` supplies the commit policy and any stream-slot family extension.
218    /// Dropping the returned `Stream` abandons it and returns the session to
219    /// idle.
220    pub fn stream(&mut self, run: &RunOptions, stream: &StreamOptions) -> Result<Stream<'_>> {
221        let (run_params, _lang, _target, _family, _prompting) = build_run_params(run)?;
222        let (stream_params, _stream_family) = build_stream_params(stream)?;
223        // Claim the model's compute lease for the whole stream lifetime: a
224        // stream spans begin..drop, so per-call locking alone would let a
225        // second stream (or a run) on another session race it.
226        self.model.with_compute(
227            Some("a stream is already active on this model"),
228            |lease| -> Result<()> {
229                check(
230                    unsafe { sys::transcribe_stream_begin(self.ptr, &run_params, &stream_params) },
231                    "stream begin",
232                )?;
233                *lease = true; // released at finalize/reset, or by Stream::drop
234                Ok(())
235            },
236        )??;
237        Ok(Stream {
238            session: self,
239            holds_lease: true,
240        })
241    }
242
243    // --- result materialization (top-level / single accessors) ---------------
244
245    fn materialize_run(&self) -> Transcript {
246        let n_seg = unsafe { sys::transcribe_n_segments(self.ptr) };
247        let n_word = unsafe { sys::transcribe_n_words(self.ptr) };
248        let n_tok = unsafe { sys::transcribe_n_tokens(self.ptr) };
249        let n_speaker = unsafe { sys::transcribe_n_speaker_segments(self.ptr) };
250
251        Transcript {
252            text: owned_str(unsafe { sys::transcribe_full_text(self.ptr) }),
253            raw_text: owned_str(unsafe { sys::transcribe_raw_text(self.ptr) }),
254            language: owned_opt_str(unsafe { sys::transcribe_detected_language(self.ptr) }),
255            timestamp_kind: TimestampKind::from_raw(unsafe {
256                sys::transcribe_returned_timestamp_kind(self.ptr)
257            }),
258            segments: (0..n_seg).map(|i| self.segment(i)).collect(),
259            speaker_segments: (0..n_speaker).map(|i| self.speaker_segment(i)).collect(),
260            words: (0..n_word).map(|i| self.word(i)).collect(),
261            tokens: (0..n_tok).map(|i| self.token(i)).collect(),
262            timings: self.timings(),
263        }
264    }
265
266    fn segment(&self, i: i32) -> Segment {
267        let mut raw: sys::transcribe_segment = unsafe { std::mem::zeroed() };
268        unsafe { sys::transcribe_segment_init(&mut raw) };
269        let _ = unsafe { sys::transcribe_get_segment(self.ptr, i, &mut raw) };
270        Segment::from_raw(&raw)
271    }
272
273    fn speaker_segment(&self, i: i32) -> SpeakerSegment {
274        let mut raw: sys::transcribe_speaker_segment = unsafe { std::mem::zeroed() };
275        unsafe { sys::transcribe_speaker_segment_init(&mut raw) };
276        let _ = unsafe { sys::transcribe_get_speaker_segment(self.ptr, i, &mut raw) };
277        SpeakerSegment::from_raw(&raw)
278    }
279
280    fn word(&self, i: i32) -> Word {
281        let mut raw: sys::transcribe_word = unsafe { std::mem::zeroed() };
282        unsafe { sys::transcribe_word_init(&mut raw) };
283        let _ = unsafe { sys::transcribe_get_word(self.ptr, i, &mut raw) };
284        Word::from_raw(&raw)
285    }
286
287    fn token(&self, i: i32) -> Token {
288        let mut raw: sys::transcribe_token = unsafe { std::mem::zeroed() };
289        unsafe { sys::transcribe_token_init(&mut raw) };
290        let _ = unsafe { sys::transcribe_get_token(self.ptr, i, &mut raw) };
291        Token::from_raw(&raw)
292    }
293
294    fn timings(&self) -> Timings {
295        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
296        unsafe { sys::transcribe_timings_init(&mut raw) };
297        let _ = unsafe { sys::transcribe_get_timings(self.ptr, &mut raw) };
298        Timings::from_raw(&raw)
299    }
300
301    // --- result materialization (batch accessors, utterance i) ---------------
302
303    fn materialize_batch(&self, i: i32) -> Transcript {
304        let n_seg = unsafe { sys::transcribe_batch_n_segments(self.ptr, i) };
305        let n_word = unsafe { sys::transcribe_batch_n_words(self.ptr, i) };
306        let n_tok = unsafe { sys::transcribe_batch_n_tokens(self.ptr, i) };
307        let n_speaker = unsafe { sys::transcribe_batch_n_speaker_segments(self.ptr, i) };
308
309        Transcript {
310            text: owned_str(unsafe { sys::transcribe_batch_full_text(self.ptr, i) }),
311            raw_text: owned_str(unsafe { sys::transcribe_batch_raw_text(self.ptr, i) }),
312            language: owned_opt_str(unsafe {
313                sys::transcribe_batch_detected_language(self.ptr, i)
314            }),
315            timestamp_kind: TimestampKind::from_raw(unsafe {
316                sys::transcribe_batch_returned_timestamp_kind(self.ptr, i)
317            }),
318            segments: (0..n_seg).map(|j| self.batch_segment(i, j)).collect(),
319            speaker_segments: (0..n_speaker)
320                .map(|j| self.batch_speaker_segment(i, j))
321                .collect(),
322            words: (0..n_word).map(|j| self.batch_word(i, j)).collect(),
323            tokens: (0..n_tok).map(|j| self.batch_token(i, j)).collect(),
324            timings: self.batch_timings(i),
325        }
326    }
327
328    fn batch_segment(&self, i: i32, j: i32) -> Segment {
329        let mut raw: sys::transcribe_segment = unsafe { std::mem::zeroed() };
330        unsafe { sys::transcribe_segment_init(&mut raw) };
331        let _ = unsafe { sys::transcribe_batch_get_segment(self.ptr, i, j, &mut raw) };
332        Segment::from_raw(&raw)
333    }
334
335    fn batch_speaker_segment(&self, i: i32, j: i32) -> SpeakerSegment {
336        let mut raw: sys::transcribe_speaker_segment = unsafe { std::mem::zeroed() };
337        unsafe { sys::transcribe_speaker_segment_init(&mut raw) };
338        let _ = unsafe { sys::transcribe_batch_get_speaker_segment(self.ptr, i, j, &mut raw) };
339        SpeakerSegment::from_raw(&raw)
340    }
341
342    fn batch_word(&self, i: i32, j: i32) -> Word {
343        let mut raw: sys::transcribe_word = unsafe { std::mem::zeroed() };
344        unsafe { sys::transcribe_word_init(&mut raw) };
345        let _ = unsafe { sys::transcribe_batch_get_word(self.ptr, i, j, &mut raw) };
346        Word::from_raw(&raw)
347    }
348
349    fn batch_token(&self, i: i32, j: i32) -> Token {
350        let mut raw: sys::transcribe_token = unsafe { std::mem::zeroed() };
351        unsafe { sys::transcribe_token_init(&mut raw) };
352        let _ = unsafe { sys::transcribe_batch_get_token(self.ptr, i, j, &mut raw) };
353        Token::from_raw(&raw)
354    }
355
356    fn batch_timings(&self, i: i32) -> Timings {
357        let mut raw: sys::transcribe_timings = unsafe { std::mem::zeroed() };
358        unsafe { sys::transcribe_timings_init(&mut raw) };
359        let _ = unsafe { sys::transcribe_batch_get_timings(self.ptr, i, &mut raw) };
360        Timings::from_raw(&raw)
361    }
362}
363
364/// Everything that must outlive a `transcribe_run` call: the params struct
365/// plus the heap buffers its pointers borrow (language strings, family ext).
366type RunParamsBundle = (
367    sys::transcribe_run_params,
368    Option<CString>,
369    Option<CString>,
370    Option<RunExtRaw>,
371    PromptingKeepalive,
372);
373
374/// Owns the buffers behind the prompting pointers of a `transcribe_run_params`.
375struct PromptingKeepalive {
376    _terms: Vec<CString>,
377    _term_ptrs: Vec<*const std::os::raw::c_char>,
378    _prompt: Option<CString>,
379    _prefix: Option<CString>,
380}
381
382/// Build `transcribe_run_params` from options. The returned keepalives own the
383/// buffers the params' pointers borrow, so the caller must hold them for the
384/// duration of the native call.
385fn build_run_params(o: &RunOptions) -> Result<RunParamsBundle> {
386    let mut params: sys::transcribe_run_params = unsafe { std::mem::zeroed() };
387    unsafe { sys::transcribe_run_params_init(&mut params) };
388
389    params.task = o.task.to_raw();
390    params.timestamps = o.timestamps.to_raw();
391    params.pnc = o.pnc.to_raw();
392    params.itn = o.itn.to_raw();
393    params.diarize = o.diarize.to_raw();
394    params.keep_special_tags = o.keep_special_tags;
395    params.spec_k_drafts = o.spec_k_drafts;
396
397    let lang = o.language.as_deref().map(CString::new).transpose()?;
398    let target = o.target_language.as_deref().map(CString::new).transpose()?;
399    params.language = lang.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
400    params.target_language = target.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
401
402    let family = o
403        .family
404        .as_ref()
405        .map(Materialize::materialize)
406        .transpose()?;
407    params.family = family.as_ref().map_or(std::ptr::null(), |f| f.ext_ptr());
408
409    let terms = o
410        .vocabulary
411        .iter()
412        .map(|t| CString::new(t.as_str()))
413        .collect::<std::result::Result<Vec<_>, _>>()?;
414    let term_ptrs: Vec<*const std::os::raw::c_char> = terms.iter().map(|c| c.as_ptr()).collect();
415    let prompt = o.prompt.as_deref().map(CString::new).transpose()?;
416    let prefix = o.prefix.as_deref().map(CString::new).transpose()?;
417    params.vocabulary = if term_ptrs.is_empty() {
418        std::ptr::null()
419    } else {
420        term_ptrs.as_ptr()
421    };
422    params.n_vocabulary = clamp_len(term_ptrs.len())?;
423    params.prompt = prompt.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
424    params.prefix = prefix.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
425    let prompting = PromptingKeepalive {
426        _terms: terms,
427        _term_ptrs: term_ptrs,
428        _prompt: prompt,
429        _prefix: prefix,
430    };
431
432    Ok((params, lang, target, family, prompting))
433}
434
435/// PCM/utterance lengths cross the ABI as `int`; reject anything that overflows.
436pub(crate) fn clamp_len(len: usize) -> Result<i32> {
437    i32::try_from(len).map_err(|_| Error::InvalidArgument(format!("length {len} exceeds i32::MAX")))
438}
439
440/// Replace the (partial-less) Aborted/OutputTruncated/OutputRepetition error
441/// with one carrying the materialized partial transcript.
442fn attach_partial(err: Error, partial: Box<Transcript>) -> Error {
443    match err {
444        Error::Aborted { message, .. } => Error::Aborted {
445            message,
446            partial: Some(partial),
447        },
448        Error::OutputTruncated { message, .. } => Error::OutputTruncated {
449            message,
450            partial: Some(partial),
451        },
452        Error::OutputRepetition { message, .. } => Error::OutputRepetition {
453            message,
454            partial: Some(partial),
455        },
456        other => other,
457    }
458}
459
460/// An active streaming run, borrowed from a [`Session`].
461///
462/// Feed PCM with [`Stream::feed`], read the UI-stable text with
463/// [`Stream::text`], and end input with [`Stream::finalize`]. Dropping the
464/// `Stream` (without finalizing) abandons it and returns the session to idle.
465/// `Send` but not `Sync`, like the session it borrows.
466///
467/// The borrow means a session can't be freed while its stream (or any other
468/// call on it) is still in use, so no native free ever races a compute:
469///
470/// ```compile_fail,E0505
471/// use transcribe_cpp::{Model, RunOptions, StreamOptions};
472/// let model = Model::load("model.gguf").unwrap();
473/// let mut session = model.session().unwrap();
474/// let mut stream = session
475///     .stream(&RunOptions::default(), &StreamOptions::default())
476///     .unwrap();
477/// drop(session); // error[E0505]: cannot move out of `session` while borrowed
478/// stream.feed(&[0.0; 160]).unwrap();
479/// ```
480pub struct Stream<'a> {
481    session: &'a mut Session,
482    // True while this stream holds the model's compute lease. Set at begin,
483    // cleared the moment the stream stops being active (finalize/reset) or on
484    // drop — whichever comes first. Tracked per-stream so drop never releases a
485    // lease a *different* session has since acquired.
486    holds_lease: bool,
487}
488
489impl std::fmt::Debug for Stream<'_> {
490    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491        f.debug_struct("Stream")
492            .field("state", &self.state())
493            .field("revision", &self.revision())
494            .finish()
495    }
496}
497
498impl Drop for Stream<'_> {
499    fn drop(&mut self) {
500        self.reset()
501    }
502}
503
504impl Stream<'_> {
505    /// Feed a chunk of 16 kHz mono float32 PCM and return the change metadata.
506    pub fn feed(&mut self, pcm: &[f32]) -> Result<StreamUpdate> {
507        let n = clamp_len(pcm.len())?;
508        let mut update: sys::transcribe_stream_update = unsafe { std::mem::zeroed() };
509        unsafe { sys::transcribe_stream_update_init(&mut update) };
510        // This stream already holds the model's compute lease (it is in
511        // flight); the lock here just serializes the native call. A feed that
512        // ends the stream (FAILED) frees the lease, as finalize does; a feed
513        // rejected before the native hook (e.g. NaN) leaves it ACTIVE and keeps it.
514        let ptr = self.session.ptr;
515        let held = self.holds_lease;
516        let (status, ended) = self.session.model.with_compute(None, |lease| {
517            let st = unsafe { sys::transcribe_stream_feed(ptr, pcm.as_ptr(), n, &mut update) };
518            let ended = unsafe { sys::transcribe_stream_get_state(ptr) }
519                == sys::transcribe_stream_state::TRANSCRIBE_STREAM_FAILED;
520            if held && ended {
521                *lease = false;
522            }
523            (st, ended)
524        })?;
525        if ended {
526            self.holds_lease = false;
527        }
528        check(status, "stream feed")?;
529        Ok(StreamUpdate::from_raw(&update))
530    }
531
532    /// Signal end of input: flush buffered audio and emit the final text. The
533    /// session transitions to finished.
534    pub fn finalize(&mut self) -> Result<StreamUpdate> {
535        let mut update: sys::transcribe_stream_update = unsafe { std::mem::zeroed() };
536        unsafe { sys::transcribe_stream_update_init(&mut update) };
537        let status = self.session.model.with_compute(None, |lease| {
538            let st = unsafe { sys::transcribe_stream_finalize(self.session.ptr, &mut update) };
539            // Finalize ends the active stream (Finished, or Failed on error);
540            // either way it is no longer active, so free the model's compute
541            // lease now rather than holding other sessions off until drop.
542            if self.holds_lease {
543                *lease = false;
544            }
545            st
546        })?;
547        self.holds_lease = false;
548        check(status, "stream finalize")?;
549        Ok(StreamUpdate::from_raw(&update))
550    }
551
552    /// Abandon the stream and return the session to idle (clears all snapshot
553    /// state). Releases the model's compute lease (the stream is no longer
554    /// active), so other sessions of the model can proceed without waiting for
555    /// this `Stream` to drop.
556    pub fn reset(&mut self) {
557        // Releases the lease only if this stream holds it (it may be another session's).
558        let _ = self.session.model.with_compute(None, |lease| {
559            unsafe { sys::transcribe_stream_reset(self.session.ptr) };
560            if self.holds_lease {
561                *lease = false;
562            }
563        });
564        self.holds_lease = false;
565    }
566
567    /// The current UI-facing text snapshot (owned copies).
568    pub fn text(&self) -> StreamText {
569        let mut raw: sys::transcribe_stream_text = unsafe { std::mem::zeroed() };
570        unsafe { sys::transcribe_stream_text_init(&mut raw) };
571        let _ = unsafe { sys::transcribe_stream_get_text(self.session.ptr, &mut raw) };
572        StreamText::from_raw(&raw)
573    }
574
575    /// A full structured snapshot (segments/words/tokens) of the current
576    /// hypothesis. For most UIs [`Stream::text`] is the better choice.
577    pub fn snapshot(&self) -> Transcript {
578        self.session.materialize_run()
579    }
580
581    /// The stream's lifecycle state.
582    pub fn state(&self) -> StreamState {
583        StreamState::from_raw(unsafe { sys::transcribe_stream_get_state(self.session.ptr) })
584    }
585
586    /// The monotonic snapshot revision; diff against the previous value.
587    pub fn revision(&self) -> i32 {
588        unsafe { sys::transcribe_stream_revision(self.session.ptr) }
589    }
590
591    /// The stream's recorded terminal failure, or `None` while it is healthy.
592    ///
593    /// Set after a [`feed`](Self::feed) / [`finalize`](Self::finalize)
594    /// transitioned the stream to [`StreamState::Failed`]; reset by a new
595    /// stream. Inspect it when [`state`](Self::state) is `Failed` to learn why.
596    pub fn last_status(&self) -> Option<Error> {
597        let status = unsafe { sys::transcribe_stream_last_status(self.session.ptr) };
598        if status == sys::transcribe_status::TRANSCRIBE_OK {
599            None
600        } else {
601            Some(error_for_status(status, "stream"))
602        }
603    }
604
605    /// Whether the stream was ended by cancellation.
606    pub fn was_aborted(&self) -> bool {
607        self.session.was_aborted()
608    }
609}