coqui_stt/
stream.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use crate::{Metadata, Model};
use std::ffi::CStr;

/// Streaming inference state.
pub struct Stream<'a> {
    pub(crate) model: &'a mut Model,
    pub(crate) state: *mut coqui_stt_sys::StreamingState,
    /// True if this state has already been freed.
    /// This is used to prevent double-freeing.
    pub(crate) already_freed: bool,
}

// NOTE:
// Streams are thread-safe, with one major caveat:
// they cannot be used from multiple threads concurrently.
// The only reason we can safely implement Sync is because
// the compiler statically enforces that this is used from
// only one thread at a time with mutable references on all
// functions that access the C API.
unsafe impl Send for Stream<'_> {}
unsafe impl Sync for Stream<'_> {}

impl Drop for Stream<'_> {
    #[inline]
    fn drop(&mut self) {
        if !self.already_freed {
            unsafe { coqui_stt_sys::STT_FreeStream(self.state) }
        }
    }
}

impl<'a> Stream<'a> {
    /// Create a new `Stream` from a [`Model`](Model).
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[allow(clippy::missing_inline_in_public_items)]
    pub fn from_model(model: &'a mut Model) -> crate::Result<Stream<'a>> {
        let mut state = std::ptr::null_mut::<coqui_stt_sys::StreamingState>();

        let retval =
            unsafe { coqui_stt_sys::STT_CreateStream(model.0, std::ptr::addr_of_mut!(state)) };

        if let Some(e) = crate::Error::from_c_int(retval) {
            return Err(e);
        }

        if state.is_null() {
            return Err(crate::Error::Unknown);
        }

        Ok(Self {
            model,
            state,
            already_freed: false,
        })
    }

    /// Get the inner pointer to the [`StreamingState`](coqui_stt_sys::StreamingState)
    /// of this `Stream`.
    ///
    /// # Safety
    /// Once this is called, the memory management of the `Stream` is no longer handled for you.
    ///
    /// The [`Model`] object this stream points to must not be disposed of until this `Stream` is disposed of.
    ///
    /// Once you are done with the pointer, to dispose of the state properly,
    /// you must not forget to either (NOT BOTH):
    /// * call [`STT_FreeStream`],
    /// * recreate this object with [`from_ptr`]
    ///
    /// [`Model`]: Model
    /// [`STT_FreeStream`]: coqui_stt_sys::STT_FreeStream
    /// [`from_ptr`]: Stream::from_ptr
    #[inline]
    #[must_use]
    pub unsafe fn into_state(mut self) -> *mut coqui_stt_sys::StreamingState {
        self.already_freed = true;
        self.state
    }

    /// Recreate a `Stream` with a pointer to a [`StreamingState`]
    /// and a pointer to the model the [`StreamingState`] references.
    ///
    /// # Safety
    /// * The `state` must point to a valid [`StreamingState`].
    /// * The `model` must point to the exact same [`Model`] the original `state` was created with.
    ///
    /// [`StreamingState`]: coqui_stt_sys::StreamingState
    /// [`Model`]: Model
    #[inline]
    pub unsafe fn from_ptr(
        model: &'a mut Model,
        state: *mut coqui_stt_sys::StreamingState,
    ) -> Stream<'a> {
        Self {
            model,
            state,
            already_freed: false,
        }
    }

    /// Return a reference to the [`Model`](crate::Model) this `Stream` references.
    #[inline]
    #[must_use]
    pub fn model(&self) -> &Model {
        self.model
    }

    /// Return a mutable reference to the [`Model`](crate::Model) this wraps.
    #[inline]
    #[must_use]
    pub fn model_mut(&mut self) -> &mut Model {
        self.model
    }

    /// Feed audio samples to an ongoing streaming inference.
    #[inline]
    pub fn feed_audio(&mut self, buffer: &[i16]) {
        unsafe {
            coqui_stt_sys::STT_FeedAudioContent(
                self.state,
                buffer.as_ptr(),
                buffer.len() as std::os::raw::c_uint,
            );
        }
    }

    /// Compute the intermediate decoding of an ongoing streaming inference.
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[allow(clippy::missing_inline_in_public_items)]
    pub fn intermediate_decode(&mut self) -> crate::Result<String> {
        let ptr = unsafe { coqui_stt_sys::STT_IntermediateDecode(self.state as *const _) };

        if ptr.is_null() {
            return Err(crate::Error::Unknown);
        }

        // SAFETY: STT_SpeechToText will always return a valid CStr
        let cstr = unsafe { CStr::from_ptr(ptr) };
        let mut unchecked_str = Vec::new();
        unchecked_str.extend_from_slice(cstr.to_bytes());

        // SAFETY: the pointer the string points to is not used anywhere after this call
        unsafe { coqui_stt_sys::STT_FreeString(ptr) }

        Ok(String::from_utf8(unchecked_str)?)
    }

    /// Compute the intermediate decoding of an ongoing streaming inference,
    /// return results including metadata.
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[inline]
    pub fn intermediate_decode_with_metadata(
        &mut self,
        num_results: u32,
    ) -> crate::Result<Metadata> {
        let ptr =
            unsafe { coqui_stt_sys::STT_IntermediateDecodeWithMetadata(self.state, num_results) };

        if ptr.is_null() {
            return Err(crate::Error::Unknown);
        }

        Ok(crate::Metadata::new(ptr))
    }

    /// **EXPERIMENTAL**: Compute the intermediate decoding of an ongoing streaming inference,
    /// flushing buffers first.
    ///
    /// This ensures that all audio that has been streamed so far is included in the result,
    /// but is more expensive than [`intermediate_decode`](Stream::intermediate_decode)
    /// because buffers are processed through the acoustic model.
    ///
    /// Calling this function too often will also degrade transcription accuracy due to
    /// trashing of the LSTM hidden state vectors.
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[allow(clippy::missing_inline_in_public_items)]
    pub fn intermediate_decode_with_buffer_flush(&mut self) -> crate::Result<String> {
        let ptr = unsafe { coqui_stt_sys::STT_IntermediateDecodeFlushBuffers(self.state) };

        if ptr.is_null() {
            return Err(crate::Error::Unknown);
        }

        // SAFETY: STT_SpeechToText will always return a valid CStr
        let cstr = unsafe { CStr::from_ptr(ptr) };
        let mut unchecked_str = Vec::new();
        unchecked_str.extend_from_slice(cstr.to_bytes());

        // SAFETY: the pointer the string points to is not used anywhere after this call
        unsafe { coqui_stt_sys::STT_FreeString(ptr) }

        Ok(String::from_utf8(unchecked_str)?)
    }

    /// **EXPERIMENTAL**: Compute the intermediate decoding of an ongoing streaming inference,
    /// flushing buffers first.
    ///
    /// This ensures that all audio that has been streamed so far is included in the result,
    /// but is more expensive than
    /// [`intermediate_decode_with_metadata`](Stream::intermediate_decode_with_metadata)
    /// because buffers are processed through the acoustic model.
    ///
    /// Calling this function too often will also degrade transcription accuracy due to
    /// trashing of the LSTM hidden state vectors.
    ///
    /// Returns results including metadata.
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[inline]
    pub fn intermediate_decode_with_metadata_and_buffer_flush(
        &mut self,
        num_results: u32,
    ) -> crate::Result<Metadata> {
        let ptr = unsafe {
            coqui_stt_sys::STT_IntermediateDecodeWithMetadataFlushBuffers(self.state, num_results)
        };

        if ptr.is_null() {
            return Err(crate::Error::Unknown);
        }

        Ok(crate::Metadata::new(ptr))
    }

    /// Compute the final decoding of an ongoing streaming inference and
    /// return the result.
    /// Signals the end of an ongoing streaming inference.
    ///
    /// Destroys this stream object.
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[allow(clippy::missing_inline_in_public_items)]
    pub fn finish_stream(mut self) -> crate::Result<String> {
        let ptr = unsafe { coqui_stt_sys::STT_FinishStream(self.state) };

        self.already_freed = true;

        if ptr.is_null() {
            return Err(crate::Error::Unknown);
        }

        // SAFETY: STT_SpeechToText will always return a valid CStr
        let cstr = unsafe { CStr::from_ptr(ptr) };
        let mut unchecked_str = Vec::new();
        unchecked_str.extend_from_slice(cstr.to_bytes());

        // SAFETY: the pointer the string points to is not used anywhere after this call
        unsafe { coqui_stt_sys::STT_FreeString(ptr) }

        Ok(String::from_utf8(unchecked_str)?)
    }

    /// Compute the final decoding of an ongoing streaming inference
    /// and return results including metadata.
    /// Signals the end of an ongoing streaming inference.
    ///
    /// Destroys this stream object.
    ///
    /// `num_results` is the maximum number of possible transcriptions to return.
    /// Note that it is not guaranteed this many will be returned at minimum,
    /// but there will never be more than this number at maximum.
    ///
    /// # Errors
    /// Passes through any errors from the C library. See enum [`Error`](crate::Error).
    #[inline]
    pub fn finish_stream_with_metadata(mut self, num_results: u32) -> crate::Result<Metadata> {
        let ptr = unsafe { coqui_stt_sys::STT_FinishStreamWithMetadata(self.state, num_results) };

        self.already_freed = true;

        if ptr.is_null() {
            return Err(crate::Error::Unknown);
        }

        Ok(crate::Metadata::new(ptr))
    }
}