hex/src/transcription/engine.rs
Dax 68127fde7a
stream: a faster live-text geometry from the model's own menus (#2107)
* stream: a faster live-text geometry from the model's own menus

Live text trails speech by a whole chunk plus right context: 2.08 s on
Parakeet Unified English, whose default tuple is 70/13/13 frames. The only
knob was HEX_STREAM_CHUNK_MS, which forced right == chunk and silently
disabled streaming when the model's menu rejected the value.

Labs › Faster live text (labs.faster_live_text, off by default) asks for a
shorter tuple chosen from the model's own GGUF chunk menus: the largest
chunk frame count from 2 to 7 and the largest right up to 7, which is
560/560 ms on Unified English (70/7/7, 1.12 s of lookahead) at about 1.6
times the encoder work. A file whose header Hex cannot read still asks for
560/560 in shipped 80 ms frames and trusts the native probe.

HEX_STREAM_RIGHT_MS joins HEX_STREAM_CHUNK_MS; a chunk alone still sets
the right context, and the env wins over the lab. A geometry the model's
menu rejects now warns and falls back to the default tuple instead of
turning streaming off.

The geometry is cached on the session with the tuning it was probed for,
and the engine compares that tuning as each live stream opens, so a toggle
change applies to the next capture without a restart (and every other
capture pays one comparison).

Measured by aymuos15: with 13-frame chunks, live text arrives about 2.08 s
behind speech, and right context is what delays it.

closes #2102

* audio: the press-across-reopen helper is Linux and Windows only

#2098 added a re-export of interruption::capture_idle for the two listeners
that read it, but gated it on test too, so a macOS build carries an import
nothing there uses. Check macOS (clippy -D warnings) fails on dev with
unused import: interruption::capture_idle; PRs only compile on macOS, so it
landed unseen.

* stream: gate the re-probe, adopt it while idle, keep a failed geometry

Review fixes for #2107:

- refresh_stream only runs after the gated probe passed (HEX_STREAMING,
  capability, GPU), so a parked engine on a CPU never starts a stream, and
  a non-Parakeet model is never re-probed.
- a changed tuning is the only thing that re-probes: a failure keeps the
  working geometry and is not retried, and toggling back is a no-op.
- the header is read only when the lab's tuple needs its menus, lazily at
  load or on the first re-probe; a header that reads fine without chunk
  menus (a cache-aware model) takes no buffered extension at all.
- the engine re-probes after each command and on its idle tick instead of
  at capture start, and yielding streams check cancellation first.
- macOS re-probes with stream_run_options, as its load probe and streams do.
- gguf_header keeps only the Parakeet stream keys, and the frame size uses
  checked_mul.
- the card and docs say the pasted text comes from the same shorter
  lookahead.

* stream: drop the unused architecture from the macOS probe call

probe_stream no longer takes an architecture (the session reads the file's
own), so load_selection's match became an unused variable in a macOS-only
module. Linux clippy cannot see it; Check macOS can.

* stream: re-probe only when the engine is quiet

Review follow-ups for #2107:

- the after-command re-probe waits for `next.is_empty() && !recording()`, so a
  queued Begin, deferred meeting chunk, or active recording never waits
  behind the probe.
- both idle-tick re-probes check `!recording()` too, and the unload tick keeps
  its park behind the same guard.
- docs/features/labs.md's Faster live text row indents its continuation lines
  at the table's column like every other row.
2026-11-20 18:26:14 -05:00

2743 lines
102 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 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;
/// The model the engine owns: macOS keeps its warm, switchable transcriber
use streaming::*;
/// (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>,
},
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).
#[cfg_attr(target_os = "macos", allow(dead_code))]
Reload(crate::transcription::models::TranscriptionSelection),
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()
}
}
/// What the worker shares with a yielding stream's owner: whether the stream
/// is still open on the engine, and its latest partial text.
#[derive(Clone)]
pub(crate) struct Yielding {
open: Arc<AtomicBool>,
/// Samples the model has consumed.
consumed: Arc<AtomicUsize>,
partials: Partials,
}
impl Yielding {
fn new() -> Self {
Self {
open: Arc::new(AtomicBool::new(true)),
consumed: Arc::default(),
partials: Partials::default(),
}
}
fn close(&self) {
self.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,
yielding: Yielding,
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.yielding.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.yielding.consumed.load(Ordering::Acquire))
}
/// The model's latest text for the audio fed so far.
pub(crate) fn partial(&self) -> Option<Partial> {
self.yielding.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 the loaded model can stream on its device; while it is parked,
/// whether its definition advertises streaming.
streams: Arc<AtomicBool>,
/// 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<()>>,
}
/// The GGUF selection the engine's model held after its last command.
type Held = Arc<Mutex<Option<crate::transcription::models::TranscriptionSelection>>>;
/// 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(),
});
}
}
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> {
let streams = model.stream_options().is_some();
Self::with_model(Some(model), None, streams)
}
/// 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> {
let streams = crate::transcription::models::validate(&selection)
.is_ok_and(|definition| definition.streams);
Self::with_model(None, Some(selection), streams)
}
/// The engine and its worker thread: `model` loaded, or `parked` waiting
/// for the first command that needs it. `streams` is what the thread
/// publishes until the model loads.
fn with_model(
model: Option<Model>,
parked: Option<crate::transcription::models::TranscriptionSelection>,
streams: bool,
) -> Result<Self> {
let streams = Arc::new(AtomicBool::new(streams));
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(
model
.as_ref()
.and_then(|model| model.gguf_selection().cloned())
.or_else(|| parked.clone()),
));
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) = &model {
publish_out_of_memory(model);
}
let worker = Worker {
model,
parked,
reload_error: None,
idle_since: Instant::now(),
running: running.clone(),
stalled: stalled.clone(),
streams: streams.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,
streams,
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(),
streams: Arc::new(AtomicBool::new(true)),
live_text: || false,
held: Held::default(),
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.streams.store(false, Ordering::Release);
(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.load(Ordering::Acquire) {
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.load(Ordering::Acquire) {
return None;
}
let id = self.next_stream.fetch_add(1, Ordering::Relaxed) + 1;
let cancel = CancelToken::new();
let yielding = Yielding::new();
self.commands
.send(Command::BeginYielding {
stream: id,
cancel: cancel.clone(),
yielding: yielding.clone(),
})
.ok()?;
Some(YieldingStream {
id,
cancel,
yielding,
sent: 0,
finished: false,
commands: self.commands.clone(),
})
}
/// Whether the loaded model can stream on its device.
pub(crate) fn streams(&self) -> bool {
self.streams.load(Ordering::Acquire)
}
/// 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.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn reload(
&self,
selection: crate::transcription::models::TranscriptionSelection,
) -> Result<()> {
self.commands
.send(Command::Reload(selection))
.map_err(|_| eyre!("transcription engine stopped"))
}
/// 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. 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())
.as_ref()
== Some(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())
.clone()
}
/// 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> {
if self.streams.load(Ordering::Acquire) {
return None;
}
match self.held_selection() {
Some(selection) => {
use crate::transcription::models::{TranscriptionModelId, definition};
// An imported model's catalog entry says it can't stream, but
// its GGUF is only checked when it loads; blame the device.
if !matches!(selection.model, TranscriptionModelId::Custom(_))
&& !definition(selection.model).streams
{
Some("the selected speech model doesn't stream")
} else {
Some(
"the speech model isn't streaming on this device (a CPU, or a GPU that could not start streaming)",
)
}
}
None => Some("no streaming speech model is loaded"),
}
}
}
/// 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 {
/// `None` while unloaded for idleness (Labs › Free memory when idle) or
/// after its reload failed.
model: Option<Model>,
/// What an unloaded model reloads, before the next command that needs it.
parked: Option<crate::transcription::models::TranscriptionSelection>,
/// Why the last reload failed, so the job it failed can name it.
reload_error: Option<String>,
/// When the last command ended.
idle_since: Instant,
running: Running,
stalled: Arc<AtomicBool>,
streams: 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.
if next.is_empty() {
self.yielding_stream(stream, &cancel, &yielding, &commands, &mut next);
}
yielding.close();
}
Command::FinishYielding { reply, .. } => {
let _ = reply.send(Err(PREEMPTED.into()));
}
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);
}
Command::Run(work) => {
if let Some(model) = self.model() {
work(model);
}
}
Command::Reload(selection) => {
tracing::info!(model = ?selection.model, "replacing the speech model in place");
self.model = None;
self.parked = Some(selection);
// A failed load stays parked; the next command tries again.
let _ = self.model();
}
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.model.as_ref() {
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.publish_streams();
self.publish_selection();
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
.model
.as_ref()
.and_then(|model| model.gguf_selection())
.cloned()
else {
return;
};
self.model = None;
tracing::info!(model = ?selection.model, "unloaded the idle speech model");
self.parked = Some(selection);
}
/// 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.model.as_mut() {
model.refresh_stream();
}
}
/// The model, reloading an unloaded one first. Audio sent meanwhile waits
/// in the queue, so nothing recorded is lost.
fn model(&mut self) -> Option<&mut Model> {
if self.model.is_none()
&& let Some(selection) = self.parked.clone()
{
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.model = Some(model);
self.parked = None;
self.reload_error = None;
}
Err(error) => {
tracing::warn!(
error = format!("{error:#}"),
"could not reload the speech model"
);
self.reload_error = Some(error.to_string());
}
}
}
self.model.as_mut()
}
/// Whether the model can stream, kept as it was while it is unloaded so
/// the next capture still opens a stream (which reloads it).
fn publish_streams(&self) {
if let Some(model) = &self.model {
self.streams
.store(model.stream_options().is_some(), Ordering::Release);
}
}
/// Any command may load or switch the model (a dictation job activates
/// its selection), so the held selection is refreshed after each. An
/// unloaded model still counts as held: work sent to it reloads it.
fn publish_selection(&self) {
let current = match &self.model {
Some(model) => model.gguf_selection(),
None => self.parked.as_ref(),
};
let mut held = self.held.lock().unwrap_or_else(|error| error.into_inner());
if held.as_ref() != current {
*held = current.cloned();
}
}
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.model.is_some();
let model_streams = self
.model
.as_ref()
.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.model.as_mut() else {
return;
};
let trailing_silence = stream_trailing_silence(model);
let closing_mark = stream_requires_closing_mark(model);
let ended = model.with_stream(&options, cancel, |stream| {
let mut capped = PauseCap::new(stream, trailing_silence).ignoring_head(head_ignored);
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.model.as_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.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.publish_streams();
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()
}
#[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> {
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);
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 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"
);
}
#[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 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_eq!(yielding.consumed.load(Ordering::Acquire), 4);
assert_eq!(
yielding.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 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"
);
}
/// 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);
}
#[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.
engine.streams.store(true, Ordering::Release);
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.load(Ordering::Acquire));
}
#[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();
engine.streams.store(true, Ordering::Release);
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();
engine.streams.store(true, Ordering::Release);
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();
engine.streams.store(false, Ordering::Release);
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.streams.store(false, Ordering::Release);
assert_eq!(
engine.stream_refusal(),
Some("no streaming speech model is loaded")
);
*engine.held.lock().unwrap() = Some(crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::ParakeetUnifiedEnglish,
language: "en".into(),
});
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() = Some(crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::ParakeetV3,
language: "en".into(),
});
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() = Some(crate::transcription::models::TranscriptionSelection {
model: crate::transcription::models::TranscriptionModelId::Custom(
crate::transcription::models::CustomModelId::parse("custom-0123456789abcdef")
.unwrap(),
),
language: "en".into(),
});
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)"
)
);
}
}