hex/src/transcription/engine.rs
Dax 1bbfc8dfa1
dictation: don't count audio before output suppression as missed opening speech (#2338) (#2514)
With Lower audio, Mute, or Pause media, a hotkey capture keeps no pre-roll
and asks for output suppression only once it passes the 300 ms hold; Lower
audio then ramps over 120 ms on its own thread. Audio still coming from the
speakers in that window was counted as speech the stream missed, so nearly
every dictation with something playing fell back to the whole clip.

The recording environment now reports the moment suppression actually
changed the output, and only when it did: Lower audio sends when the ramp
first writes its full target, from the ramp's own thread, so a late Bluetooth
readback no longer delays it; Mute when the write lands over a non-zero
volume; Pause media the latest of the player pause command being issued and
the browser pause being sent, without the browser's confirmation windows. The
report is asynchronous, so stopping or another session is never held up
behind a ramp. Nothing is reported when the effect changed nothing, was
skipped on headphones under Labs › Only on speakers, or was stopped before
the target was written.

The audio owner maps the reported moment onto the recorded timeline and adds
a 40 ms speaker-to-microphone margin; up to one resampler input buffer may
still be unprocessed, so the position can sit slightly early, which only ever
ignores less speech. The live stream's head is raised with
Command::IgnoreHead, applied before it finalizes if it arrives before Finish;
one after the finish is ignored.

Checks: a_reported_effect_raises_the_head_from_the_recorded_timeline,
media_speech_before_output_suppression_took_effect_is_not_a_lost_opening,
speech_after_the_raised_head_is_still_a_lost_opening,
a_head_raised_before_the_finish_keeps_the_stream,
a_head_raised_after_the_finish_cannot_save_the_stream,
a_guard_reports_when_the_target_is_written_not_when_the_readback_settles,
a_guard_that_changes_nothing_reports_no_moment, and
muting_an_already_silent_output_changes_nothing. Linux and Windows keep their
current head (ROADMAP). Not measured on a microphone or a device.
2026-11-23 07:09:11 -05:00

3338 lines
124 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! The thread that owns the loaded GGUF model and runs all of its inference.
//!
//! A capture that the model can stream is fed while the shortcut is held, so
//! release only decodes the last second or two of audio. Every finish carries
//! the complete clip: a stream that failed, stalled, or produced no text is
//! replaced by an offline transcription of that clip, and a model or device
//! that cannot stream always takes the offline path. Commands are handled in
//! order on one thread, because a live stream holds the model's compute lease.
use std::collections::VecDeque;
mod slot;
mod streaming;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, eyre};
use transcribe_cpp::CancelToken;
use slot::{HeldState, ModelSlot};
use streaming::*;
/// The model the engine owns: macOS keeps its warm, switchable transcriber
/// (GGUF or Apple Speech); Linux and Windows load one GGUF model.
#[cfg(target_os = "macos")]
pub(crate) type Model = crate::transcription::WarmTranscriber;
#[cfg(not(target_os = "macos"))]
pub(crate) type Model = crate::transcription::local_transcriber::LocalTranscriber;
/// Transcribes a complete 16 kHz clip offline on the engine thread.
pub(crate) type Offline = Box<dyn FnOnce(&mut Model, Vec<f32>) -> Result<String, String> + Send>;
/// Low-priority work on the model, such as a meeting chunk. It receives
/// `None` instead of the model when dictation claimed the engine first.
pub(crate) type Background = Box<dyn FnOnce(Option<&mut Model>) + Send>;
/// A healthy finish decodes at most a couple of seconds of buffered audio.
/// Past this the stream is aborted and the clip is transcribed offline.
const STREAM_FINISH_DEADLINE: Duration = Duration::from_millis(1_500);
/// Audio fed past the clip's trimmed end (a release handled late) that the
/// stream may still keep. The audio owner caps live feeding at the release
/// plus the base tail (`DictationCapture::limit_stream_to`), but audio that
/// arrived before the finish began can still sit past the clip's end. Beyond
/// this, the offline clip is authoritative.
const MAX_OVERFED_SAMPLES: usize = 16_000 / 4;
/// How long a job may run once the engine starts it, before the clip's own
/// share. It covers activating and prewarming the largest model inside the
/// job (macOS loads a new selection there). Time queued behind other work is
/// never counted: the deadline only catches a wedged engine, never a slow one.
const JOB_DEADLINE: Duration = Duration::from_secs(180);
/// Run time allowed per second of audio: two passes (voice-delimited
/// dictation retranscribes without its control phrase) on a CPU-only device
/// up to four times slower than real time.
const JOB_SECONDS_PER_AUDIO_SECOND: u32 = 8;
/// How often a waiter whose job has not started checks whether the job ahead
/// of it timed out, leaving the engine wedged.
const QUEUE_POLL: Duration = Duration::from_millis(250);
/// How often an idle engine looks again at Labs › Free memory when idle.
const IDLE_RECHECK: Duration = Duration::from_secs(30);
/// How long dropping the engine waits for its thread. A native run that cannot
/// be aborted is left to finish on its own.
const SHUTDOWN_DEADLINE: Duration = Duration::from_secs(10);
#[derive(Clone, Copy)]
struct Deadlines {
stream_finish: Duration,
job: Duration,
job_seconds_per_audio_second: u32,
shutdown: Duration,
}
impl Deadlines {
const PRODUCTION: Self = Self {
stream_finish: STREAM_FINISH_DEADLINE,
job: JOB_DEADLINE,
job_seconds_per_audio_second: JOB_SECONDS_PER_AUDIO_SECOND,
shutdown: SHUTDOWN_DEADLINE,
};
fn job_for(&self, samples: usize) -> Duration {
self.job
+ Duration::from_secs_f64(samples as f64 / 16_000.0) * self.job_seconds_per_audio_second
}
}
pub(crate) enum Command {
Begin {
stream: u64,
/// Aborts this stream only.
cancel: CancelToken,
/// Where the stream publishes its text after each feed, when live
/// text is on (Labs).
partials: Option<Partials>,
/// Clip samples of Hex's own sounds at the capture's head (the
/// pre-roll and the start tone): speech it heard there is never a
/// lost opening.
head_ignored: usize,
},
Feed {
stream: u64,
samples: Vec<f32>,
},
/// Raises the clip samples ignored at the stream's head, as Hex's output
/// suppression only reports that it took effect after the stream began.
/// The value only ever increases and is applied before the finalize.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
IgnoreHead {
stream: u64,
head: usize,
},
Cancel {
stream: u64,
},
Finish {
stream: Option<u64>,
clip: Vec<f32>,
offline: Offline,
job: Job,
},
/// An offline run that waits for an open live stream to end instead of
/// interrupting it, such as a capture's word chunk or a `/streams`
/// window. Like a finish it is a dictation request, so background work
/// sent before it yields.
Foreground {
clip: Vec<f32>,
offline: Offline,
job: Job,
},
/// A live stream that gives way to dictation (`/streams`): any dictation
/// request closes it, and while a dictation stream is open it is refused
/// instead of interrupting it.
BeginYielding {
stream: u64,
cancel: CancelToken,
yielding: Yielding,
},
/// Finalizes a yielding stream, or answers [`PREEMPTED`] at once when it
/// is no longer open. It never runs anything offline.
FinishYielding {
stream: u64,
reply: SyncSender<Result<String, String>>,
},
/// Work that needs the model itself, such as loading or switching it.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
Run(Box<dyn FnOnce(&mut Model) + Send>),
/// Drops the model, then loads `selection` in its place, for a GPU with
/// no room for both (#1170). Replies once the load commits or fails.
#[cfg_attr(target_os = "macos", allow(dead_code))]
Reload {
selection: crate::transcription::models::TranscriptionSelection,
reply: SyncSender<std::result::Result<(), String>>,
},
Background {
/// The dictation generation when the work was submitted.
generation: u64,
work: Background,
},
Shutdown,
}
/// Why a yielding stream ended without its text: dictation needed the engine.
pub(crate) const PREEMPTED: &str = "the stream gave way to dictation";
/// A live stream's text so far, as the model reports it after each feed.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Partial {
/// The prefix the model has committed; it only grows within one stream.
pub stable: String,
/// The model's volatile hypothesis after `stable`.
pub tentative: String,
}
/// One stream's latest partial text, shared between the worker that
/// publishes it and the stream's owner. Each stream has its own, so a new
/// capture never reads an older one's text.
#[derive(Clone, Default)]
pub(crate) struct Partials(Arc<Mutex<Published>>);
#[derive(Default)]
struct Published {
/// Bumped by each change, so an owner can tell what it has not seen.
seq: u64,
partial: Option<Partial>,
}
impl Partials {
/// Publishes `partial`; returns whether it changed the text.
pub(crate) fn publish(&self, partial: Partial) -> bool {
let mut published = self.0.lock().unwrap_or_else(|error| error.into_inner());
if published.partial.as_ref() == Some(&partial) {
return false;
}
published.seq += 1;
published.partial = Some(partial);
true
}
fn latest(&self) -> Option<Partial> {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.partial
.clone()
}
/// The latest partial when it is newer than `seen`, which it advances.
fn newer_than(&self, seen: &mut u64) -> Option<Partial> {
let published = self.0.lock().unwrap_or_else(|error| error.into_inner());
if published.seq <= *seen {
return None;
}
*seen = published.seq;
published.partial.clone()
}
}
/// State shared between a yielding stream's owner and the engine worker.
struct YieldingState {
open: AtomicBool,
/// Samples the model has consumed.
consumed: AtomicUsize,
partials: Partials,
}
/// The engine worker's unique handle to a yielding stream. Dropping it always
/// marks the stream closed, so a feed error, cancel, preemption, refused
/// begin, or shutdown can never leave the owner waiting on a dead stream.
pub(crate) struct Yielding(Arc<YieldingState>);
impl Yielding {
fn pair() -> (Self, Arc<YieldingState>) {
let state = Arc::new(YieldingState {
open: AtomicBool::new(true),
consumed: AtomicUsize::default(),
partials: Partials::default(),
});
(Self(state.clone()), state)
}
fn record_consumed(&self, samples: usize, partial: Partial) {
self.0.consumed.fetch_add(samples, Ordering::AcqRel);
self.0.partials.publish(partial);
}
fn close(self) {
drop(self);
}
}
impl Drop for Yielding {
fn drop(&mut self) {
self.0.open.store(false, Ordering::Release);
}
}
/// A live stream that gives way to dictation (`/streams`). Unlike a
/// [`LiveStream`] it is not a dictation request: background work sent before
/// it still runs, and any dictation request closes it. Feed it 16 kHz audio,
/// then [`Self::finish`] it or drop it to cancel.
pub(crate) struct YieldingStream {
id: u64,
cancel: CancelToken,
state: Arc<YieldingState>,
sent: usize,
finished: bool,
commands: Sender<Command>,
}
impl YieldingStream {
/// Whether the stream is still open on the engine. Once dictation closes
/// it, its audio must be transcribed some other way.
pub(crate) fn open(&self) -> bool {
self.state.open.load(Ordering::Acquire)
}
pub(crate) fn feed(&mut self, samples: &[f32]) {
if samples.is_empty() || !self.open() {
return;
}
self.sent += samples.len();
let _ = self.commands.send(Command::Feed {
stream: self.id,
samples: samples.to_vec(),
});
}
/// Samples sent that the model has not consumed yet. Keeping this small
/// keeps a dictation request from queueing behind a pile of feeds.
pub(crate) fn in_flight(&self) -> usize {
self.sent
.saturating_sub(self.state.consumed.load(Ordering::Acquire))
}
/// The model's latest text for the audio fed so far.
pub(crate) fn partial(&self) -> Option<Partial> {
self.state.partials.latest()
}
/// Finalizes the stream within `deadline`. It fails with [`PREEMPTED`]
/// when dictation closed it first, and is aborted when the engine does
/// not reach it in time; either way nothing was lost but this text.
pub(crate) fn finish(mut self, deadline: Duration) -> Result<String, String> {
self.finished = true;
if !self.open() {
return Err(PREEMPTED.into());
}
let (reply, receiver) = mpsc::sync_channel(1);
if self
.commands
.send(Command::FinishYielding {
stream: self.id,
reply,
})
.is_err()
{
return Err("transcription engine stopped".into());
}
match receiver.recv_timeout(deadline) {
Ok(result) => result,
Err(RecvTimeoutError::Timeout) => {
self.cancel.cancel();
Err("the stream missed its finish deadline".into())
}
Err(RecvTimeoutError::Disconnected) => Err("transcription engine stopped".into()),
}
}
}
impl Drop for YieldingStream {
fn drop(&mut self) {
if !self.finished {
let _ = self.commands.send(Command::Cancel { stream: self.id });
}
}
}
/// One finish request as the worker sees it: its own cancellation, so a
/// timeout aborts this job and never a later capture, and its reply.
pub(crate) struct Job {
cancel: CancelToken,
reply: Sender<Reply>,
}
impl Job {
fn start(&self) {
let _ = self.reply.send(Reply::Started);
}
fn finish(self, result: Result<Transcribed, String>) {
let _ = self.reply.send(Reply::Done(result));
}
}
enum Reply {
/// The engine began this job; its deadline starts now.
Started,
Done(Result<Transcribed, String>),
}
#[derive(Debug)]
pub struct Transcribed {
pub text: String,
pub source: Source,
/// Time from the finish request to the final text.
pub finish_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
Stream,
Offline,
/// The stream could not be used; the reason is logged with the result.
Fallback(String),
}
impl Source {
pub fn label(&self) -> &str {
match self {
Self::Stream => "stream",
Self::Offline => "offline",
Self::Fallback(_) => "fallback",
}
}
}
/// The token of the job or stream the worker is running, so dropping the
/// engine aborts it. Work entered after the engine stops starts cancelled.
#[derive(Clone, Default)]
struct Running(Arc<Mutex<RunningState>>);
#[derive(Default)]
struct RunningState {
stopping: bool,
cancel: Option<CancelToken>,
}
impl Running {
fn enter(&self, cancel: &CancelToken) {
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
if state.stopping {
cancel.cancel();
}
state.cancel = Some(cancel.clone());
}
fn stop(&self) {
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
state.stopping = true;
if let Some(cancel) = &state.cancel {
cancel.cancel();
}
}
}
pub struct TranscriptionEngine {
commands: Sender<Command>,
running: Running,
/// Set when a job misses its deadline and cleared when the worker starts
/// another: jobs queued behind a wedged run fail instead of waiting.
stalled: Arc<AtomicBool>,
/// Dictation requests sent so far. Background work submitted before a
/// newer request yields to it.
requests: Arc<AtomicU64>,
/// Whether dictation streams publish their text as they go, asked as
/// each stream begins: Labs › Live text, or a
/// [`crate::dictation::live_text::Demand`].
live_text: fn() -> bool,
held: Held,
/// Whether the worker is running a dictation stream or finish.
dictating: Arc<AtomicBool>,
next_stream: AtomicU64,
deadlines: Deadlines,
thread: Option<JoinHandle<()>>,
}
type Held = Arc<Mutex<HeldState>>;
/// A live stream for one capture. Feed it the capture's 16 kHz audio in order,
/// then either [`TranscriptionEngine::finish`] or drop it to cancel.
pub struct LiveStream {
id: u64,
cancel: CancelToken,
fed: usize,
finished: bool,
commands: Sender<Command>,
/// The stream's text so far, with live text on, and the last version
/// [`Self::take_partial`] returned.
partials: Option<(Partials, u64)>,
}
impl LiveStream {
/// Total samples handed to the stream so far.
pub fn fed(&self) -> usize {
self.fed
}
/// The model's text for the audio fed so far, when it changed since the
/// last call. Always `None` without live text. It is provisional: the
/// finish may replace it entirely, so it is only ever shown, never
/// pasted or kept.
pub fn take_partial(&mut self) -> Option<Partial> {
let (partials, seen) = self.partials.as_mut()?;
partials.newer_than(seen)
}
pub fn feed(&mut self, samples: &[f32]) {
if samples.is_empty() {
return;
}
self.fed += samples.len();
let _ = self.commands.send(Command::Feed {
stream: self.id,
samples: samples.to_vec(),
});
}
/// Raises the clip samples the opening check ignores for this stream. It
/// only ever increases, and the engine applies the latest value before it
/// finalizes; a value sent after the stream ended is ignored. An
/// `IgnoreHead` sent before `finish` is handled before the `Finish` on the
/// same channel, so it is seen; one sent after cannot be.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn raise_ignored_head(&self, head: usize) {
let _ = self.commands.send(Command::IgnoreHead {
stream: self.id,
head,
});
}
}
impl Drop for LiveStream {
fn drop(&mut self) {
if !self.finished {
let _ = self.commands.send(Command::Cancel { stream: self.id });
}
}
}
/// A finish in flight. Waiting enforces the stream deadline from the caller's
/// side, so a stalled native stream cannot hold the paste forever, then bounds
/// the job once the engine starts it, so a wedged run fails instead.
pub struct PendingTranscript {
reply: Receiver<Reply>,
cancel: CancelToken,
stream_cancel: Option<CancelToken>,
stalled: Arc<AtomicBool>,
/// How long the job may run once started: its allowance plus the clip's.
job: Duration,
stream_finish: Duration,
}
impl PendingTranscript {
pub fn wait(self) -> Result<Transcribed, String> {
let mut stream_deadline = self
.stream_cancel
.as_ref()
.map(|_| Instant::now() + self.stream_finish);
let mut job_deadline: Option<Instant> = None;
loop {
let now = Instant::now();
let timeout = [stream_deadline, job_deadline]
.into_iter()
.flatten()
.min()
.map_or(QUEUE_POLL, |deadline| {
deadline.saturating_duration_since(now).min(QUEUE_POLL)
});
match self.reply.recv_timeout(timeout) {
Ok(Reply::Done(result)) => return result,
Ok(Reply::Started) => job_deadline = Some(Instant::now() + self.job),
Err(RecvTimeoutError::Disconnected) => {
return Err("transcription engine stopped".into());
}
Err(RecvTimeoutError::Timeout) => {
let now = Instant::now();
if let (Some(deadline), Some(stream)) = (stream_deadline, &self.stream_cancel)
&& now >= deadline
{
tracing::warn!("live stream missed its finish deadline; aborting it");
stream.cancel();
stream_deadline = None;
}
if job_deadline.is_some_and(|deadline| now >= deadline) {
tracing::error!(
deadline_ms = self.job.as_millis() as u64,
"transcription missed its deadline; failing the job"
);
self.stalled.store(true, Ordering::Release);
self.abandon();
return Err("transcription timed out".into());
}
if job_deadline.is_none() && self.stalled.load(Ordering::Acquire) {
tracing::error!("transcription engine is stuck; failing a queued job");
self.abandon();
return Err("transcription engine is stuck".into());
}
}
}
}
}
/// Aborts this job's run, or skips it if the engine has not reached it.
fn abandon(&self) {
self.cancel.cancel();
if let Some(stream) = &self.stream_cancel {
stream.cancel();
}
}
}
impl TranscriptionEngine {
pub fn start(model: Model) -> Result<Self> {
Self::with_slot(ModelSlot::loaded(model))
}
/// Starts with no model loaded, remembering `selection` to reload on the
/// first command that needs it, as [`Worker::park`] leaves the engine.
/// Labs › Free memory when idle uses this so a launch stays unloaded
/// until the first dictation. Whether it can stream is seeded from the
/// model's definition, not measured on this device: the first capture
/// either streams after the reload or falls back to its whole clip.
pub fn start_parked(
selection: crate::transcription::models::TranscriptionSelection,
) -> Result<Self> {
Self::with_slot(ModelSlot::parked(selection))
}
/// The engine and its worker thread initialized with `slot`.
fn with_slot(slot: ModelSlot) -> Result<Self> {
let (commands, receiver) = mpsc::channel();
let requests = Arc::new(AtomicU64::new(0));
let running = Running::default();
let stalled = Arc::new(AtomicBool::new(false));
let held = Held::new(Mutex::new(slot.snapshot()));
let dictating = Arc::new(AtomicBool::new(false));
// The model the engine adopts speaks for dictation (#1984). A parked
// engine has no model, so it leaves the last word alone.
if let Some(model) = slot.model() {
publish_out_of_memory(model);
}
let worker = Worker {
slot,
idle_since: Instant::now(),
running: running.clone(),
stalled: stalled.clone(),
requests: requests.clone(),
held: held.clone(),
dictating: dictating.clone(),
};
let thread = thread::Builder::new()
.name("transcription-engine".into())
.spawn(move || worker.run(receiver))?;
Ok(Self {
commands,
running,
stalled,
requests,
live_text: || {
crate::labs::live_text()
|| crate::labs::stop_phrase()
|| crate::dictation::live_text::demanded()
},
held,
dictating,
next_stream: AtomicU64::new(0),
deadlines: Deadlines::PRODUCTION,
thread: Some(thread),
})
}
/// An engine without a worker whose model always streams; tests read the
/// commands it would have handled.
#[cfg(test)]
pub(crate) fn for_test() -> (Self, Receiver<Command>) {
let (commands, receiver) = mpsc::channel();
let engine = Self {
commands,
running: Running::default(),
stalled: Arc::default(),
requests: Arc::default(),
live_text: || false,
held: Held::new(Mutex::new(HeldState::Loaded {
selection: None,
backend: None,
streams: true,
})),
dictating: Arc::default(),
next_stream: AtomicU64::new(0),
deadlines: Deadlines::PRODUCTION,
thread: None,
};
(engine, receiver)
}
/// Like [`Self::for_test`] for a model that cannot stream.
#[cfg(test)]
pub(crate) fn for_test_without_streaming() -> (Self, Receiver<Command>) {
let (engine, receiver) = Self::for_test();
*engine.held.lock().unwrap_or_else(|e| e.into_inner()) = HeldState::Empty;
(engine, receiver)
}
#[cfg(test)]
fn with_deadlines(mut self, deadlines: Deadlines) -> Self {
self.deadlines = deadlines;
self
}
/// Turns live text on, as Labs does.
#[cfg(test)]
pub(crate) fn with_live_text(mut self) -> Self {
self.live_text = || true;
self
}
/// Opens a live stream when the loaded model can stream on this device.
#[cfg(test)]
pub fn begin(&self) -> Option<LiveStream> {
self.begin_ignoring_head(0)
}
/// Opens a live stream whose opening-coverage check ignores `head_ignored`
/// clip samples: Hex's own sounds at the capture's head, never a lost
/// opening.
pub fn begin_ignoring_head(&self, head_ignored: usize) -> Option<LiveStream> {
if !self.streams() {
return None;
}
let id = self.next_stream.fetch_add(1, Ordering::Relaxed) + 1;
let cancel = CancelToken::new();
let partials = (self.live_text)().then(Partials::default);
self.requests.fetch_add(1, Ordering::AcqRel);
self.commands
.send(Command::Begin {
stream: id,
cancel: cancel.clone(),
partials: partials.clone(),
head_ignored,
})
.ok()?;
Some(LiveStream {
id,
cancel,
fed: 0,
finished: false,
commands: self.commands.clone(),
partials: partials.map(|partials| (partials, 0)),
})
}
/// Opens a stream that gives way to dictation, when the loaded model can
/// stream on this device. See [`YieldingStream`].
pub(crate) fn begin_yielding(&self) -> Option<YieldingStream> {
if !self.streams() {
return None;
}
let id = self.next_stream.fetch_add(1, Ordering::Relaxed) + 1;
let cancel = CancelToken::new();
let (yielding, state) = Yielding::pair();
self.commands
.send(Command::BeginYielding {
stream: id,
cancel: cancel.clone(),
yielding,
})
.ok()?;
Some(YieldingStream {
id,
cancel,
state,
sent: 0,
finished: false,
commands: self.commands.clone(),
})
}
/// Whether the loaded model (or parked model) can stream on its device.
pub(crate) fn streams(&self) -> bool {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.streams()
}
/// Finishes a capture with its complete 16 kHz clip. Without a stream,
/// or when the stream is unusable, the clip is transcribed offline.
#[cfg(not(target_os = "macos"))]
pub fn finish(&self, stream: Option<LiveStream>, clip: Vec<f32>) -> Result<PendingTranscript> {
self.finish_with(
stream,
clip,
Box::new(|model, clip| {
// Labs › Skip long pauses, asked as the run starts, then
// padding that follows the cut rather than being trimmed by
// a trailing pause (#1629).
let clip =
padded_whole_clip(clip, crate::labs::skip_pauses(), Some(model.model_id()));
model
.transcribe(&clip)
.map_err(|error| format!("{error:#}"))
}),
)
}
/// Like `finish`, with the caller's offline transcription of the clip.
pub fn finish_with(
&self,
stream: Option<LiveStream>,
clip: Vec<f32>,
offline: Offline,
) -> Result<PendingTranscript> {
let (stream, stream_cancel) = match stream {
Some(mut stream) => {
stream.finished = true;
(Some(stream.id), Some(stream.cancel.clone()))
}
None => (None, None),
};
self.request(clip.len(), stream_cancel, |job| Command::Finish {
stream,
clip,
offline,
job,
})
}
/// Transcribes `clip` offline after every command already sent, without
/// ever interrupting a live stream: one open when it arrives finishes
/// first. Background work sent before it yields, as to a finish.
pub fn foreground(&self, clip: Vec<f32>, offline: Offline) -> Result<PendingTranscript> {
self.request(clip.len(), None, |job| Command::Foreground {
clip,
offline,
job,
})
}
fn request(
&self,
samples: usize,
stream_cancel: Option<CancelToken>,
command: impl FnOnce(Job) -> Command,
) -> Result<PendingTranscript> {
let (reply, receiver) = mpsc::channel();
let cancel = CancelToken::new();
let job = self.deadlines.job_for(samples);
self.requests.fetch_add(1, Ordering::AcqRel);
self.commands
.send(command(Job {
cancel: cancel.clone(),
reply,
}))
.map_err(|_| eyre!("transcription engine stopped"))?;
Ok(PendingTranscript {
reply: receiver,
cancel,
stream_cancel,
stalled: self.stalled.clone(),
job,
stream_finish: self.deadlines.stream_finish,
})
}
/// Runs `work` with the model, after every command already sent. A live
/// stream is closed first; its finish then takes the offline path.
#[cfg(target_os = "macos")]
pub fn run(&self, work: impl FnOnce(&mut Model) + Send + 'static) -> Result<()> {
self.commands
.send(Command::Run(Box::new(work)))
.map_err(|_| eyre!("transcription engine stopped"))
}
/// Runs `work` with the model unless a dictation request was sent first or
/// a live stream is open, and returns `None` when one was. A request sent
/// while `work` runs waits for it: transcribe.cpp cannot abort a Metal run.
pub fn background<R: Send + 'static>(
&self,
work: impl FnOnce(&mut Model) -> R + Send + 'static,
) -> Result<Option<R>> {
let (reply, receiver) = mpsc::channel();
let generation = self.requests.load(Ordering::Acquire);
self.commands
.send(Command::Background {
generation,
work: Box::new(move |model| {
let _ = reply.send(model.map(work));
}),
})
.map_err(|_| eyre!("transcription engine stopped"))?;
receiver
.recv()
.map_err(|_| eyre!("transcription engine stopped"))
}
/// Replaces the model with `selection` after every command already sent:
/// the old one is dropped first, so its memory is free for the new one.
/// Commands sent meanwhile wait for the load, and the returned receiver
/// reports whether the reload committed or failed.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn reload(
&self,
selection: crate::transcription::models::TranscriptionSelection,
) -> Result<Receiver<std::result::Result<(), String>>> {
let (reply, receiver) = mpsc::sync_channel(1);
self.commands
.send(Command::Reload { selection, reply })
.map_err(|_| eyre!("transcription engine stopped"))?;
Ok(receiver)
}
/// Drops the engine on its own thread, so replacing the model from the
/// hotkey loop never waits on a run still in flight.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn retire(self) {
let spawned = thread::Builder::new()
.name("transcription-engine-retire".into())
.spawn(move || drop(self));
if let Err(error) = spawned {
tracing::warn!(%error, "could not retire the old transcription engine in the background");
}
}
/// Makes this the engine that meeting transcription and the local API share.
pub fn share(self: &Arc<Self>) {
*SHARED.lock().unwrap_or_else(|error| error.into_inner()) = Arc::downgrade(self);
}
/// The running app's engine, when one is shared.
pub fn shared() -> Option<Arc<Self>> {
SHARED
.lock()
.unwrap_or_else(|error| error.into_inner())
.upgrade()
}
/// Whether the model holds the GGUF `selection` as of its last finished
/// command (including a parked model, never a failed reload). Readable
/// while dictation runs, unlike the model itself.
pub(crate) fn holds(
&self,
selection: &crate::transcription::models::TranscriptionSelection,
) -> bool {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.holds(selection)
}
}
impl TranscriptionEngine {
/// The GGUF selection the model held after its last finished command.
pub(crate) fn held_selection(
&self,
) -> Option<crate::transcription::models::TranscriptionSelection> {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.selection()
}
/// Where the model held after its last finished command runs, for
/// `hex status`: `None` before a load and once it is unloaded.
pub(crate) fn held_backend(&self) -> Option<crate::transcription::SpeechBackend> {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.backend()
}
/// Why a live stream cannot open for a capture, when it can't: the
/// model's own definition doesn't stream, or it streams in principle but
/// not on the device it loaded on (a CPU, or a GPU whose stream probe
/// failed). `None` when a stream can open.
pub(crate) fn stream_refusal(&self) -> Option<&'static str> {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.stream_refusal()
}
}
/// Whether a dictation or a meeting records, so an idle model stays loaded:
/// both hold idle-sleep prevention while they record, and a macOS capture
/// counts from its press.
fn recording() -> bool {
crate::audio::idle_sleep::held() || dictation_busy()
}
/// The model `selection` loads into, prewarmed, as the engine held it.
#[cfg(target_os = "macos")]
fn reload(selection: &crate::transcription::models::TranscriptionSelection) -> Result<Model> {
let mut model = Model::default();
model.activate(selection)?.prewarm()?;
Ok(model)
}
#[cfg(not(target_os = "macos"))]
fn reload(selection: &crate::transcription::models::TranscriptionSelection) -> Result<Model> {
let model = Model::load(selection)?;
publish_out_of_memory(&model);
Ok(model)
}
/// Publishes why the engine's model runs on the CPU (#1984). Only the model
/// the engine holds speaks for dictation: the local API's own model, model
/// preparation, and a superseded model swap load beside it and never get
/// here.
fn publish_out_of_memory(_model: &Model) {
#[cfg(not(target_os = "macos"))]
crate::transcription::gpu_health::set_out_of_memory(_model.out_of_memory());
}
static SHARED: std::sync::Mutex<std::sync::Weak<TranscriptionEngine>> =
std::sync::Mutex::new(std::sync::Weak::new());
/// Whether dictation is capturing or transcribing, so host audio and
/// background work give way to it. macOS counts a capture from its press;
/// Linux and Windows count the shared engine's dictation streams and finishes.
pub(crate) fn dictation_busy() -> bool {
#[cfg(target_os = "macos")]
let capturing = crate::parakeet::dictation_busy();
#[cfg(not(target_os = "macos"))]
let capturing = false;
capturing
|| TranscriptionEngine::shared()
.is_some_and(|engine| engine.dictating.load(Ordering::Acquire))
}
/// A model the engine can hold: the GGUF transcriber on macOS, the one local
/// GGUF model on Linux and Windows.
#[cfg(target_os = "macos")]
pub(crate) type HeldModel = crate::transcription::Transcriber;
#[cfg(not(target_os = "macos"))]
pub(crate) type HeldModel = crate::transcription::local_transcriber::LocalTranscriber;
/// The engine's model when it is the GGUF `selection`, never loading or
/// switching one.
pub(crate) fn held<'a>(
model: &'a mut Model,
selection: &crate::transcription::models::TranscriptionSelection,
) -> Option<&'a mut HeldModel> {
#[cfg(target_os = "macos")]
let model = model
.active()
.filter(|model| matches!(model, crate::transcription::Transcriber::Gguf(_)))?;
model.matches_selection(selection).then_some(model)
}
/// Transcribes a complete 16 kHz clip with a held model, padded as a
/// dictation's clip is.
pub(crate) fn transcribe_clip(model: &mut HeldModel, samples: Vec<f32>) -> Result<String> {
#[cfg(target_os = "macos")]
return model.transcribe(samples);
#[cfg(not(target_os = "macos"))]
model.transcribe_clip(samples)
}
/// Transcribes a complete 16 kHz clip with a held model and its own native
/// timings, never estimated ones.
pub(crate) fn transcribe_clip_timed(
model: &mut HeldModel,
samples: Vec<f32>,
) -> Result<crate::transcription::transcript::Transcript, String> {
model
.transcribe_timed(samples)
.map_err(|error| format!("{error:#}"))
}
/// The finest native timings a held model gives. Dictation never asks; the
/// local API answers `422` for a level the model cannot produce.
pub(crate) fn timestamp_level(
model: &HeldModel,
) -> crate::transcription::transcript::TimestampLevel {
model.timestamps()
}
/// A whole clip as a non-macOS dictation run transcribes it: long pauses cut
/// first, then the minimum duration and the model's trailing silence, so a
/// trailing pause cannot trim Unified English's closing context (#1629).
#[cfg(not(target_os = "macos"))]
fn padded_whole_clip(
clip: Vec<f32>,
skip_pauses: bool,
model: Option<crate::transcription::models::TranscriptionModelId>,
) -> Vec<f32> {
let mut clip = whole_clip(clip, skip_pauses);
crate::transcription::pad_gguf_samples(&mut clip, model);
clip
}
impl Drop for TranscriptionEngine {
fn drop(&mut self) {
self.running.stop();
// A live stream's sender may outlive the engine; stop explicitly.
let _ = self.commands.send(Command::Shutdown);
let Some(thread) = self.thread.take() else {
return;
};
let deadline = Instant::now() + self.deadlines.shutdown;
while !thread.is_finished() && Instant::now() < deadline {
thread::sleep(Duration::from_millis(5));
}
if thread.is_finished() {
let _ = thread.join();
} else {
tracing::error!("transcription engine did not stop in time; leaving it running");
}
}
}
struct Worker {
/// Explicit lifecycle of the owned model: empty, loaded, parked, or
/// reload-failed.
slot: ModelSlot,
/// When the last command ended.
idle_since: Instant,
running: Running,
stalled: Arc<AtomicBool>,
requests: Arc<AtomicU64>,
held: Held,
dictating: Arc<AtomicBool>,
}
/// How a live stream ended inside the worker.
enum StreamEnd {
/// A finish for this stream: the final text, or why the stream is unusable.
Finished {
result: Result<String, String>,
clip: Vec<f32>,
offline: Offline,
job: Job,
started: Instant,
},
Cancelled,
/// Another command arrived first; it is handled after the stream closes.
Interrupted(Command),
Disconnected,
}
impl Worker {
fn run(mut self, commands: Receiver<Command>) {
// Commands received while a stream was open, handled before new ones.
let mut next = VecDeque::new();
loop {
let Some(command) = next.pop_front().or_else(|| self.wait(&commands)) else {
return;
};
match command {
Command::Begin {
stream,
cancel,
partials,
head_ignored,
} => {
self.dictating.store(true, Ordering::Release);
crate::dictation::vocabulary::for_dictation(|| {
self.stream(
stream,
&cancel,
partials.as_ref(),
head_ignored,
&commands,
&mut next,
);
});
self.dictating.store(false, Ordering::Release);
}
Command::BeginYielding {
stream,
cancel,
yielding,
} => {
// Anything already waiting comes first. Dropping `yielding`
// on any exit closes the stream's open flag.
if next.is_empty() {
self.yielding_stream(stream, &cancel, yielding, &commands, &mut next);
}
}
Command::FinishYielding { reply, .. } => {
let _ = reply.send(Err(PREEMPTED.into()));
}
// The stream already ended, so its finalize cannot see a
// later head. It is dropped.
Command::IgnoreHead { .. } => {}
Command::Finish {
stream,
clip,
offline,
job,
} => {
let source = match stream {
// The stream was already closed: its begin failed or
// another command interrupted it.
Some(_) => Source::Fallback("the live stream was not available".into()),
None => Source::Offline,
};
self.dictating.store(true, Ordering::Release);
crate::dictation::vocabulary::for_dictation(|| {
self.run_offline(clip, offline, source, job);
});
self.dictating.store(false, Ordering::Release);
}
Command::Foreground { clip, offline, job } => {
self.run_offline(clip, offline, Source::Offline, job);
}
#[cfg(target_os = "macos")]
Command::Run(work) => {
if let Some(model) = self.slot.model_mut() {
work(model);
} else {
// Switching from a parked or failed-reload slot runs
// on a fresh warm transcriber so a broken parked model
// cannot block a switch; if activation fails, the
// previous slot stays intact.
let mut model = Model::default();
work(&mut model);
if model.active().is_some() {
self.slot = ModelSlot::loaded(model);
}
}
}
#[cfg(not(target_os = "macos"))]
Command::Run(work) => {
if let Some(model) = self.model() {
work(model);
}
}
Command::Reload { selection, reply } => {
tracing::info!(model = ?selection.model, "replacing the speech model in place");
// Drop the running model first so its GPU memory is free
// before loading the replacement.
self.slot = ModelSlot::parked(selection);
let result = match self.model() {
Some(_) => Ok(()),
None => Err(self
.slot
.reload_error()
.unwrap_or("the speech model could not be reloaded")
.to_string()),
};
let _ = reply.send(result);
}
Command::Background { generation, work } => {
let current = self.requests.load(Ordering::Acquire) == generation;
work(if current { self.model() } else { None });
}
Command::Shutdown => return,
// Stale input for a stream that already ended.
Command::Feed { .. } | Command::Cancel { .. } => {}
}
// Any command may load or switch the model. A parked engine has
// no model, so it leaves the last word alone.
if let Some(model) = self.slot.model() {
publish_out_of_memory(model);
}
// Only when the engine is quiet: a queued Begin, deferred work,
// or a recording must never wait behind the probe.
if next.is_empty() && !recording() {
self.refresh_stream();
}
self.slot.sync_streams();
self.publish_slot();
self.idle_since = Instant::now();
}
}
/// The next command. With Labs › Free memory when idle on, it unloads
/// the model once nothing has used it for the chosen time and nothing
/// records (a dictation or a meeting); between commands no request runs.
fn wait(&mut self, commands: &Receiver<Command>) -> Option<Command> {
loop {
let Some(after) = crate::labs::unload_idle() else {
// Settings may turn it on meanwhile.
match commands.recv_timeout(IDLE_RECHECK) {
Ok(command) => return Some(command),
Err(RecvTimeoutError::Timeout) => {
// An idle tick, so a toggle change while nothing
// records reaches the model before a capture opens.
if !recording() {
self.refresh_stream();
}
continue;
}
Err(RecvTimeoutError::Disconnected) => return None,
}
};
let idle = self.idle_since.elapsed();
let wait = after
.saturating_sub(idle)
.clamp(Duration::from_millis(1), IDLE_RECHECK);
match commands.recv_timeout(wait) {
Ok(command) => return Some(command),
Err(RecvTimeoutError::Disconnected) => return None,
Err(RecvTimeoutError::Timeout) => {
if !recording() {
self.refresh_stream();
if self.idle_since.elapsed() >= after {
self.park();
}
}
}
}
}
}
/// Unloads a loaded GGUF model, freeing its memory, and keeps its
/// selection to reload. Apple Speech stays: it holds no model of Hex's.
fn park(&mut self) {
let Some(selection) = self.slot.park() else {
return;
};
tracing::info!(model = ?selection.model, "unloaded the idle speech model");
// The device goes with the model: `hex status` must not keep naming it.
self.publish_slot();
}
/// Adopts a changed Labs › Faster live text or env geometry while
/// nothing records. A loaded model re-probes; an unloaded one takes the
/// change when it next loads, and one the gated probe never cleared
/// stays off.
fn refresh_stream(&mut self) {
if let Some(model) = self.slot.model_mut() {
model.refresh_stream();
}
}
/// The model, reloading an unloaded or previously failed one first. Audio
/// sent meanwhile waits in the queue, so nothing recorded is lost.
fn model(&mut self) -> Option<&mut Model> {
if let Some(selection) = self.slot.reload_target() {
let started = Instant::now();
match reload(&selection) {
Ok(model) => {
tracing::info!(
model = ?selection.model,
load_ms = started.elapsed().as_millis(),
"reloaded the speech model"
);
self.slot = ModelSlot::loaded(model);
}
Err(error) => {
tracing::warn!(
error = format!("{error:#}"),
"could not reload the speech model"
);
self.slot = ModelSlot::ReloadFailed {
selection,
error: error.to_string(),
};
}
}
self.publish_slot();
}
self.slot.model_mut()
}
/// Publishes the current model slot's selection, device, and streaming
/// capability atomically.
fn publish_slot(&self) {
*self.held.lock().unwrap_or_else(|error| error.into_inner()) = self.slot.snapshot();
}
fn run_offline(&mut self, clip: Vec<f32>, offline: Offline, source: Source, job: Job) {
if job.cancel.is_cancelled() {
// Its waiter already gave up on it.
job.finish(Err("transcription was abandoned".into()));
return;
}
let started = Instant::now();
self.start(&job);
self.offline(clip, offline, source, started, job);
}
/// Starts a job's clock. The engine is evidently moving again.
fn start(&self, job: &Job) {
self.stalled.store(false, Ordering::Release);
job.start();
}
/// Drives one live stream until it finishes, is cancelled, or another
/// command interrupts it. Commands still to be handled, in order, are
/// pushed onto `next`.
fn stream(
&mut self,
id: u64,
cancel: &CancelToken,
partials: Option<&Partials>,
head_ignored: usize,
commands: &Receiver<Command>,
next: &mut VecDeque<Command>,
) {
let options = self
.model()
.and_then(|model| model.stream_options().cloned());
let Some(options) = options else {
let loaded = self.slot.model().is_some();
let model_streams = self
.slot
.model()
.and_then(|model| model.gguf_selection())
// An imported model's catalog entry says it can't stream, but
// its GGUF is only checked when it loads.
.filter(|selection| {
!matches!(
selection.model,
crate::transcription::models::TranscriptionModelId::Custom(_)
)
})
.map(|selection| crate::transcription::models::definition(selection.model).streams);
match loaded {
true => tracing::info!(
stream = id,
live_text = partials.is_some(),
model_streams,
"a live stream was requested but this model can't stream on its device; transcribing the whole clip"
),
false => tracing::info!(
stream = id,
live_text = partials.is_some(),
"a live stream was requested but no speech model is loaded; transcribing the whole clip"
),
}
return;
};
self.running.enter(cancel);
let begun = Instant::now();
let mut stats = FeedStats::default();
let stalled = &self.stalled;
let Some(model) = self.slot.model_mut() else {
return;
};
let trailing_silence = stream_trailing_silence(model);
let closing_mark = stream_requires_closing_mark(model);
let opening_slack = stream_opening_slack(model);
let ended = model.with_stream(&options, cancel, |stream| {
let mut capped = PauseCap::new(stream, trailing_silence)
.ignoring_head(head_ignored)
.opening_slack(opening_slack);
let ended = drive_stream(
id,
&mut capped,
commands,
stalled,
partials,
next,
&mut stats,
);
stats.pauses_dropped_ms = capped.dropped / 16;
ended
});
let FeedStats {
feed_ms,
feeds,
partials: changes,
pauses_dropped_ms,
} = stats;
match ended {
Ok(StreamEnd::Finished {
result,
clip,
offline,
job,
started,
}) => {
tracing::info!(
audio_ms = clip.len() / 16,
stream_ms = begun.elapsed().as_millis(),
feeds,
feed_ms,
partials = changes,
pauses_dropped_ms,
finish_ms = started.elapsed().as_millis(),
"finished live stream"
);
let result = result.and_then(|text| check_closing_mark(text, closing_mark));
match result {
Ok(text) => job.finish(Ok(Transcribed {
text,
source: Source::Stream,
finish_ms: started.elapsed().as_millis() as u64,
})),
Err(_) if job.cancel.is_cancelled() => {
job.finish(Err("transcription was abandoned".into()));
}
Err(reason) => {
tracing::warn!(%reason, "live stream unusable; transcribing the full clip");
self.offline(clip, offline, Source::Fallback(reason), started, job);
}
}
}
Ok(StreamEnd::Cancelled) | Ok(StreamEnd::Disconnected) => {}
Ok(StreamEnd::Interrupted(command)) => {
// The capture goes on without its stream (a model switch):
// its text stops, so the plate hides.
if let Some(partials) = partials {
partials.publish(Partial::default());
}
next.push_back(command);
}
Err(error) => tracing::warn!(%error, "could not begin a live stream"),
}
}
/// Drives one yielding stream until it finishes, is cancelled, or any
/// command that is not its own, background, or foreground work arrives;
/// that command is handled next.
fn yielding_stream(
&mut self,
id: u64,
cancel: &CancelToken,
yielding: Yielding,
commands: &Receiver<Command>,
next: &mut VecDeque<Command>,
) {
if cancel.is_cancelled() {
return;
}
let options = self
.model()
.and_then(|model| model.stream_options().cloned());
let Some(options) = options else {
return;
};
self.running.enter(cancel);
let Some(model) = self.slot.model_mut() else {
return;
};
let ended = model.with_stream(&options, cancel, |stream| {
drive_yielding(id, stream, commands, yielding, next)
});
match ended {
Ok(Some(command)) => next.push_back(command),
Ok(None) => {}
Err(error) => tracing::warn!(%error, "could not begin a yielding stream"),
}
}
fn offline(
&mut self,
clip: Vec<f32>,
offline: Offline,
source: Source,
started: Instant,
job: Job,
) {
self.running.enter(&job.cancel);
let Some(model) = self.model() else {
let reason = match self.slot.reload_error() {
Some(error) => format!("the speech model could not be reloaded: {error}"),
None => "the speech model could not be reloaded".into(),
};
job.finish(Err(reason));
return;
};
let result = crate::transcription::gguf_session::with_job_cancel(&job.cancel, || {
offline(model, clip)
})
.map(|text| Transcribed {
text: text.trim().to_string(),
source,
finish_ms: started.elapsed().as_millis() as u64,
});
// An offline run may switch the model (macOS activates a selection).
self.slot.sync_streams();
self.publish_slot();
job.finish(result);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_labels_distinguish_fallbacks() {
assert_eq!(Source::Stream.label(), "stream");
assert_eq!(Source::Offline.label(), "offline");
assert_eq!(Source::Fallback("x".into()).label(), "fallback");
}
#[test]
fn streams_send_their_audio_in_order_and_cancel_when_dropped() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin().expect("the test engine streams");
stream.feed(&[0.1; 3]);
stream.feed(&[]);
stream.feed(&[0.2; 2]);
assert_eq!(stream.fed(), 5);
drop(stream);
let finished = engine.begin().expect("the test engine streams");
let pending = engine
.finish_with(
Some(finished),
vec![0.0; 7],
Box::new(|_, _| Ok(String::new())),
)
.unwrap();
assert!(pending.stream_cancel.is_some());
let received = commands.try_iter().collect::<Vec<_>>();
assert!(matches!(
received.as_slice(),
[
Command::Begin { stream: 1, .. },
Command::Feed { stream: 1, samples: first },
Command::Feed { stream: 1, samples: second },
Command::Cancel { stream: 1 },
Command::Begin { stream: 2, .. },
Command::Finish { stream: Some(2), clip, .. },
] if first.len() == 3 && second.len() == 2 && clip.len() == 7
));
}
#[derive(Default)]
struct FakeStream {
fed: Vec<f32>,
/// Fail every feed once this many samples are in, as a native
/// stream error would.
fail_after: Option<usize>,
/// Where its finalized text starts, in milliseconds.
text_start_ms: Option<u64>,
/// Where its finalized text ends, in milliseconds.
text_end_ms: Option<u64>,
/// Language tags its raw decode carries.
tags: Vec<String>,
}
impl StreamFeed for FakeStream {
fn feed(&mut self, samples: &[f32]) -> Result<(), String> {
if self.fail_after.is_some_and(|after| self.fed.len() >= after) {
return Err("native feed failed".into());
}
self.fed.extend_from_slice(samples);
Ok(())
}
fn finalize(&mut self) -> Result<String, String> {
Ok(format!("streamed {}", self.fed.len()))
}
fn partial(&self) -> Partial {
Partial {
stable: format!("heard {}", self.fed.len()),
tentative: String::new(),
}
}
fn text_start_ms(&self) -> Option<u64> {
self.text_start_ms
}
fn text_end_ms(&self) -> Option<u64> {
self.text_end_ms
}
fn language_tags(&self) -> Vec<String> {
self.tags.clone()
}
}
#[test]
fn foreground_work_waits_for_an_open_stream_instead_of_interrupting_it() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin().unwrap();
assert!(matches!(
commands.try_recv().unwrap(),
Command::Begin { stream: 1, .. }
));
stream.feed(&[0.1; 4]);
let chunk = engine
.foreground(vec![0.0; 9], Box::new(|_, _| Ok("chunk".into())))
.unwrap();
stream.feed(&[0.2; 4]);
let dictation = engine
.finish_with(
Some(stream),
vec![0.0; 8],
Box::new(|_, _| panic!("the dictation must not be retranscribed offline")),
)
.unwrap();
let mut fake = FakeStream::default();
let mut deferred = VecDeque::new();
let ended = drive_stream(
1,
&mut fake,
&commands,
&AtomicBool::new(false),
None,
&mut deferred,
&mut FeedStats::default(),
);
let StreamEnd::Finished { result, job, .. } = ended else {
panic!("the stream did not finish");
};
// The stream got all its audio and finished as a stream.
assert_eq!(result, Ok("streamed 8".to_string()));
assert_eq!(fake.fed.len(), 8);
job.finish(Ok(Transcribed {
text: "streamed 8".into(),
source: Source::Stream,
finish_ms: 0,
}));
assert_eq!(dictation.wait().unwrap().source, Source::Stream);
// The chunk waits to run after the stream.
assert!(matches!(
deferred.as_slices().0,
[Command::Foreground { clip, .. }] if clip.len() == 9
));
drop(deferred);
assert!(chunk.wait().is_err());
}
fn tone(samples: usize) -> Vec<f32> {
(0..samples)
.map(|i| 0.3 * (i as f32 * 0.05).sin())
.collect()
}
/// A clip with `(start_ms, length_ms)` tone bursts in order, then the
/// 200 ms tail after a stop.
fn sparse_speech(bursts: &[(usize, usize)]) -> Vec<f32> {
let mut clip = Vec::new();
for &(start_ms, length_ms) in bursts {
clip.resize(start_ms * 16, 0.0);
clip.extend(tone(length_ms * 16));
}
clip.extend(vec![0.0; 3_200]);
clip
}
#[test]
fn a_dictation_stream_hears_only_the_ends_of_long_pauses() {
// Quiet first, as the pre-roll is, so the noise floor starts low.
let mut clip = vec![0.0; 8_000];
clip.extend(tone(16_000));
clip.extend(vec![0.0; 16_000]);
clip.extend(tone(16_000));
clip.extend(vec![0.0; 160_000]);
clip.extend(tone(16_000));
clip.extend(vec![0.0; 80_000]);
let mut fake = FakeStream::default();
let mut capped = PauseCap::new(&mut fake, 0);
for chunk in clip.chunks(1_234) {
capped.feed(chunk).unwrap();
}
capped.finalize().unwrap();
let dropped = capped.dropped;
// A 1 s pause passes whole; the 10 s one keeps 2.5 s and 0.3 s, and
// the trailing 5 s one only its head.
let long = 160_000 - PAUSE_HEAD_SAMPLES - PAUSE_TAIL_SAMPLES;
let trailing = 80_000 - PAUSE_HEAD_SAMPLES;
assert_eq!(dropped, long + trailing);
assert_eq!(fake.fed.len(), clip.len() - dropped);
assert_eq!(fake.fed[..56_000], clip[..56_000]);
let resumed = 56_000 + PAUSE_HEAD_SAMPLES + PAUSE_TAIL_SAMPLES;
assert_eq!(fake.fed[resumed..resumed + 16_000], clip[216_000..232_000]);
}
#[test]
fn quiet_speech_over_steady_noise_is_never_cut_as_a_pause() {
// #458: -28 dBFS syllables over -35 dBFS noise, too close to the
// floor for the meeting detector's 12 dB speech margin.
assert_quiet_speech_is_kept(-28.0, -35.0, 0.0);
// #841: a quiet built-in microphone, whose speech sits under
// -55 dBFS throughout.
assert_quiet_speech_is_kept(-62.0, -72.0, 0.0);
// #841: a built-in digital microphone whose DC offset (-26 dBFS) is
// far louder than its speech; only the speech moves the level.
assert_quiet_speech_is_kept(-50.0, -58.0, 0.05);
}
#[test]
fn a_stream_that_heard_only_quiet_audio_falls_back_to_the_whole_clip() {
use crate::transcription::pause_segmenter::tests::noise;
// #841: the cap took a whole dictation for one pause and the stream
// kept only its first 2.5 s; that stream must not be used.
let mut seed = 3;
let clip = noise(6_000, -80.0, &mut seed);
let mut fake = FakeStream::default();
let mut capped = PauseCap::new(&mut fake, 0);
let result = finish_stream(&mut capped, &clip, 0);
assert!(capped.dropped > 0);
assert!(result.is_err(), "{result:?}");
}
/// Quiet pre-roll, 2 s of speech, a 1 s pause, `phrase` samples of
/// speech, then the 200 ms tail after the stop.
fn speech_pause_phrase(phrase: usize) -> Vec<f32> {
let mut clip = vec![0.0; 8_000];
clip.extend(tone(32_000));
clip.extend(vec![0.0; 16_000]);
clip.extend(tone(phrase));
clip.extend(vec![0.0; 3_200]);
clip
}
fn finish_with_text_end(clip: &[f32], text_end_ms: u64) -> Result<String, String> {
finish_with_text_bounds(clip, None, text_end_ms)
}
fn finish_with_text_bounds(
clip: &[f32],
text_start_ms: Option<u64>,
text_end_ms: u64,
) -> Result<String, String> {
finish_with_text_bounds_ignoring_head(clip, 0, text_start_ms, text_end_ms)
}
/// As above, with `head_ignored` clip samples of Hex's own sounds at the
/// capture's head, as the audio owner passes for a real capture.
fn finish_with_text_bounds_ignoring_head(
clip: &[f32],
head_ignored: usize,
text_start_ms: Option<u64>,
text_end_ms: u64,
) -> Result<String, String> {
finish_with_opening_slack(
clip,
head_ignored,
text_start_ms,
text_end_ms,
UNTRANSCRIBED_SLACK_SAMPLES,
)
}
/// As above, with `slack` samples of speech the stream may leave before
/// its text starts, for a model whose first-word time lags its audio.
fn finish_with_opening_slack(
clip: &[f32],
head_ignored: usize,
text_start_ms: Option<u64>,
text_end_ms: u64,
slack: usize,
) -> Result<String, String> {
let mut fake = FakeStream {
text_start_ms,
text_end_ms: Some(text_end_ms),
..FakeStream::default()
};
let mut capped = PauseCap::new(&mut fake, 0)
.ignoring_head(head_ignored)
.opening_slack(slack);
for chunk in clip.chunks(1_600) {
capped.feed(chunk).unwrap();
}
let result = finish_stream(&mut capped, clip, clip.len());
assert_eq!(fake.fed, clip);
result
}
fn finish_with_tags(clip: &[f32], tags: Vec<String>) -> Result<String, String> {
let mut fake = FakeStream {
text_start_ms: Some(500),
text_end_ms: Some(4_200),
tags,
..FakeStream::default()
};
let mut capped = PauseCap::new(&mut fake, 0);
for chunk in clip.chunks(1_600) {
capped.feed(chunk).unwrap();
}
let result = finish_stream(&mut capped, clip, clip.len());
assert_eq!(fake.fed, clip);
result
}
#[test]
fn a_stream_that_dropped_a_phrase_after_a_pause_falls_back_to_the_whole_clip() {
// #1101: speech, a 1 s pause, a short last phrase, then stop. The
// stream heard it all, but its text ended with the first speech.
let clip = speech_pause_phrase(12_800);
let result = finish_with_text_end(&clip, 2_500);
assert!(
result
.as_ref()
.is_err_and(|reason| reason.contains("speech follows")),
"{result:?}"
);
// Text that reaches the phrase is the stream's to keep.
assert_eq!(
finish_with_text_end(&clip, 4_200),
Ok(format!("streamed {}", clip.len()))
);
}
#[test]
fn a_closing_full_stop_at_the_clips_end_does_not_cover_a_dropped_phrase() {
// Nemotron 3.5 ASR puts its final full stop on the clip's last frame
// (apollo, FLEURS: the last word ended at 8.8 s, the stop at 10.16 s).
let token = |text: &str, t1_ms| transcribe_cpp::Token {
text: text.into(),
t1_ms,
..Default::default()
};
let tokens = [
token(" channels", 2_480),
token(",", 2_500),
token(".", 4_400),
token(" ", 4_400),
];
assert_eq!(spoken_text_end_ms(&tokens), Some(2_480));
assert_eq!(spoken_text_end_ms(&[token(".", 4_400)]), None);
}
#[test]
fn a_short_sound_after_the_text_does_not_discard_the_stream() {
// A key click or the stop tone in the tail is not a dropped phrase.
let clip = speech_pause_phrase(2_400);
assert_eq!(
finish_with_text_end(&clip, 2_500),
Ok(format!("streamed {}", clip.len()))
);
}
#[test]
fn a_stream_that_lost_the_opening_phrase_falls_back_to_the_whole_clip() {
// Speech opens at 500 ms; text that starts at 3 s lost its opening.
let clip = speech_pause_phrase(12_800);
let result = finish_with_text_bounds(&clip, Some(3_000), 4_200);
assert!(
result
.as_ref()
.is_err_and(|reason| reason.contains("precedes")),
"{result:?}"
);
// Text that starts with the speech is the stream's to keep.
assert_eq!(
finish_with_text_bounds(&clip, Some(500), 4_200),
Ok(format!("streamed {}", clip.len()))
);
}
#[test]
fn parakeets_late_first_word_time_is_not_a_lost_opening() {
// An illustrative late first-word timestamp: speech at 220-860 ms and
// text at 1280 ms is a 1,060 ms lag, just past the top of the measured
// 100-1000 ms range. With no pre-roll to exclude, this is a stream
// that lost nothing, as the CPU measurement suggests; the 400 ms
// slack refused it.
let mut clip = vec![0.0; 3_520]; // 220 ms
clip.extend(tone(10_240)); // speech, 220-860 ms
clip.extend(vec![0.0; 6_720]); // pause to the text, 860-1280 ms
clip.extend(tone(5_120)); // the text's own speech, 1280-1600 ms
clip.extend(vec![0.0; 3_200]);
assert!(
finish_with_text_bounds(&clip, Some(1_280), 1_600)
.is_err_and(|reason| reason.contains("precedes")),
"the tight slack is what refused this stream"
);
assert_eq!(
finish_with_opening_slack(&clip, 0, Some(1_280), 1_600, PARAKEET_OPENING_SLACK_SAMPLES),
Ok(format!("streamed {}", clip.len()))
);
}
#[test]
fn parakeets_opening_slack_still_refuses_a_lost_opening() {
// 3 s of speech the stream lost, then a 1 s pause, then the text at
// 4.5 s: more than 1.2 s of slack plus the 300 ms threshold before t0.
let mut clip = vec![0.0; 8_000]; // 500 ms
clip.extend(tone(48_000)); // the lost speech, 500-3500 ms
clip.extend(vec![0.0; 16_000]); // a 1 s pause
clip.extend(tone(16_000)); // the text's own speech, 4500-5500 ms
clip.extend(vec![0.0; 3_200]);
let result =
finish_with_opening_slack(&clip, 0, Some(4_500), 5_500, PARAKEET_OPENING_SLACK_SAMPLES);
assert!(
result
.as_ref()
.is_err_and(|reason| reason.contains("precedes")),
"{result:?}"
);
}
#[test]
fn parakeets_opening_slack_edge_is_one_frame() {
use crate::transcription::pause_segmenter::FRAME_SAMPLES;
// The 1.2 s slack with the 300 ms threshold: a speech frame counts
// only while it ends strictly before t0 - 1.2 s, and the span rule
// refuses speech that opens 300 ms or more before that edge once
// 100 ms is detected before the 400 ms edge. So 15 frames (300 ms)
// ending one frame before the edge are refused, while 14 (280 ms)
// ending at the edge are kept: the edge frame is not counted and the
// span stays under 300 ms.
let text_start_ms: u64 = 3_000;
let covered = text_start_ms as usize * 16 - PARAKEET_OPENING_SLACK_SAMPLES; // 28_800
let frame: usize = FRAME_SAMPLES;
let threshold = UNTRANSCRIBED_SPEECH_SAMPLES / frame; // 15 frames
for (speech_end, frames, refused) in [
(covered - frame, threshold, true), // 28_480: all 15 frames count
(covered, threshold - 1, false), // 28_800: 13 count, 280 ms span
] {
let mut clip = vec![0.0; speech_end - frames * frame];
clip.extend(tone(frames * frame)); // the lost opening
clip.extend(vec![0.0; 4_800]); // the pause to the text
let result = finish_with_opening_slack(
&clip,
0,
Some(text_start_ms),
text_start_ms + 300,
PARAKEET_OPENING_SLACK_SAMPLES,
);
assert_eq!(
result
.as_ref()
.is_err_and(|reason| reason.contains("precedes")),
refused,
"{speech_end}: {result:?}"
);
}
}
#[test]
fn parakeets_sparse_opening_spanning_1800_ms_is_refused() {
// Production's waited case: text at 3.92 s with 720 ms of speech
// detected from 920 ms, but only 240 ms of it before the slack's edge
// at 2.72 s, under the 300 ms threshold. Its span alone refuses it.
let clip = sparse_speech(&[
(920, 80),
(1_620, 80),
(2_320, 80),
(2_920, 200),
(3_220, 280),
]);
let result =
finish_with_opening_slack(&clip, 0, Some(3_920), 4_220, PARAKEET_OPENING_SLACK_SAMPLES);
assert!(
result.as_ref().is_err_and(
|reason| reason.contains("speech from 920 ms precedes it and spans 1800 ms")
),
"{result:?}"
);
}
#[test]
fn parakeets_sparse_opening_spanning_3080_ms_is_refused() {
// The other waited case: text at 4.48 s with 520 ms of speech
// detected from 200 ms, but only 240 ms of it before the slack's edge
// at 3.28 s, under the 300 ms threshold. Its span alone refuses it.
let clip = sparse_speech(&[
(200, 80),
(900, 80),
(1_600, 80),
(3_400, 140),
(3_920, 140),
]);
let result =
finish_with_opening_slack(&clip, 0, Some(4_480), 4_780, PARAKEET_OPENING_SLACK_SAMPLES);
assert!(
result.as_ref().is_err_and(
|reason| reason.contains("speech from 200 ms precedes it and spans 3080 ms")
),
"{result:?}"
);
}
#[test]
fn parakeets_sparse_frames_cannot_hide_a_dense_lost_opening() {
// Four old frames (80 ms) around 1 s, then 800 ms of lost speech from
// 2.8 s to 3.6 s, text at 4 s. Counting only before the 1.2 s edge
// (2.8 s) sees 80 ms and accepts; counting before the 400 ms edge
// (3.6 s) sees the dense speech, so the 1.84 s span refuses it.
let clip = sparse_speech(&[(960, 80), (2_800, 800)]);
let result =
finish_with_opening_slack(&clip, 0, Some(4_000), 4_300, PARAKEET_OPENING_SLACK_SAMPLES);
assert!(
result.as_ref().is_err_and(
|reason| reason.contains("speech from 960 ms precedes it and spans 1840 ms")
),
"{result:?}"
);
}
#[test]
fn parakeets_span_rule_needs_100_ms_before_the_old_edge() {
// Speech at 400 ms starts 1.4 s before the 1.2 s edge at 1.8 s. Four
// frames (80 ms) before the 400 ms edge are under the rule's minimum
// and kept; five (100 ms) are refused.
for (frames, refused) in [(4usize, false), (5, true)] {
let mut clip = vec![0.0; 400 * 16];
clip.extend(tone(frames * 20 * 16));
clip.extend(vec![0.0; 3_200]);
let result = finish_with_opening_slack(
&clip,
0,
Some(3_000),
3_300,
PARAKEET_OPENING_SLACK_SAMPLES,
);
if refused {
assert!(
result.as_ref().is_err_and(|reason| reason
.contains("speech from 400 ms precedes it and spans 1400 ms")),
"{frames}: {result:?}"
);
} else {
assert_eq!(result, Ok(format!("streamed {}", clip.len())), "{frames}");
}
}
}
#[test]
fn parakeets_span_rule_edge_is_one_frame() {
// Text at 3 s puts the 1.2 s edge at 1.8 s: speech starting exactly
// 300 ms before it is refused, one frame later (280 ms) is kept. Both
// have the rule's 100 ms minimum before the 400 ms edge.
for (speech_start_ms, refused) in [(1_500usize, true), (1_520, false)] {
let mut clip = vec![0.0; speech_start_ms * 16];
clip.extend(tone(100 * 16));
clip.extend(vec![0.0; 3_200]);
let result = finish_with_opening_slack(
&clip,
0,
Some(3_000),
3_300,
PARAKEET_OPENING_SLACK_SAMPLES,
);
if refused {
assert!(
result.as_ref().is_err_and(|reason| {
reason.contains("speech from") && reason.contains("spans 300 ms")
}),
"{speech_start_ms}: {result:?}"
);
} else {
assert_eq!(
result,
Ok(format!("streamed {}", clip.len())),
"{speech_start_ms}"
);
}
}
}
#[test]
fn parakeets_measured_lags_are_not_lost_openings() {
// Production refused these streams. Their first detected speech came
// 820-1420 ms before the text, under the span rule's 1.5 s, so this
// fix keeps them accepted.
for (speech_start_ms, text_start_ms) in
[(220u64, 1_280u64), (300, 1_120), (220, 1_440), (340, 1_760)]
{
let mut clip = vec![0.0; speech_start_ms as usize * 16];
clip.extend(tone(640 * 16));
clip.extend(vec![0.0; 3_200]);
let result = finish_with_opening_slack(
&clip,
0,
Some(text_start_ms),
text_start_ms + 300,
PARAKEET_OPENING_SLACK_SAMPLES,
);
assert_eq!(
result,
Ok(format!("streamed {}", clip.len())),
"{speech_start_ms} -> {text_start_ms}"
);
}
}
#[test]
fn hexs_own_sounds_at_the_captures_head_are_not_a_lost_opening() {
// The pre-roll (0-0.45 s), the 272 ms Classic start tone (0.45-0.72 s),
// and the tap's click (0.72-0.82 s) are Hex's own sounds; the first
// word comes 0.8 s later. The stream lost nothing, so the clip is kept.
let mut clip = vec![0.0; 7_200]; // 450 ms of pre-roll
clip.extend(tone(4_352)); // the 272 ms start tone
clip.extend(tone(1_600)); // the tap's click, 100 ms
clip.extend(vec![0.0; 12_448]); // room up to 1.6 s
clip.extend(tone(16_000)); // the dictation itself, 1.6-2.6 s
clip.extend(vec![0.0; 3_200]);
let head = 14_400; // 900 ms: the pre-roll, the tone, and its margin
assert_eq!(
finish_with_text_bounds_ignoring_head(&clip, head, Some(1_600), 2_600),
Ok(format!("streamed {}", clip.len()))
);
// Without the exclusion the same sounds are 400 ms of "speech" before
// the text, which is what a real model sees when they are all the head
// holds.
assert!(
finish_with_text_bounds(&clip, Some(1_600), 2_600)
.is_err_and(|reason| reason.contains("precedes")),
"the head exclusion is what keeps this stream"
);
}
/// As [`finish_with_text_bounds_ignoring_head`], but the stream begins
/// with no head and the capture raises it after `raise_at` samples, as
/// the effect report does once suppression actually took effect.
fn finish_raising_head(
clip: &[f32],
raise_at: usize,
head: usize,
text_start_ms: Option<u64>,
text_end_ms: u64,
) -> Result<String, String> {
let mut fake = FakeStream {
text_start_ms,
text_end_ms: Some(text_end_ms),
..FakeStream::default()
};
let mut capped = PauseCap::new(&mut fake, 0);
let (before, after) = clip.split_at(raise_at.min(clip.len()));
capped.feed(before).unwrap();
capped.raise_ignored_head(head);
capped.feed(after).unwrap();
let result = finish_stream(&mut capped, clip, clip.len());
assert_eq!(fake.fed, clip);
result
}
#[test]
fn media_speech_before_output_suppression_took_effect_is_not_a_lost_opening() {
// 200 ms of room, then 900 ms of what the speakers were playing, then
// the dictation at 1.8 s. The stream began with no head; the raise
// after it began covers the media, so nothing before the text counts.
let mut clip = vec![0.0; 3_200];
clip.extend(tone(14_400));
clip.extend(vec![0.0; 11_200]);
clip.extend(tone(16_000));
clip.extend(vec![0.0; 3_200]);
assert!(
finish_with_text_bounds(&clip, Some(1_800), 2_800)
.is_err_and(|reason| reason.contains("precedes")),
"without the head the media is a lost opening"
);
assert_eq!(
finish_raising_head(&clip, 4_800, 17_600, Some(1_800), 2_800),
Ok(format!("streamed {}", clip.len()))
);
}
/// 200 ms of room, 900 ms of what the speakers played, then the
/// dictation from 1.8 s: a stream whose text starts at 1.8 s.
fn media_then_dictation() -> Vec<f32> {
let mut clip = vec![0.0; 3_200];
clip.extend(tone(14_400));
clip.extend(vec![0.0; 11_200]);
clip.extend(tone(16_000));
clip.extend(vec![0.0; 3_200]);
clip
}
/// Runs the commands the real engine queued through `drive_stream`, the
/// way the worker does after taking the `Begin` head.
fn drive_queued_stream(
mut queued: Vec<Command>,
head: usize,
text_start_ms: u64,
text_end_ms: u64,
) -> (StreamEnd, Receiver<Command>) {
let mut fake = FakeStream {
text_start_ms: Some(text_start_ms),
text_end_ms: Some(text_end_ms),
..FakeStream::default()
};
let mut capped = PauseCap::new(&mut fake, 0).ignoring_head(head);
let (relay, relayed) = mpsc::channel();
for command in queued.drain(..) {
relay.send(command).unwrap();
}
let mut stats = FeedStats::default();
let ended = drive_stream(
1,
&mut capped,
&relayed,
&AtomicBool::new(false),
None,
&mut VecDeque::new(),
&mut stats,
);
(ended, relayed)
}
fn begin_head(command: Command) -> usize {
match command {
Command::Begin { head_ignored, .. } => head_ignored,
_ => panic!("a stream began"),
}
}
#[test]
fn a_head_raised_before_the_finish_keeps_the_stream() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin().expect("the test engine streams");
let clip = media_then_dictation();
stream.feed(&clip);
stream.raise_ignored_head(17_600);
let _finish = engine
.finish_with(
Some(stream),
clip.clone(),
Box::new(|_, _| Ok(String::new())),
)
.unwrap();
let mut queued = commands.try_iter().collect::<Vec<_>>();
let head = begin_head(queued.remove(0));
let (ended, _) = drive_queued_stream(queued, head, 1_800, 2_800);
match ended {
StreamEnd::Finished { result, .. } => {
assert_eq!(result, Ok(format!("streamed {}", clip.len())));
}
_ => panic!("the stream should have finished"),
}
}
#[test]
fn a_head_raised_after_the_finish_cannot_save_the_stream() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin().expect("the test engine streams");
let clip = media_then_dictation();
stream.feed(&clip);
let _finish = engine
.finish_with(
Some(stream),
clip.clone(),
Box::new(|_, _| Ok(String::new())),
)
.unwrap();
let mut queued = commands.try_iter().collect::<Vec<_>>();
let head = begin_head(queued.remove(0));
// The head arrives after the Finish command: the stream finalizes
// without it, so the media it heard is a lost opening.
queued.push(Command::IgnoreHead {
stream: 1,
head: 17_600,
});
let (ended, relayed) = drive_queued_stream(queued, head, 1_800, 2_800);
match ended {
StreamEnd::Finished { result, .. } => assert!(
result
.as_ref()
.is_err_and(|reason| reason.contains("precedes")),
"{result:?}"
),
_ => panic!("the stream should have finished"),
}
// The late head was never handled: the finish already ended the stream.
assert!(matches!(
relayed.try_recv(),
Ok(Command::IgnoreHead {
stream: 1,
head: 17_600
})
));
}
#[test]
fn speech_after_the_raised_head_is_still_a_lost_opening() {
// 200 ms of room and 700 ms of media the raise covers, then 400 ms
// the stream missed at 0.95-1.35 s, text at 1.8 s: still a lost
// opening.
let mut clip = vec![0.0; 3_200];
clip.extend(tone(11_200));
clip.extend(vec![0.0; 800]);
clip.extend(tone(6_400));
clip.extend(vec![0.0; 7_200]);
clip.extend(tone(9_600));
clip.extend(vec![0.0; 3_200]);
let result = finish_raising_head(&clip, 4_800, 14_400, Some(1_800), 2_400);
assert!(
result
.as_ref()
.is_err_and(|reason| reason.contains("precedes")),
"{result:?}"
);
}
#[test]
fn a_lost_opening_after_a_long_pause_still_falls_back_to_the_whole_clip() {
// The review's case: 1.6 s of speech the stream lost, then a 1 s
// pause, then the text at 3.5 s. The pause is longer than the check's
// 400 ms slack, so nothing but counting the speech itself can catch it.
let mut clip = vec![0.0; 14_400]; // 900 ms: pre-roll and start tone
clip.extend(tone(25_600)); // 1.6 s of lost speech, 0.9-2.5 s
clip.extend(vec![0.0; 16_000]); // a 1 s pause
clip.extend(tone(16_000)); // the text's own speech, 3.5-4.5 s
clip.extend(vec![0.0; 3_200]);
let result = finish_with_text_bounds_ignoring_head(&clip, 14_400, Some(3_500), 4_500);
assert!(
result.as_ref().is_err_and(
|reason| reason.contains("precedes") && reason.contains("from 900 to 2500 ms")
),
"{result:?}"
);
}
#[test]
fn a_short_click_before_the_text_does_not_discard_the_stream() {
// A 150 ms click before the speech is not a lost opening.
let mut clip = vec![0.0; 8_000];
clip.extend(tone(2_400));
clip.extend(vec![0.0; 16_000]);
clip.extend(tone(12_800));
clip.extend(vec![0.0; 3_200]);
assert_eq!(
finish_with_text_bounds(&clip, Some(1_600), 2_500),
Ok(format!("streamed {}", clip.len()))
);
}
#[test]
fn a_punctuation_token_does_not_start_the_streams_text() {
let token = |text: &str, t0_ms| transcribe_cpp::Token {
text: text.into(),
t0_ms,
..Default::default()
};
let tokens = [
token(".", 40),
token(" channels", 2_480),
token(" later", 3_000),
];
assert_eq!(spoken_text_start_ms(&tokens), Some(2_480));
assert_eq!(spoken_text_start_ms(&[token(".", 40)]), None);
}
#[test]
fn a_stream_that_switched_language_falls_back_to_the_whole_clip() {
assert_eq!(language_tags("<en-US> hello <en-US> there"), ["<en-US>"]);
assert_eq!(
language_tags("<en-US> hello <de-DE>"),
["<en-US>", "<de-DE>"]
);
let clip = speech_pause_phrase(12_800);
// One tag repeated, as one per segment, is not a switch.
let tags = |raw: &str| {
language_tags(raw)
.into_iter()
.map(str::to_string)
.collect::<Vec<_>>()
};
let same = finish_with_tags(&clip, tags("<en-US> hello <en-US>"));
assert_eq!(same, Ok(format!("streamed {}", clip.len())));
let switched = finish_with_tags(&clip, tags("<en-US> hello <de-DE>"));
assert!(
switched
.as_ref()
.is_err_and(|reason| reason.contains("switched language from <en-US> to <de-DE>")),
"{switched:?}"
);
}
#[test]
fn skipping_pauses_cuts_a_whole_clips_long_pauses_to_their_ends() {
// #899: quiet pre-roll, speech, a 1 s pause, speech, a 10 s pause,
// speech, and a 5 s trailing pause.
let mut clip = vec![0.0; 8_000];
clip.extend(tone(16_000));
clip.extend(vec![0.0; 16_000]);
clip.extend(tone(16_000));
clip.extend(vec![0.0; 160_000]);
clip.extend(tone(16_000));
clip.extend(vec![0.0; 80_000]);
let (kept, dropped) = skip_long_pauses(&clip).expect("long pauses are cut");
let long = 160_000 - PAUSE_HEAD_SAMPLES - PAUSE_TAIL_SAMPLES;
let trailing = 80_000 - PAUSE_HEAD_SAMPLES;
assert_eq!(dropped, long + trailing);
assert_eq!(kept.len(), clip.len() - dropped);
// The short pause passes whole, and the speech after the long one
// follows its head and tail.
assert_eq!(kept[..56_000], clip[..56_000]);
let resumed = 56_000 + PAUSE_HEAD_SAMPLES + PAUSE_TAIL_SAMPLES;
assert_eq!(kept[resumed..resumed + 16_000], clip[216_000..232_000]);
// The trailing pause keeps its head.
assert_eq!(kept.len(), resumed + 16_000 + PAUSE_HEAD_SAMPLES);
}
#[test]
fn skipping_pauses_leaves_short_pauses_and_quiet_only_clips_whole() {
use crate::transcription::pause_segmenter::tests::noise;
let mut clip = vec![0.0; 8_000];
clip.extend(tone(16_000));
clip.extend(vec![0.0; 16_000]);
clip.extend(tone(16_000));
assert!(skip_long_pauses(&clip).is_none());
assert_eq!(whole_clip(clip.clone(), true), clip);
// #841: nothing above the floor, so nothing is taken for a pause.
let mut seed = 3;
let quiet = noise(6_000, -80.0, &mut seed);
assert!(skip_long_pauses(&quiet).is_none());
assert_eq!(whole_clip(quiet.clone(), true), quiet);
}
#[test]
fn with_skip_pauses_off_the_whole_clip_is_untouched() {
let mut clip = vec![0.0; 8_000];
clip.extend(tone(16_000));
clip.extend(vec![0.0; 160_000]);
clip.extend(tone(16_000));
let untouched = whole_clip(clip.clone(), false);
assert_eq!(
untouched.iter().map(|s| s.to_bits()).collect::<Vec<_>>(),
clip.iter().map(|s| s.to_bits()).collect::<Vec<_>>()
);
assert!(whole_clip(clip.clone(), true).len() < clip.len());
}
#[cfg(not(target_os = "macos"))]
#[test]
fn a_whole_clip_is_padded_after_cutting_its_trailing_pause() {
use crate::transcription::UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES;
use crate::transcription::models::TranscriptionModelId;
// #1629: quiet pre-roll, speech, then a 5 s trailing pause. Cutting
// the pause must leave the 400 ms of Unified English silence after
// the cut, where nothing can trim it.
let mut clip = vec![0.0; 8_000];
clip.extend(tone(16_000));
clip.extend(vec![0.0; 80_000]);
let cut = whole_clip(clip.clone(), true);
let cut_len = cut.len();
assert_eq!(cut_len, 8_000 + 16_000 + PAUSE_HEAD_SAMPLES);
let padded = padded_whole_clip(
clip,
true,
Some(TranscriptionModelId::ParakeetUnifiedEnglish),
);
assert_eq!(
padded.len(),
cut_len + UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES
);
assert_eq!(padded[..cut_len], cut[..]);
assert!(padded[cut_len..].iter().all(|&sample| sample == 0.0));
}
fn assert_quiet_speech_is_kept(speech_db: f32, noise_db: f32, dc_offset: f32) {
use crate::transcription::pause_segmenter::{FRAME_SAMPLES, SpeechFrames, tests::noise};
// 17 s of syllables over steady noise.
let mut seed = 11;
let mut clip = noise(17_000, noise_db, &mut seed);
let mut voice_seed = 5;
for start in (0..clip.len()).step_by(4_800) {
let burst = noise(240, speech_db, &mut voice_seed);
for (sample, voice) in clip[start..].iter_mut().zip(burst) {
*sample += voice;
}
}
for sample in &mut clip {
*sample += dc_offset;
}
let mut speech = SpeechFrames::default();
assert!(
!clip
.as_chunks::<FRAME_SAMPLES>()
.0
.iter()
.any(|frame| speech.is_speech(frame)),
"the speech margin misses this speech"
);
let mut fake = FakeStream::default();
let mut capped = PauseCap::new(&mut fake, 0);
for chunk in clip.chunks(1_234) {
capped.feed(chunk).unwrap();
}
capped.finalize().unwrap();
assert_eq!(capped.dropped, 0);
assert_eq!(fake.fed, clip);
}
#[test]
fn a_dictation_stream_hears_trailing_silence_before_it_finalizes() {
// #657: without trailing silence the stream dropped the closing
// full stop or question mark the whole clip kept.
let clip = tone(16_000);
let mut fake = FakeStream::default();
let mut capped = PauseCap::new(&mut fake, 6_400);
for chunk in clip.chunks(1_234) {
capped.feed(chunk).unwrap();
}
assert_eq!(
capped.finalize(),
Ok(format!("streamed {}", 16_000 + 6_400))
);
assert_eq!(capped.dropped, 0);
assert_eq!(fake.fed[..16_000], clip[..]);
assert!(fake.fed[16_000..].iter().all(|&sample| sample == 0.0));
}
fn heard(samples: usize) -> Partial {
Partial {
stable: format!("heard {samples}"),
tentative: String::new(),
}
}
/// Where the worker publishes the text of the stream `commands` began.
fn begun_partials(commands: &Receiver<Command>) -> Option<Partials> {
match commands.try_recv() {
Ok(Command::Begin { partials, .. }) => partials,
_ => panic!("a stream began"),
}
}
/// Drives stream 1 through the commands queued so far, then a cancel.
fn drive_queued(
commands: &Receiver<Command>,
stream: &mut FakeStream,
partials: Option<&Partials>,
) -> FeedStats {
let (relay, relayed) = mpsc::channel();
for command in commands.try_iter() {
relay.send(command).unwrap();
}
relay.send(Command::Cancel { stream: 1 }).unwrap();
let mut stats = FeedStats::default();
let ended = drive_stream(
1,
stream,
&relayed,
&AtomicBool::new(false),
partials,
&mut VecDeque::new(),
&mut stats,
);
assert!(matches!(ended, StreamEnd::Cancelled));
stats
}
#[test]
fn a_dictation_stream_publishes_its_text_after_each_feed_with_live_text() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_live_text();
let mut stream = engine.begin().unwrap();
let partials = begun_partials(&commands).expect("live text gives the stream a slot");
assert_eq!(
stream.take_partial(),
None,
"nothing is published before a feed"
);
stream.feed(&[0.1; 4]);
stream.feed(&[0.2; 2]);
let stats = drive_queued(&commands, &mut FakeStream::default(), Some(&partials));
assert_eq!(stats.partials, 2);
// The owner reads the newest text once, then nothing until it changes.
assert_eq!(stream.take_partial(), Some(heard(6)));
assert_eq!(stream.take_partial(), None);
assert!(!partials.publish(heard(6)), "the same text is not a change");
assert_eq!(stream.take_partial(), None);
assert!(partials.publish(heard(7)));
assert_eq!(stream.take_partial(), Some(heard(7)));
}
#[test]
fn without_live_text_a_dictation_stream_publishes_nothing() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin().unwrap();
assert!(begun_partials(&commands).is_none());
stream.feed(&[0.1; 4]);
let stats = drive_queued(&commands, &mut FakeStream::default(), None);
assert_eq!(stats.partials, 0);
assert_eq!(stream.take_partial(), None);
}
#[test]
fn each_dictation_stream_has_its_own_text() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_live_text();
let mut first = engine.begin().unwrap();
let first_partials = begun_partials(&commands).unwrap();
// An older capture's stream is still finishing when a new one opens.
let mut second = engine.begin().unwrap();
let second_partials = begun_partials(&commands).unwrap();
assert!(first_partials.publish(heard(4)));
assert_eq!(
second.take_partial(),
None,
"the new capture shows no old text"
);
assert_eq!(first.take_partial(), Some(heard(4)));
assert!(second_partials.publish(heard(1)));
assert_eq!(second.take_partial(), Some(heard(1)));
assert_eq!(first.take_partial(), None);
}
#[test]
fn a_failed_feed_clears_the_text_and_stops_publishing() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_live_text();
let mut stream = engine.begin().unwrap();
let partials = begun_partials(&commands).unwrap();
stream.feed(&[0.1; 4]);
stream.feed(&[0.2; 4]);
stream.feed(&[0.3; 4]);
let mut failing = FakeStream {
fail_after: Some(4),
..FakeStream::default()
};
let stats = drive_queued(&commands, &mut failing, Some(&partials));
assert_eq!(stats.partials, 1, "the first feed's text, then nothing");
assert_eq!(failing.fed.len(), 4, "a failed stream is fed no more");
// The plate hides instead of freezing on the last words.
assert_eq!(stream.take_partial(), Some(Partial::default()));
}
fn begun_yielding(commands: &Receiver<Command>) -> Yielding {
match commands.try_recv() {
Ok(Command::BeginYielding { yielding, .. }) => yielding,
_ => panic!("a yielding stream began"),
}
}
#[test]
fn a_yielding_stream_reports_partials_and_finishes_through_the_stream() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin_yielding().unwrap();
let yielding = begun_yielding(&commands);
stream.feed(&[0.1; 4]);
assert_eq!(stream.in_flight(), 4);
let finishing = thread::spawn(move || stream.finish(Duration::from_secs(5)));
// The finish is sent from the other thread; wait for it to queue.
let mut queued = Vec::new();
while queued.len() < 2 {
queued.push(commands.recv().unwrap());
}
let (relay, relayed) = mpsc::channel();
for command in queued {
relay.send(command).unwrap();
}
let state = yielding.0.clone();
let mut fake = FakeStream::default();
let interrupted = drive_yielding(1, &mut fake, &relayed, yielding, &mut VecDeque::new());
assert!(interrupted.is_none());
assert_eq!(finishing.join().unwrap(), Ok("streamed 4".into()));
assert!(!state.open.load(Ordering::Acquire));
assert_eq!(state.consumed.load(Ordering::Acquire), 4);
assert_eq!(
state.partials.latest(),
Some(Partial {
stable: "heard 4".into(),
tentative: String::new(),
})
);
}
#[test]
fn a_dictation_request_closes_a_yielding_stream_and_runs_next() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin_yielding().unwrap();
let yielding = begun_yielding(&commands);
stream.feed(&[0.1; 4]);
let generation = engine.requests.load(Ordering::Acquire);
let _chunk = engine
.foreground(vec![0.0; 3], Box::new(|_, _| Ok("chunk".into())))
.unwrap();
assert_eq!(
engine.requests.load(Ordering::Acquire),
generation + 1,
"foreground work is a dictation-class request"
);
let _dictation = engine.begin().unwrap();
stream.feed(&[0.2; 4]);
let mut fake = FakeStream::default();
let mut deferred = VecDeque::new();
let interrupted = drive_yielding(1, &mut fake, &commands, yielding, &mut deferred);
assert!(matches!(
interrupted,
Some(Command::Begin { stream: 2, .. })
));
assert!(!stream.open(), "dictation closed the stream");
assert_eq!(fake.fed.len(), 4);
assert!(matches!(
deferred.as_slices().0,
[Command::Foreground { clip, .. }] if clip.len() == 3
));
// A closed stream answers at once; its owner transcribes offline.
assert_eq!(stream.finish(Duration::from_secs(5)), Err(PREEMPTED.into()));
}
#[test]
fn yielding_stream_closes_on_feed_failure_cancel_and_unread_drop() {
// Native feed failure inside drive_yielding must mark the stream closed
// so its owner exits its send loop instead of spinning forever.
let (engine, commands) = TranscriptionEngine::for_test();
let mut stream = engine.begin_yielding().unwrap();
let yielding = begun_yielding(&commands);
stream.feed(&[0.1; 4]);
stream.feed(&[0.2; 4]);
let mut failing = FakeStream {
fail_after: Some(4),
..FakeStream::default()
};
assert!(
drive_yielding(1, &mut failing, &commands, yielding, &mut VecDeque::new()).is_none()
);
assert!(
!stream.open(),
"a failed feed must close the yielding stream"
);
assert_eq!(stream.finish(Duration::from_secs(5)), Err(PREEMPTED.into()));
// Explicit cancel closes the stream on exit as well.
let (engine, commands) = TranscriptionEngine::for_test();
let stream = engine.begin_yielding().unwrap();
let yielding = begun_yielding(&commands);
let state = yielding.0.clone();
drop(stream);
assert!(
drive_yielding(
1,
&mut FakeStream::default(),
&commands,
yielding,
&mut VecDeque::new()
)
.is_none()
);
assert!(!state.open.load(Ordering::Acquire));
// Dropping an unread BeginYielding command (e.g. engine shutdown) closes
// the stream automatically via Yielding's Drop impl.
let (engine, commands) = TranscriptionEngine::for_test();
let stream = engine.begin_yielding().unwrap();
assert!(stream.open());
drop(commands);
assert!(!stream.open(), "dropping queued BeginYielding closes open");
}
#[test]
fn an_open_dictation_stream_refuses_a_yielding_stream_instead_of_ending() {
let (engine, commands) = TranscriptionEngine::for_test();
let mut dictation = engine.begin().unwrap();
assert!(matches!(
commands.try_recv().unwrap(),
Command::Begin { stream: 1, .. }
));
let yielding = engine.begin_yielding().unwrap();
dictation.feed(&[0.1; 4]);
let _pending = engine
.finish_with(
Some(dictation),
vec![0.0; 4],
Box::new(|_, _| panic!("the dictation must not be retranscribed offline")),
)
.unwrap();
let mut fake = FakeStream::default();
let ended = drive_stream(
1,
&mut fake,
&commands,
&AtomicBool::new(false),
None,
&mut VecDeque::new(),
&mut FeedStats::default(),
);
let StreamEnd::Finished { result, .. } = ended else {
panic!("the dictation stream did not finish");
};
assert_eq!(result, Ok("streamed 4".to_string()));
assert!(!yielding.open());
}
const SHORT: Deadlines = Deadlines {
stream_finish: Duration::from_millis(50),
job: Duration::from_millis(100),
job_seconds_per_audio_second: 0,
shutdown: Duration::from_millis(100),
};
fn silent() -> Offline {
Box::new(|_, _| Ok(String::new()))
}
/// Takes the next finish the test engine would have run.
fn next_job(commands: &Receiver<Command>) -> Job {
commands
.try_iter()
.find_map(|command| match command {
Command::Finish { job, .. } => Some(job),
_ => None,
})
.expect("a finish was sent")
}
#[test]
fn a_started_job_that_never_ends_fails_instead_of_hanging() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_deadlines(SHORT);
for streamed in [false, true] {
let stream = streamed.then(|| engine.begin().expect("the test engine streams"));
let pending = engine
.finish_with(stream, vec![0.0; 1_600], silent())
.unwrap();
let job = next_job(&commands);
job.start();
let started = Instant::now();
assert_eq!(pending.wait().unwrap_err(), "transcription timed out");
assert!(started.elapsed() < Duration::from_secs(2));
assert!(job.cancel.is_cancelled(), "a timeout aborts the stuck run");
engine.stalled.store(false, Ordering::Release);
}
}
#[test]
fn the_job_clock_does_not_count_time_queued_behind_other_work() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_deadlines(SHORT);
let pending = engine.finish_with(None, Vec::new(), silent()).unwrap();
let job = next_job(&commands);
let worker = thread::spawn(move || {
// Three job deadlines pass before the engine reaches the job.
thread::sleep(SHORT.job * 3);
job.start();
job.finish(Ok(Transcribed {
text: "late but fine".into(),
source: Source::Offline,
finish_ms: 0,
}));
});
assert_eq!(pending.wait().unwrap().text, "late but fine");
worker.join().unwrap();
}
#[test]
fn a_timed_out_job_cancels_only_itself_not_the_next_capture() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_deadlines(SHORT);
let first = engine.finish_with(None, Vec::new(), silent()).unwrap();
let first_job = next_job(&commands);
first_job.start();
// Capture 2 begins while job 1 is still running.
let second = engine.begin().expect("the test engine streams");
assert_eq!(first.wait().unwrap_err(), "transcription timed out");
assert!(first_job.cancel.is_cancelled());
assert!(!second.cancel.is_cancelled(), "capture 2's stream survives");
let Some(Command::Begin { cancel, .. }) = commands.try_iter().next() else {
panic!("capture 2 began a stream");
};
assert!(!cancel.is_cancelled());
// A capture that begins after the timeout is untouched too.
let third = engine.begin().expect("the test engine streams");
assert!(!third.cancel.is_cancelled());
}
#[test]
fn jobs_queued_behind_a_wedged_run_fail_instead_of_waiting_forever() {
let (engine, commands) = TranscriptionEngine::for_test();
let engine = engine.with_deadlines(SHORT);
let wedged = engine.finish_with(None, Vec::new(), silent()).unwrap();
let queued = engine.finish_with(None, Vec::new(), silent()).unwrap();
let wedged_job = next_job(&commands);
let queued_job = next_job(&commands);
wedged_job.start();
assert_eq!(wedged.wait().unwrap_err(), "transcription timed out");
let started = Instant::now();
assert_eq!(queued.wait().unwrap_err(), "transcription engine is stuck");
assert!(started.elapsed() < Duration::from_secs(2));
assert!(
queued_job.cancel.is_cancelled(),
"the engine skips it later"
);
}
#[test]
fn the_job_deadline_grows_with_the_clip() {
let (engine, _commands) = TranscriptionEngine::for_test_without_streaming();
let pending = engine
.finish_with(None, vec![0.0; 16_000 * 30], silent())
.unwrap();
assert_eq!(
pending.job,
JOB_DEADLINE + Duration::from_secs(30 * u64::from(JOB_SECONDS_PER_AUDIO_SECOND))
);
}
#[test]
fn a_parked_engine_holds_its_selection_and_reloads_it_before_the_first_job() {
// A language no model supports fails the reload deterministically,
// without depending on a model installed on the test machine.
let selection = crate::transcription::models::TranscriptionSelection {
language: "zz".into(),
..Default::default()
};
let engine = TranscriptionEngine::start_parked(selection.clone()).unwrap();
assert!(engine.holds(&selection), "the parked model counts as held");
assert!(!engine.streams(), "an unusable selection cannot stream");
let transcribed = engine
.finish_with(
None,
Vec::new(),
Box::new(|_, _| panic!("a parked engine must reload its model first")),
)
.unwrap()
.wait();
assert!(
transcribed
.unwrap_err()
.starts_with("the speech model could not be reloaded"),
"the failure names why the reload failed"
);
assert!(
!engine.holds(&selection),
"after reload fails, the engine must not claim to hold the model"
);
assert_eq!(engine.held_selection(), None);
assert!(!engine.streams());
}
#[test]
fn a_failed_reload_clears_streaming_and_reports_the_error() {
let engine = TranscriptionEngine::start_parked(
crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::ParakeetUnifiedEnglish,
language: "en".into(),
},
)
.unwrap();
assert!(
engine.streams(),
"parked streaming model advertises streaming"
);
let invalid = crate::transcription::models::TranscriptionSelection {
language: "zz".into(),
..Default::default()
};
let result = engine
.reload(invalid.clone())
.unwrap()
.recv_timeout(Duration::from_secs(5))
.unwrap();
assert!(result.is_err());
assert!(!engine.holds(&invalid));
assert_eq!(engine.held_selection(), None);
assert!(
!engine.streams(),
"stale streaming flag from previous slot must be cleared on failed reload"
);
}
/// A real engine thread over macOS's warm transcriber with no model
/// loaded: it cannot stream, so every finish runs the offline closure.
#[cfg(target_os = "macos")]
mod worker {
use super::*;
fn offline_text(text: &'static str) -> Offline {
Box::new(move |_, clip| Ok(format!(" {text} {} ", clip.len())))
}
#[test]
fn a_finish_without_a_stream_transcribes_the_clip_offline() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
assert!(engine.begin().is_none());
let transcribed = engine
.finish_with(None, vec![0.0; 5], offline_text("whole"))
.unwrap()
.wait()
.unwrap();
assert_eq!(transcribed.text, "whole 5");
assert_eq!(transcribed.source, Source::Offline);
}
fn claim_streaming_for_test(engine: &TranscriptionEngine) {
*engine.held.lock().unwrap() = HeldState::Loaded {
selection: None,
backend: None,
streams: true,
};
}
#[test]
fn an_unusable_stream_falls_back_to_the_complete_clip() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
// Claim streaming so a stream opens that the model cannot serve.
claim_streaming_for_test(&engine);
let mut stream = engine.begin().expect("streaming was claimed");
stream.feed(&[0.0; 3]);
let transcribed = engine
.finish_with(Some(stream), vec![0.0; 9], offline_text("fallback"))
.unwrap()
.wait()
.unwrap();
assert_eq!(transcribed.text, "fallback 9");
assert!(matches!(transcribed.source, Source::Fallback(_)));
assert!(!engine.streams());
}
#[test]
fn run_on_a_parked_slot_still_executes_and_keeps_parked_when_switch_fails() {
let selection = crate::transcription::models::TranscriptionSelection {
language: "zz".into(),
..Default::default()
};
let engine = TranscriptionEngine::start_parked(selection.clone()).unwrap();
let (tx, rx) = mpsc::channel();
engine
.run(move |model| {
assert!(model.active().is_none());
tx.send("ran").unwrap();
})
.unwrap();
assert_eq!(rx.recv_timeout(Duration::from_secs(5)).unwrap(), "ran");
assert!(
engine.holds(&selection),
"a switch that left no active model preserves the parked selection"
);
}
#[test]
fn work_runs_in_order_and_failures_reach_the_caller() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
let (order, ran) = mpsc::channel();
let first = order.clone();
engine.run(move |_| first.send("run").unwrap()).unwrap();
let failed = engine
.finish_with(
None,
Vec::new(),
Box::new(move |_, _| {
order.send("finish").unwrap();
Err("dictation was cancelled".into())
}),
)
.unwrap();
assert_eq!(failed.wait().unwrap_err(), "dictation was cancelled");
assert_eq!(ran.try_iter().collect::<Vec<_>>(), ["run", "finish"]);
}
#[test]
fn background_work_yields_to_dictation_sent_before_it_runs() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
assert_eq!(engine.background(|_| 7).unwrap(), Some(7));
let generation = engine.requests.fetch_add(1, Ordering::AcqRel);
let (reply, ran) = mpsc::channel();
engine
.commands
.send(Command::Background {
generation,
work: Box::new(move |model| reply.send(model.is_some()).unwrap()),
})
.unwrap();
assert!(!ran.recv().unwrap(), "stale background work must not run");
}
#[test]
fn a_wedged_run_times_out_its_job_and_later_jobs_still_finish() {
let engine = TranscriptionEngine::start(Model::default())
.unwrap()
.with_deadlines(SHORT);
let (release, wedged) = mpsc::channel::<()>();
let stuck = engine
.finish_with(
None,
Vec::new(),
Box::new(move |_, _| {
let _ = wedged.recv();
Ok("late".into())
}),
)
.unwrap();
assert_eq!(stuck.wait().unwrap_err(), "transcription timed out");
let next = engine
.finish_with(None, vec![0.0; 2], offline_text("next"))
.unwrap();
release.send(()).unwrap();
assert_eq!(next.wait().unwrap().text, "next 2");
}
#[test]
fn dropping_a_wedged_engine_returns() {
let engine = TranscriptionEngine::start(Model::default())
.unwrap()
.with_deadlines(SHORT);
let (_release, wedged) = mpsc::channel::<()>();
let (entered, running) = mpsc::channel();
engine
.run(move |_| {
entered.send(()).unwrap();
let _ = wedged.recv();
})
.unwrap();
running.recv_timeout(Duration::from_secs(5)).unwrap();
let started = Instant::now();
drop(engine);
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn a_job_queued_behind_slow_work_is_not_timed_out() {
let engine = TranscriptionEngine::start(Model::default())
.unwrap()
.with_deadlines(SHORT);
// A model load that outlasts the job deadline three times over.
engine.run(|_| thread::sleep(SHORT.job * 3)).unwrap();
let queued = engine
.finish_with(None, vec![0.0; 4], offline_text("queued"))
.unwrap();
assert_eq!(queued.wait().unwrap().text, "queued 4");
}
#[test]
fn a_timeout_aborts_the_offline_run_through_its_job_token() {
let engine = TranscriptionEngine::start(Model::default())
.unwrap()
.with_deadlines(SHORT);
let (aborted, saw_abort) = mpsc::channel();
let stuck = engine
.finish_with(
None,
Vec::new(),
Box::new(move |_, _| {
// What transcribe-cpp's abort callback polls.
let cancel =
crate::transcription::gguf_session::job_cancel().expect("installed");
while !cancel.is_cancelled() {
thread::sleep(Duration::from_millis(5));
}
aborted.send(()).unwrap();
Err("aborted".into())
}),
)
.unwrap();
assert_eq!(stuck.wait().unwrap_err(), "transcription timed out");
saw_abort.recv_timeout(Duration::from_secs(5)).unwrap();
let next = engine
.finish_with(None, vec![0.0; 2], offline_text("next"))
.unwrap();
assert_eq!(next.wait().unwrap().text, "next 2");
}
#[test]
fn retiring_a_wedged_engine_returns_at_once() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
let (release, wedged) = mpsc::channel::<()>();
let (entered, running) = mpsc::channel();
engine
.run(move |_| {
entered.send(()).unwrap();
let _ = wedged.recv();
})
.unwrap();
running.recv_timeout(Duration::from_secs(5)).unwrap();
let started = Instant::now();
engine.retire();
assert!(started.elapsed() < Duration::from_millis(500));
release.send(()).unwrap();
}
#[test]
fn a_yielding_stream_on_a_model_that_cannot_stream_closes_at_once() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
claim_streaming_for_test(&engine);
let mut stream = engine.begin_yielding().expect("streaming was claimed");
stream.feed(&[0.0; 3]);
assert_eq!(stream.finish(Duration::from_secs(5)), Err(PREEMPTED.into()));
}
#[test]
fn dropping_the_engine_stops_despite_an_open_stream() {
let engine = TranscriptionEngine::start(Model::default()).unwrap();
claim_streaming_for_test(&engine);
let stream = engine.begin().expect("streaming was claimed");
drop(engine);
drop(stream);
}
/// Quitting frees the model by dropping the engine; that must finish
/// work in flight and end the thread that owns the model before
/// returning, or ggml's Metal teardown at exit sees a live buffer.
#[test]
fn dropping_the_engine_ends_the_thread_that_owns_the_model_first() {
struct ThreadExit(Arc<AtomicBool>);
impl Drop for ThreadExit {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
thread_local! {
static EXIT: std::cell::RefCell<Option<ThreadExit>> =
const { std::cell::RefCell::new(None) };
}
let engine = TranscriptionEngine::start(Model::default()).unwrap();
let exited = Arc::new(AtomicBool::new(false));
let finished = Arc::new(AtomicBool::new(false));
let (started, running) = mpsc::channel();
let (on_exit, done) = (exited.clone(), finished.clone());
engine
.run(move |_| {
EXIT.with(|slot| *slot.borrow_mut() = Some(ThreadExit(on_exit)));
started.send(()).unwrap();
thread::sleep(Duration::from_millis(50));
done.store(true, Ordering::SeqCst);
})
.unwrap();
running.recv().unwrap();
drop(engine);
assert!(
finished.load(Ordering::SeqCst),
"work in flight was abandoned"
);
assert!(
exited.load(Ordering::SeqCst),
"the engine thread outlived the engine"
);
}
}
#[test]
fn an_engine_whose_model_cannot_stream_opens_no_stream() {
let (engine, commands) = TranscriptionEngine::for_test_without_streaming();
assert!(engine.begin().is_none());
let pending = engine
.finish_with(None, vec![0.0; 7], Box::new(|_, _| Ok(String::new())))
.unwrap();
assert!(pending.stream_cancel.is_none());
assert!(matches!(
commands.try_iter().collect::<Vec<_>>().as_slice(),
[Command::Finish { stream: None, .. }]
));
}
/// A capture that wanted live text is told which side refuses: the
/// model's own definition, or the device it loaded on.
#[test]
fn a_stream_refusal_names_the_model_or_the_device() {
let (engine, _commands) = TranscriptionEngine::for_test();
assert_eq!(engine.stream_refusal(), None, "it can stream");
*engine.held.lock().unwrap() = HeldState::Empty;
assert_eq!(
engine.stream_refusal(),
Some("no streaming speech model is loaded")
);
*engine.held.lock().unwrap() = HeldState::Loaded {
selection: Some(crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::ParakeetUnifiedEnglish,
language: "en".into(),
}),
backend: None,
streams: false,
};
assert_eq!(
engine.stream_refusal(),
Some(
"the speech model isn't streaming on this device (a CPU, or a GPU that could not start streaming)"
)
);
*engine.held.lock().unwrap() = HeldState::Loaded {
selection: Some(crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::ParakeetV3,
language: "en".into(),
}),
backend: None,
streams: false,
};
assert_eq!(
engine.stream_refusal(),
Some("the selected speech model doesn't stream")
);
// An imported model's catalog entry says it can't stream, but its
// GGUF is only checked when it loads: blame the device instead.
*engine.held.lock().unwrap() = HeldState::Loaded {
selection: Some(crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::Custom(
crate::transcription::models::CustomModelId::parse("custom-0123456789abcdef")
.unwrap(),
),
language: "en".into(),
}),
backend: None,
streams: false,
};
assert_eq!(
engine.stream_refusal(),
Some(
"the speech model isn't streaming on this device (a CPU, or a GPU that could not start streaming)"
)
);
}
}