use std::io::{Read, Seek}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use color_eyre::eyre::Result; use hound::{Sample, SampleFormat, WavReader, WavSpec}; use crate::transcription::engine::{ HeldModel, dictation_busy, held, timestamp_level, transcribe_clip, transcribe_clip_timed, }; use crate::transcription::models::TranscriptionSelection; use crate::transcription::transcript::{TimestampLevel, Transcript}; /// The service's own model, for a selection the dictation engine does not /// hold: macOS's switchable transcriber, or one local GGUF model. #[cfg(target_os = "macos")] type WarmTranscriber = crate::transcription::WarmTranscriber; #[cfg(not(target_os = "macos"))] type WarmTranscriber = crate::transcription::local_transcriber::WarmLocal; const COMMAND_CAPACITY: usize = 1; const MIN_SAMPLE_RATE: u32 = 8_000; const MAX_SAMPLE_RATE: u32 = 192_000; const MAX_CHANNELS: u16 = 8; const MAX_NORMALIZED_AUDIO_BYTES: usize = 64 * 1024 * 1024; const MAX_NORMALIZED_SAMPLES: usize = MAX_NORMALIZED_AUDIO_BYTES / size_of::(); /// Pause before asking again while dictation holds the shared engine. const SHARED_RETRY: Duration = Duration::from_millis(50); /// How long host audio waits out a dictation, such as a locked one, before /// using a copy of the service's own. const SHARED_WAIT: Duration = Duration::from_secs(20); /// Longer host audio would hold a dictation released during it behind it on /// the shared engine, so it runs on a copy of the service's own. `hex /// transcribe` sends a long file in pieces of this length. pub(crate) const SHARED_MAX_SAMPLES: usize = 30 * 16_000; pub struct TranscriptionService { commands: Option>, worker: Option>, } #[derive(Clone)] pub struct TranscriptionServiceHandle { commands: SyncSender, audio_busy: Arc, } #[derive(Debug)] pub struct AudioClip { /// The 16 kHz mono samples every transcriber runs. pub(crate) samples: Vec, pub duration_ms: u64, } pub struct TranscriptionJob { canceled: Arc, result: Receiver>, } pub struct AudioAdmission(Arc); #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AudioError { Invalid, Unsupported, ResourceExhausted, } /// The sample types the canonical WAV decoder reads, chosen by a file's spec. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum WavFormat { F32, I8, I16, I32, } /// The accepted WAV input: 8 kHz through 192 kHz and one through eight /// channels. `Unsupported` for anything else, before any samples are /// allocated. pub(crate) fn validate_wav_input(spec: &WavSpec) -> Result<(), AudioError> { if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&spec.sample_rate) || !(1..=MAX_CHANNELS).contains(&spec.channels) { return Err(AudioError::Unsupported); } Ok(()) } /// The sample type `spec` selects: integer PCM or 32-bit float. `Unsupported` /// for a format the decoder does not read. pub(crate) fn wav_format(spec: &WavSpec) -> Result { Ok(match (spec.sample_format, spec.bits_per_sample) { (SampleFormat::Float, 32) => WavFormat::F32, (SampleFormat::Int, 1..=8) => WavFormat::I8, (SampleFormat::Int, 9..=16) => WavFormat::I16, (SampleFormat::Int, 17..=32) => WavFormat::I32, _ => return Err(AudioError::Unsupported), }) } #[derive(Debug)] pub enum TranscriptionServiceError { QueueFull, Unavailable, Cancelled, Model(String), Inference(String), /// The model cannot produce the asked-for timings natively. Timestamps, } enum Command { Prepare { selection: TranscriptionSelection, canceled: Arc, response: SyncSender>, }, Transcribe { selection: TranscriptionSelection, clip: AudioClip, timings: TimestampLevel, admission: AudioAdmission, canceled: Arc, response: SyncSender>, }, } impl TranscriptionService { pub fn start() -> Result<(Self, TranscriptionServiceHandle)> { let (commands, receiver) = mpsc::sync_channel(COMMAND_CAPACITY); let audio_busy = Arc::new(AtomicBool::new(false)); let worker = thread::Builder::new() .name("transcription-service".into()) .spawn(move || run(receiver))?; Ok(( Self { commands: Some(commands.clone()), worker: Some(worker), }, TranscriptionServiceHandle { commands, audio_busy, }, )) } pub fn shutdown(&mut self) { self.commands.take(); if let Some(worker) = self.worker.take() && worker.join().is_err() { tracing::error!("transcription service worker panicked during shutdown"); } } } impl Drop for TranscriptionService { fn drop(&mut self) { self.shutdown(); } } impl TranscriptionServiceHandle { pub fn admit_audio(&self) -> Option { self.audio_busy .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .ok() .map(|_| AudioAdmission(self.audio_busy.clone())) } pub fn prepare( &self, selection: TranscriptionSelection, canceled: Arc, ) -> std::result::Result<(), TranscriptionServiceError> { let (response, result) = mpsc::sync_channel(1); self.submit(Command::Prepare { selection, canceled, response, })?; result .recv() .unwrap_or(Err(TranscriptionServiceError::Unavailable)) } pub fn transcribe( &self, selection: TranscriptionSelection, clip: AudioClip, admission: AudioAdmission, timings: TimestampLevel, ) -> std::result::Result { let (response, result) = mpsc::sync_channel(1); let canceled = Arc::new(AtomicBool::new(false)); self.submit(Command::Transcribe { selection, clip, timings, admission, canceled: canceled.clone(), response, })?; Ok(TranscriptionJob { canceled, result }) } fn submit(&self, command: Command) -> std::result::Result<(), TranscriptionServiceError> { match self.commands.try_send(command) { Ok(()) => Ok(()), Err(TrySendError::Full(_)) => Err(TranscriptionServiceError::QueueFull), Err(TrySendError::Disconnected(_)) => Err(TranscriptionServiceError::Unavailable), } } } impl Drop for AudioAdmission { fn drop(&mut self) { self.0.store(false, Ordering::Release); } } impl TranscriptionJob { pub fn wait_timeout( &self, timeout: Duration, ) -> std::result::Result< Option>, TranscriptionServiceError, > { match self.result.recv_timeout(timeout) { Ok(result) => Ok(Some(result)), Err(RecvTimeoutError::Timeout) => Ok(None), Err(RecvTimeoutError::Disconnected) => Err(TranscriptionServiceError::Unavailable), } } pub fn cancel(&self) { self.canceled.store(true, Ordering::Release); } } impl Drop for TranscriptionJob { fn drop(&mut self) { self.cancel(); } } impl AudioClip { pub fn decode_wav(reader: R) -> std::result::Result { let mut reader = WavReader::new(reader).map_err(|_| AudioError::Invalid)?; let spec = reader.spec(); validate_wav_input(&spec)?; let frames = usize::try_from(reader.duration()).map_err(|_| AudioError::ResourceExhausted)?; let normalized_samples = frames .checked_mul(16_000) .and_then(|samples| samples.checked_add(spec.sample_rate as usize - 1)) .map(|samples| samples / spec.sample_rate as usize) .ok_or(AudioError::ResourceExhausted)?; if frames == 0 || frames > MAX_NORMALIZED_SAMPLES || normalized_samples > MAX_NORMALIZED_SAMPLES { return Err(AudioError::ResourceExhausted); } let channels = usize::from(spec.channels); let int_scale = 2_f32.powi(i32::from(spec.bits_per_sample) - 1); let mono = match wav_format(&spec)? { WavFormat::F32 => { decode_mono::<_, f32, _>(&mut reader, channels, frames, |sample| sample)? } WavFormat::I8 => decode_mono::<_, i8, _>(&mut reader, channels, frames, |sample| { f32::from(sample) / 128.0 })?, WavFormat::I16 => decode_mono::<_, i16, _>(&mut reader, channels, frames, |sample| { f32::from(sample) / int_scale })?, WavFormat::I32 => decode_mono::<_, i32, _>(&mut reader, channels, frames, |sample| { sample as f32 / int_scale })?, }; let duration_ms = mono.len() as u64 * 1_000 / u64::from(spec.sample_rate); let samples = crate::dictation::try_resample_for_parakeet(&mono, spec.sample_rate) .map_err(|_| AudioError::Unsupported)?; if samples.len() > MAX_NORMALIZED_SAMPLES { return Err(AudioError::ResourceExhausted); } Ok(Self { samples, duration_ms, }) } } fn decode_mono( reader: &mut WavReader, channels: usize, frames: usize, convert: F, ) -> std::result::Result, AudioError> where R: Read, S: Sample, F: Fn(S) -> f32, { let mut mono = Vec::new(); mono.try_reserve_exact(frames) .map_err(|_| AudioError::ResourceExhausted)?; let mut samples = reader.samples::(); for _ in 0..frames { let mut sum = 0.0_f64; for _ in 0..channels { let sample = samples .next() .ok_or(AudioError::Invalid)? .map_err(|_| AudioError::Invalid)?; let sample = convert(sample); if !sample.is_finite() { return Err(AudioError::Invalid); } sum += f64::from(sample); } let average = (sum / channels as f64) as f32; if !average.is_finite() { return Err(AudioError::Invalid); } mono.push(average); } Ok(mono) } fn run(commands: Receiver) { #[cfg(target_os = "macos")] crate::parakeet::prioritize_inference_thread(); let mut active = WarmTranscriber::default(); while let Ok(command) = commands.recv() { match command { Command::Prepare { selection, canceled, response, } => { let _ = response.send(prepare(&mut active, &selection, &canceled)); } Command::Transcribe { selection, clip, timings, admission, canceled, response, } => { let result = transcribe(&mut active, &selection, clip, &canceled, timings); // A client woken by this result admits its next clip at once // (a long file is one clip after another), so the slot must be // free before the send, not when the worker loops again. drop(admission); let _ = response.send(result); } } } } fn check_canceled(canceled: &AtomicBool) -> std::result::Result<(), TranscriptionServiceError> { if canceled.load(Ordering::Acquire) { Err(TranscriptionServiceError::Cancelled) } else { Ok(()) } } /// Loads `selection`, or prewarms it when it is already loaded, so a host can /// prepare when it starts recording and its clips skip the idle restore. /// When the dictation engine holds the model, prepare uses that copy and never /// loads its own; a dictation in progress means it is warm already. fn prepare( active: &mut WarmTranscriber, selection: &TranscriptionSelection, canceled: &Arc, ) -> std::result::Result<(), TranscriptionServiceError> { if let Some(engine) = crate::transcription::engine::TranscriptionEngine::shared() && engine.holds(selection) { *active = WarmTranscriber::default(); if dictation_busy() { return Ok(()); } return match with_shared_model(selection, canceled, Duration::ZERO, HeldModel::prewarm)? { Some(prewarmed) => { prewarmed.map_err(|error| TranscriptionServiceError::Model(error.to_string())) } // Dictation claimed the engine first, so the model is running. None if engine.holds(selection) => Ok(()), None => prepare_own(active, selection, canceled), }; } prepare_own(active, selection, canceled) } /// Loads `selection` into the service's own copy, or prewarms that copy. fn prepare_own( active: &mut WarmTranscriber, selection: &TranscriptionSelection, canceled: &Arc, ) -> std::result::Result<(), TranscriptionServiceError> { check_canceled(canceled)?; let loaded = active .active() .is_some_and(|model| model.matches_selection(selection)); let model = load(active, selection)?; if loaded { model .prewarm() .map_err(|error| TranscriptionServiceError::Model(error.to_string()))?; } Ok(()) } fn load<'a>( active: &'a mut WarmTranscriber, selection: &TranscriptionSelection, ) -> std::result::Result<&'a mut HeldModel, TranscriptionServiceError> { active .activate(selection) .map_err(|error| TranscriptionServiceError::Model(error.to_string())) } /// Runs `work` on the dictation engine's loaded model when it is the GGUF /// model `selection` asks for, so the app never holds a second copy for host /// audio. `None` when there is no engine (a direct-child service) or it holds /// another model, or when dictation stays busy for `wait`. Like meeting /// chunks, it starts only while no dictation is capturing or transcribing. fn with_shared_model( selection: &TranscriptionSelection, canceled: &Arc, wait: Duration, work: impl FnOnce(&mut HeldModel) -> R + Send + Clone + 'static, ) -> std::result::Result, TranscriptionServiceError> { enum Shared { Busy, Canceled, Other, Ran(R), } let Some(engine) = crate::transcription::engine::TranscriptionEngine::shared() else { return Ok(None); }; let started = Instant::now(); loop { check_canceled(canceled)?; let give_up = || { if started.elapsed() >= wait { return true; } thread::sleep(SHARED_RETRY); false }; if dictation_busy() { if give_up() { return Ok(None); } continue; } let selection = selection.clone(); let canceled = canceled.clone(); let work = work.clone(); let ran = engine.background(move |model| { if dictation_busy() { return Shared::Busy; } if canceled.load(Ordering::Acquire) { return Shared::Canceled; } match held(model, &selection) { Some(transcriber) => Shared::Ran(work(transcriber)), None => Shared::Other, } }); match ran { Ok(Some(Shared::Ran(result))) => return Ok(Some(result)), Ok(Some(Shared::Canceled)) => return Err(TranscriptionServiceError::Cancelled), Ok(Some(Shared::Other)) | Err(_) => return Ok(None), Ok(None | Some(Shared::Busy)) => { if give_up() { return Ok(None); } } } } } fn transcribe( active: &mut WarmTranscriber, selection: &TranscriptionSelection, clip: AudioClip, canceled: &Arc, timings: TimestampLevel, ) -> std::result::Result { check_canceled(canceled)?; let mut samples = clip.samples; if heard_nothing(selection, &samples, timings) { return Ok(Transcript::default()); } let engine_has_model = if samples.len() <= SHARED_MAX_SAMPLES { let audio = Arc::new(samples); let shared = { let audio = audio.clone(); with_shared_model(selection, canceled, SHARED_WAIT, move |model| { run_clip(model, audio.as_ref().clone(), timings) })? }; if let Some(transcript) = shared { *active = WarmTranscriber::default(); check_canceled(canceled)?; return transcript; } samples = Arc::unwrap_or_clone(audio); false } else { with_shared_model(selection, canceled, SHARED_WAIT, |_| ())?.is_some() }; let model = load(active, selection)?; check_canceled(canceled)?; let transcript = run_clip(model, samples, timings); // A long clip's copy is only temporary when the engine holds the model. if engine_has_model { *active = WarmTranscriber::default(); } let transcript = transcript?; check_canceled(canceled)?; Ok(transcript) } /// Whether a GGUF clip holds only silence, as a long GGUF clip's silent /// chunks are skipped: models invent text for silence (#1194) or run to their /// generation cap (#968). Only an installed speech detector is asked, so a /// request never starts its download, and a timed request still gets the /// model's own answer or refusal. fn heard_nothing( selection: &TranscriptionSelection, samples: &[f32], timings: TimestampLevel, ) -> bool { timings == TimestampLevel::None && matches!( crate::transcription::models::definition(selection.model).runtime, crate::transcription::models::ModelRuntime::Gguf(_) ) && crate::transcription::models::speech_detector_installed() && !crate::transcription::gguf_session::chunk_may_hold_speech(samples) } /// Transcribes `samples` on a held model, with the model's own timings only /// when the request asked for them and the model produces that level. Nothing /// estimates or downgrades a level: a word request a segment-only model cannot /// answer is refused instead. fn run_clip( model: &mut HeldModel, samples: Vec, timings: TimestampLevel, ) -> std::result::Result { if timings == TimestampLevel::None { return transcribe_clip(model, samples) .map(|text| Transcript { text, ..Default::default() }) .map_err(|error| TranscriptionServiceError::Inference(error.to_string())); } check_timings(timestamp_level(model), timings)?; transcribe_clip_timed(model, samples).map_err(TranscriptionServiceError::Inference) } /// The 422 decision: a timed request is answered only when the model produces /// that level itself. Nothing estimates the times or answers a word request /// with segments. fn check_timings( model: TimestampLevel, requested: TimestampLevel, ) -> std::result::Result<(), TranscriptionServiceError> { if requested.supported_by(model) { Ok(()) } else { Err(TranscriptionServiceError::Timestamps) } } #[cfg(test)] mod tests { use std::io::Cursor; use hound::{WavSpec, WavWriter}; use super::*; #[test] fn wav_decode_downmixes_and_resamples_without_a_duration_limit() { let mut wav = Cursor::new(Vec::new()); { let mut writer = WavWriter::new( &mut wav, WavSpec { channels: 2, sample_rate: 48_000, bits_per_sample: 16, sample_format: SampleFormat::Int, }, ) .unwrap(); for _ in 0..61 * 48_000 { writer.write_sample(16_384_i16).unwrap(); writer.write_sample(-16_384_i16).unwrap(); } writer.finalize().unwrap(); } wav.set_position(0); let clip = AudioClip::decode_wav(wav).unwrap(); assert_eq!(clip.duration_ms, 61_000); assert_eq!(clip.samples.len(), 61 * 16_000); assert!(clip.samples.iter().all(|sample| sample.abs() < 0.001)); } #[test] fn invalid_wav_is_rejected() { assert_eq!( AudioClip::decode_wav(Cursor::new(b"not a wav".to_vec())).unwrap_err(), AudioError::Invalid ); } #[test] fn hostile_wav_metadata_is_rejected_before_audio_allocation() { let mut wav = wav_bytes(WavSpec { channels: 1, sample_rate: 16_000, bits_per_sample: 16, sample_format: SampleFormat::Int, }); let data = wav.windows(4).position(|bytes| bytes == b"data").unwrap(); let declared_bytes = u32::try_from((MAX_NORMALIZED_SAMPLES + 1) * 2).unwrap(); wav[data + 4..data + 8].copy_from_slice(&declared_bytes.to_le_bytes()); assert_eq!( AudioClip::decode_wav(Cursor::new(wav)).unwrap_err(), AudioError::ResourceExhausted ); } #[test] fn unsupported_sample_rates_are_rejected_before_resampling() { let wav = wav_bytes(WavSpec { channels: 1, sample_rate: 1, bits_per_sample: 16, sample_format: SampleFormat::Int, }); assert_eq!( AudioClip::decode_wav(Cursor::new(wav)).unwrap_err(), AudioError::Unsupported ); } #[test] fn float_downmix_accumulates_large_finite_channels_without_overflow() { let mut wav = Cursor::new(Vec::new()); { let mut writer = WavWriter::new( &mut wav, WavSpec { channels: 8, sample_rate: 16_000, bits_per_sample: 32, sample_format: SampleFormat::Float, }, ) .unwrap(); for _ in 0..8 { writer.write_sample(f32::MAX).unwrap(); } writer.finalize().unwrap(); } wav.set_position(0); let clip = AudioClip::decode_wav(wav).unwrap(); assert!(clip.samples.iter().all(|sample| sample.is_finite())); } #[test] fn a_timed_request_is_answered_only_at_the_models_own_level() { use crate::transcription::transcript::TimestampLevel::{None, Segment, Word}; assert!( matches!( check_timings(Segment, Word), Err(TranscriptionServiceError::Timestamps) ), "word timings are never derived from a segment-only model" ); assert!(check_timings(Segment, Segment).is_ok()); assert!(check_timings(Word, Word).is_ok()); assert!(check_timings(Word, Segment).is_ok()); assert!(check_timings(None, None).is_ok()); } #[test] fn audio_admission_is_exclusive() { let (_service, handle) = TranscriptionService::start().unwrap(); let admission = handle.admit_audio().unwrap(); assert!(handle.admit_audio().is_none()); drop(admission); assert!(handle.admit_audio().is_some()); } /// A file worker or API client woken by its result admits its next clip /// right away, so the slot is already free when the result arrives. The /// response is a rendezvous channel and the test does not receive until /// the slot reads free, so a send that still holds the admission blocks /// with no one to answer it and this fails every time. The job is /// cancelled before the worker can read it, so it answers `Cancelled` /// without loading a model. #[test] fn a_jobs_result_arrives_only_after_its_slot_is_free() { let (commands, receiver) = mpsc::sync_channel(COMMAND_CAPACITY); let handle = TranscriptionServiceHandle { commands, audio_busy: Arc::new(AtomicBool::new(false)), }; let admission = handle.admit_audio().expect("the slot starts free"); let canceled = Arc::new(AtomicBool::new(true)); // A rendezvous channel: the worker's send returns only once this test // receives, so a send before the admission drops would keep the slot // busy here for as long as this test waits. let (response, result) = mpsc::sync_channel(0); handle .submit(Command::Transcribe { selection: TranscriptionSelection::default(), clip: AudioClip { samples: vec![0.0; 16], duration_ms: 1, }, timings: TimestampLevel::None, admission, canceled: canceled.clone(), response, }) .unwrap(); let worker = thread::spawn(move || run(receiver)); let job = TranscriptionJob { canceled, result }; let deadline = Instant::now() + Duration::from_secs(2); let next = loop { if let Some(next) = handle.admit_audio() { break next; } assert!( Instant::now() < deadline, "the client can admit its next clip before the result arrives" ); thread::sleep(Duration::from_millis(1)); }; drop(next); let outcome = job .wait_timeout(Duration::from_secs(10)) .expect("the worker answers") .expect("the job returns a result"); assert!(matches!(outcome, Err(TranscriptionServiceError::Cancelled))); assert!( handle.admit_audio().is_some(), "the client can admit its next clip the moment the result arrives" ); drop(handle); worker.join().unwrap(); } #[test] fn dropping_a_pending_job_requests_cancellation() { let canceled = Arc::new(AtomicBool::new(false)); let (_sender, result) = mpsc::sync_channel(1); let job = TranscriptionJob { canceled: canceled.clone(), result, }; drop(job); assert!(canceled.load(Ordering::Acquire)); } fn wav_bytes(spec: WavSpec) -> Vec { let mut wav = Cursor::new(Vec::new()); { let mut writer = WavWriter::new(&mut wav, spec).unwrap(); writer.write_sample(0_i16).unwrap(); writer.finalize().unwrap(); } wav.into_inner() } }