Skip to main content

transcribe_cpp_types/
types.rs

1//! Idiomatic Rust enums mirroring the C API's parameter enums.
2//!
3//! transcribe-cpp maps each to/from its `transcribe-cpp-sys` NewType.
4//! Conversions INTO C are total; conversions OUT of C validate the raw integer
5//! and fall back to a safe default for an unknown value (enum hygiene — we
6//! never assume the library only ever hands back values this version knows
7//! about).
8
9/// The task a run performs.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11#[non_exhaustive]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub enum Task {
14    /// Transcribe speech in its source language.
15    #[default]
16    Transcribe,
17    /// Translate speech into the target language (model must support it).
18    Translate,
19    /// `RunOptions::prompt` replaces the task instruction; the output is free
20    /// text in `text` / `raw_text` (model must support `Feature::Instruct`;
21    /// offline only).
22    Instruct,
23}
24
25impl Task {
26    /// The C enum value (`transcribe_task`), for transcribe-cpp's conversion. Not public
27    /// API: an exhaustive match here makes a new variant fail to compile until
28    /// it has a value, and transcribe-cpp tests every value against the header.
29    #[doc(hidden)]
30    pub const fn c_value(self) -> u32 {
31        match self {
32            Task::Transcribe => 0,
33            Task::Translate => 1,
34            Task::Instruct => 2,
35        }
36    }
37}
38
39/// Requested (or returned) timestamp granularity.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub enum TimestampKind {
43    /// Text only, no alignment data.
44    None,
45    /// "Richest the model supports" — resolved per-family at run time.
46    #[default]
47    Auto,
48    /// Segment-level start/end times.
49    Segment,
50    /// Word-level start/end times.
51    Word,
52    /// Token-level start/end times.
53    Token,
54}
55
56/// K/V activation precision for the decoder's flash-attention path.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59pub enum KvType {
60    /// f16 for quantized weights, f32 for f32 weights. The best default.
61    #[default]
62    Auto,
63    /// Full-precision K/V.
64    F32,
65    /// Half-precision K/V.
66    F16,
67}
68
69/// Punctuation + capitalization runtime toggle.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72pub enum Pnc {
73    /// The family's shipped default (what its published WER was measured at).
74    #[default]
75    Default,
76    /// Explicitly disable runtime PNC (supporting families only).
77    Off,
78    /// Explicitly enable runtime PNC (supporting families only).
79    On,
80}
81
82/// Inverse-text-normalization runtime toggle.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
85pub enum Itn {
86    /// The family's shipped default.
87    #[default]
88    Default,
89    /// Explicitly disable runtime ITN (supporting families only).
90    Off,
91    /// Explicitly enable runtime ITN (supporting families only).
92    On,
93}
94
95/// Speaker-attribution runtime toggle.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
98pub enum Diarize {
99    /// Library default: speaker attribution is disabled for every family.
100    #[default]
101    Default,
102    /// Explicitly disable speaker attribution.
103    Off,
104    /// Enable speaker attribution on supporting models.
105    On,
106}
107
108/// Which compute backend to request when loading a model.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
110#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
111pub enum Backend {
112    /// Best available device; CPU is the always-present fallback. The default.
113    #[default]
114    Auto,
115    /// Strict CPU (no GPU, no host accelerators) — the determinism choice.
116    Cpu,
117    /// CPU plus host-memory accelerators (BLAS/AMX) when present.
118    CpuAccel,
119    /// Require Metal; errors if this build has no Metal.
120    Metal,
121    /// Require Vulkan; errors if this build has no Vulkan.
122    Vulkan,
123    /// Require CUDA; errors if this build has no CUDA.
124    Cuda,
125    /// Require ROCm; errors if this build has no ROCm.
126    Rocm,
127}
128
129/// A yes/no model capability probe (`transcribe_model_supports`).
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131#[non_exhaustive]
132#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
133pub enum Feature {
134    /// The whisper run extension's initial prompt / prompt tokens.
135    InitialPrompt,
136    /// Runs a multi-tier temperature fallback loop (whisper today).
137    TemperatureFallback,
138    /// Handles audio longer than its native window in one run (whisper today).
139    LongForm,
140    /// Honors the abort callback between chunks/decode steps.
141    Cancellation,
142    /// Exposes a runtime PNC toggle.
143    Pnc,
144    /// Exposes a runtime ITN toggle.
145    Itn,
146    /// Produces structured speaker attribution.
147    Diarization,
148    /// `RunOptions::vocabulary` is formatted for this model.
149    Vocabulary,
150    /// `RunOptions::prompt` reaches a transcription-conditioning slot.
151    ContextPrompt,
152    /// Supports `Task::Instruct`.
153    Instruct,
154    /// Honors `RunOptions::prefix` as forced decoder text.
155    TranscriptPrefix,
156}
157
158impl Feature {
159    /// The C enum value (`transcribe_feature`), for transcribe-cpp's conversion. Not public
160    /// API: an exhaustive match here makes a new variant fail to compile until
161    /// it has a value, and transcribe-cpp tests every value against the header.
162    #[doc(hidden)]
163    pub const fn c_value(self) -> u32 {
164        match self {
165            Feature::InitialPrompt => 0,
166            Feature::TemperatureFallback => 1,
167            Feature::LongForm => 2,
168            Feature::Cancellation => 3,
169            Feature::Pnc => 4,
170            Feature::Itn => 5,
171            Feature::Diarization => 6,
172            Feature::Vocabulary => 7,
173            Feature::ContextPrompt => 8,
174            Feature::Instruct => 9,
175            Feature::TranscriptPrefix => 10,
176        }
177    }
178}
179
180/// When the UI-facing committed text grows during a stream.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
182#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
183pub enum CommitPolicy {
184    /// The family's stable-prefix implementation. The default.
185    #[default]
186    Auto,
187    /// Commit nothing during feed; finalize commits the final text.
188    OnFinalize,
189    /// Commit a raw prefix accepted by the stable-prefix implementation.
190    StablePrefix,
191}
192
193/// Stream lifecycle state.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
196pub enum StreamState {
197    Idle,
198    Active,
199    Finished,
200    Failed,
201}
202
203/// The slot a family extension is pointed at.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205#[non_exhaustive]
206#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
207pub enum ExtSlot {
208    /// `transcribe_run_params::family`.
209    Run,
210    /// `transcribe_stream_params::family`.
211    Stream,
212    /// `transcribe_diarize_params::family`.
213    DiarizeRun,
214}
215
216impl ExtSlot {
217    /// The C enum value (`transcribe_ext_slot`), for transcribe-cpp's conversion. Not public
218    /// API: an exhaustive match here makes a new variant fail to compile until
219    /// it has a value, and transcribe-cpp tests every value against the header.
220    #[doc(hidden)]
221    pub const fn c_value(self) -> u32 {
222        match self {
223            ExtSlot::Run => 0,
224            ExtSlot::Stream => 1,
225            ExtSlot::DiarizeRun => 2,
226        }
227    }
228}
229
230/// A kind of work a model can do (`transcribe_role`).
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232#[non_exhaustive]
233#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
234pub enum Role {
235    /// Transcription: `transcribe_cpp::Session`.
236    Asr,
237    /// Speaker diarization: `transcribe_cpp::DiarizeSession`.
238    Diarize,
239    /// Language identification: `transcribe_cpp::LangIdSession`.
240    LangId,
241    /// Voice activity detection: `transcribe_cpp::VadSession`.
242    Vad,
243    /// End-of-turn detection: `transcribe_cpp::TurnSession`.
244    Turn,
245}
246
247impl Role {
248    /// This role's `TRANSCRIBE_ROLE_*` bit. transcribe-cpp tests these against
249    /// the C header's values.
250    const fn bit(self) -> u32 {
251        match self {
252            Role::Asr => 1,
253            Role::Diarize => 2,
254            Role::LangId => 4,
255            Role::Vad => 8,
256            Role::Turn => 16,
257        }
258    }
259}
260
261/// The set of [`Role`]s a model serves (`transcribe_cpp::Model::roles`).
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
264pub struct Roles(u32);
265
266impl Roles {
267    /// A set from a raw `transcribe_role` bitmask (`TRANSCRIBE_ROLE_*` bits).
268    /// Bits this version does not know are kept.
269    pub const fn from_bits(bits: u32) -> Roles {
270        Roles(bits)
271    }
272
273    /// Whether the model serves `role`.
274    pub fn contains(self, role: Role) -> bool {
275        self.0 & role.bit() != 0
276    }
277
278    /// The raw `transcribe_role` bitmask (`TRANSCRIBE_ROLE_*` bits).
279    pub fn bits(self) -> u32 {
280        self.0
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn roles_contains_exactly_its_bits() {
290        let all = [
291            Role::Asr,
292            Role::Diarize,
293            Role::LangId,
294            Role::Vad,
295            Role::Turn,
296        ];
297        for (i, role) in all.iter().enumerate() {
298            let one = Roles::from_bits(role.bit());
299            assert_eq!(one.bits(), role.bit());
300            for (j, other) in all.iter().enumerate() {
301                assert_eq!(one.contains(*other), i == j, "{role:?} vs {other:?}");
302            }
303        }
304        let asr_vad = Roles::from_bits(Role::Asr.bit() | Role::Vad.bit() | 1 << 30);
305        assert!(asr_vad.contains(Role::Asr) && asr_vad.contains(Role::Vad));
306        assert!(!asr_vad.contains(Role::Turn));
307        assert_eq!(asr_vad.bits(), 1 | 8 | 1 << 30);
308    }
309}