hex/src/transcription/service.rs
Dax 648ec4725a
labs: transcribe dropped audio files (#1798)
* labs: transcribe dropped audio files

Add Labs › Transcribe dropped audio (off by default) and its backend:
WAV and MP3 on every OS, M4A/AIFF/CAF on macOS through the meeting import
bridge, decoded in 30 s pieces, transcribed in-process with the selected
model, and written as <stem>.txt beside the file with a Downloads fallback,
collision numbering, atomic writes, cancellation, and progress. Move the
shared pieces reader out of the transcribe CLI so both use it.

The window's drop target lands in a later change.

* labs: drop audio files on the window to save a transcript

The window root takes files with the extensions this build reads while
Labs › Transcribe dropped audio is on: a file drag shows "Drop to save a
transcript" over the window, a drag Hex can't read says what it reads, and
a drop queues one job per file behind the one running, all at the dictation
model and language in use. A worker transcribes each file and the toast
shows its name, a progress ring and percentage, how many wait behind it,
and Cancel; a saved file shows its name, the whole path, and Show in folder
(meeting::reveal), and a failure shows the backend's own words. The lab's
card offers Transcribe a file…, which opens the same queue's native file
dialog, for Wayland, where nothing can be dropped.

file_transcript exposes its extension table for the drop filter and dialog,
and finds every format from that one list. New goldens cover the hint and
the transcribing toast, and the drop-transcribe card now leads with a wave.

* meeting: use the renamed bridge in the import test

* transcription: find a temp folder through a symlinked path

* transcription: finish the audio file drop's review fixes

A drop right after Cancel (or the lab turned off and on) started a second
worker and a second transcription service while the first was still loading
or running. The running job now stays tracked as cancelling, its toast says
Cancelling… with no Cancel, and the next queued file starts only when its
worker reports Done or its channel closes. A cancel before the save also
stops a cancelled file from writing a transcript.

Also: validate a WAV whole before a model loads, report an unknown MP3 length
as indeterminate progress, map a bridge decode failure to Unreadable, keep a
writable source folder's transcript beside it without Downloads, name this
build's formats in the Labs card, use the kit's 16 pt toast lead, route Show
in folder through the host, derive the Audio folder through app_paths, and
correct the stale comments and feature map.

* transcription: read dropped files through the shared pieces reader

The rebased tree already decodes every container through Pieces, so the
dropped-file backend now opens, validates and reads one Pieces instance
instead of its own WAV, rodio MP3 and macOS bridge readers. Progress comes
from the reader's position and duration, and a compressed file with no
header duration reports no fraction. The retired Labs › Expire meeting audio
gate and the removed Transcribe files lab leave the tree too.

* labs: refresh the goldens for the dropped audio card

The card's row and the drop hint and toast change the Labs images and the
two drop scenes; only those eight goldens changed.

* labs: finish the dropped audio card's translations and goldens

The string tables already translate Audio files and Transcription stopped,
so the lab reuses them; the card's English line gains translations, the
website catalog lists the lab, and the what's new goldens show it.

* labs: offer every audio format the shared reader decodes

the dropped audio lab offered wav and mp3 everywhere, and the old macOS decoder's extras only on macOS, though every OS reads through the shared pieces reader. it now offers one list: wav, mp3, m4a, mp4, aiff/aif, caf, flac, ogg/oga/opus, webm, and mkv. every copy, translation, and golden names it, and a fixture proves the reader takes each one. also names the codec or missing track on a failure, keeps a late cancel's saved toast, and waits for a cancelled worker before the next file.

* labs: offer raw AAC and MOV files too

* labs: offer the reader's other common extensions

the shared pieces reader detects formats by content, so m4b, m4v, 3gp,
aifc, mka, weba, and wave decode too. the extension list is now described
as the common names it offers rather than an exhaustive set, empty files
and unreadable wavs say why, and a lab-off poll drains the worker's
channel instead of reading one event.

* transcription: free the audio slot before a result is sent

A long file is transcribed one piece after another, and each piece admits
the slot as soon as the previous result arrives. The worker released the
slot only after sending that result, so the next admit could see it busy
and fail mid-file with "Another transcription is running".

Also fixes the codec refusal's grammar and two stale comments.

* transcription: say where a damaged file stopped

a compressed file that stops decoding partway now says where it stopped
("talk.m4a is damaged at 12:34") instead of only that it is corrupt; a wav
refused up front keeps the old words. the slot-order test uses a rendezvous
response channel and waits for the slot to read free before receiving, so
sending before the admission drops fails every time instead of occasionally.
a locked drop-transcribe card keeps the lock's words instead of replacing
them with its formats line.
2026-11-18 20:49:59 -05:00

806 lines
27 KiB
Rust

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::<f32>();
/// 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<SyncSender<Command>>,
worker: Option<JoinHandle<()>>,
}
#[derive(Clone)]
pub struct TranscriptionServiceHandle {
commands: SyncSender<Command>,
audio_busy: Arc<AtomicBool>,
}
#[derive(Debug)]
pub struct AudioClip {
/// The 16 kHz mono samples every transcriber runs.
pub(crate) samples: Vec<f32>,
pub duration_ms: u64,
}
pub struct TranscriptionJob {
canceled: Arc<AtomicBool>,
result: Receiver<std::result::Result<Transcript, TranscriptionServiceError>>,
}
pub struct AudioAdmission(Arc<AtomicBool>);
#[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<WavFormat, AudioError> {
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<AtomicBool>,
response: SyncSender<std::result::Result<(), TranscriptionServiceError>>,
},
Transcribe {
selection: TranscriptionSelection,
clip: AudioClip,
timings: TimestampLevel,
admission: AudioAdmission,
canceled: Arc<AtomicBool>,
response: SyncSender<std::result::Result<Transcript, TranscriptionServiceError>>,
},
}
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<AudioAdmission> {
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<AtomicBool>,
) -> 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<TranscriptionJob, TranscriptionServiceError> {
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<std::result::Result<Transcript, TranscriptionServiceError>>,
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<R: Read + Seek>(reader: R) -> std::result::Result<Self, AudioError> {
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<R, S, F>(
reader: &mut WavReader<R>,
channels: usize,
frames: usize,
convert: F,
) -> std::result::Result<Vec<f32>, 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::<S>();
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<Command>) {
#[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<AtomicBool>,
) -> 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<AtomicBool>,
) -> 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<R: Send + 'static>(
selection: &TranscriptionSelection,
canceled: &Arc<AtomicBool>,
wait: Duration,
work: impl FnOnce(&mut HeldModel) -> R + Send + Clone + 'static,
) -> std::result::Result<Option<R>, TranscriptionServiceError> {
enum Shared<R> {
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<AtomicBool>,
timings: TimestampLevel,
) -> std::result::Result<Transcript, TranscriptionServiceError> {
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<f32>,
timings: TimestampLevel,
) -> std::result::Result<Transcript, TranscriptionServiceError> {
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<u8> {
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()
}
}