Files
Jarvise-project/frontend/src/voice/audio.rs
T
BlackAngelTV 15dadb3afb feat(frontend): transcribe the microphone while the user is still speaking
Waiting for the release before starting reduced the whole cost to the moment it
is most visible: the Whisper model load and the inference over the entire
recording landed together after the button press. The capture is now cut into
pieces as it arrives — inside a pause when there is one, so a word is never
split in two, and at four seconds at the latest — and each piece is queued to
the voice thread in order. By the time the user stops, only the tail is left to
transcribe; a tail too short to hold a word is not even sent. The model load
happens during the first sentence instead of after it, the recognised text
appears live as it is spoken, and the pieces are joined back into one question.
2026-10-06 20:24:03 +02:00

476 lines
15 KiB
Rust

//! Audio input (microphone) and output (speaker) through `cpal`.
//!
//! Callbacks run on the audio thread and only push/pull samples to/from a shared
//! buffer, so nothing here blocks for long.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{FromSample, Sample, SampleFormat, SizedSample, StreamConfig};
/// Anything that can go wrong when opening or using an audio device.
#[derive(Debug)]
pub enum AudioError {
NoInputDevice,
NoOutputDevice,
Config(String),
Build(String),
Play(String),
}
impl std::fmt::Display for AudioError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AudioError::NoInputDevice => write!(f, "aucun micro détecté"),
AudioError::NoOutputDevice => write!(f, "aucun haut-parleur détecté"),
AudioError::Config(message) => write!(f, "configuration audio : {message}"),
AudioError::Build(message) => write!(f, "ouverture du flux audio : {message}"),
AudioError::Play(message) => write!(f, "lecture audio : {message}"),
}
}
}
impl std::error::Error for AudioError {}
/// Length of the quiet windows [`chunk_cut`] looks for, in milliseconds.
const SILENCE_WINDOW_MS: usize = 30;
/// RMS below which such a window counts as a pause between two words.
const SILENCE_RMS: f32 = 0.012;
/// Shortest piece worth transcribing: below that, Whisper has too little
/// context and starts inventing words.
pub const MIN_CHUNK_SECONDS: f32 = 1.2;
/// Longest piece sent without waiting for a pause, so the transcription never
/// trails far behind a speaker who does not breathe.
pub const MAX_CHUNK_SECONDS: f32 = 4.0;
/// An active microphone recording. Drop it (via [`Recorder::stop`]) to end the
/// capture; the samples are mono `f32` at [`Recorder::sample_rate`].
pub struct Recorder {
stream: cpal::Stream,
sink: Arc<Mutex<Vec<f32>>>,
sample_rate: u32,
/// How many samples were already handed out, so a long recording can be
/// transcribed piece by piece while it is still being made.
read: usize,
}
impl Recorder {
/// Opens the default microphone and starts capturing.
pub fn start() -> Result<Self, AudioError> {
let host = cpal::default_host();
let device = host
.default_input_device()
.ok_or(AudioError::NoInputDevice)?;
let supported = device
.default_input_config()
.map_err(|error| AudioError::Config(error.to_string()))?;
let sample_rate = supported.sample_rate();
let format = supported.sample_format();
let config = supported.config();
let sink = Arc::new(Mutex::new(Vec::new()));
let stream = build_input(&device, config, format, sink.clone())?;
stream
.play()
.map_err(|error| AudioError::Play(error.to_string()))?;
Ok(Self {
stream,
sink,
sample_rate,
read: 0,
})
}
/// Rate of the captured samples.
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
/// Takes everything recorded since the previous call, and forgets it here:
/// the caller owns those samples from now on. Lets the app transcribe the
/// beginning of a sentence while the end is still being spoken.
pub fn drain_pending(&mut self) -> Vec<f32> {
take_since(&self.sink, &mut self.read)
}
/// Stops the capture and returns the mono samples recorded since the last
/// [`Self::drain_pending`], with their rate.
pub fn stop(mut self) -> (Vec<f32>, u32) {
// Closing the stream first guarantees no sample is appended after the
// final drain.
drop(self.stream);
let remaining = take_since(&self.sink, &mut self.read);
(remaining, self.sample_rate)
}
}
/// Copies the samples written after `read`, then moves the cursor to the end.
fn take_since(sink: &Mutex<Vec<f32>>, read: &mut usize) -> Vec<f32> {
let Ok(guard) = sink.lock() else {
return Vec::new();
};
if *read >= guard.len() {
return Vec::new();
}
let pending = guard[*read..].to_vec();
*read = guard.len();
pending
}
/// Root-mean-square level of a window, the cheap way to tell a pause from
/// speech.
pub fn rms(samples: &[f32]) -> f32 {
if samples.is_empty() {
return 0.0;
}
let sum: f32 = samples.iter().map(|sample| sample * sample).sum();
(sum / samples.len() as f32).sqrt()
}
/// End of the last pause in `samples`, if the buffer holds one.
///
/// Cutting in a pause is what keeps a word whole: a cut in the middle of \"bonjour\"
/// gives one chunk with \"bon\" and the next with \"jour\", and Whisper can only
/// guess at either.
fn last_silence(samples: &[f32], rate: usize) -> Option<usize> {
let window = (SILENCE_WINDOW_MS * rate / 1000).max(1);
if samples.len() < 2 * window {
return None;
}
let step = (window / 3).max(1);
let mut start = samples.len() - window;
loop {
if rms(&samples[start..start + window]) < SILENCE_RMS {
// The pause stays in the chunk: it costs nothing and keeps the
// trailing word complete.
return Some(start + window);
}
if start < step {
return None;
}
start -= step;
}
}
/// Where to cut the live capture so it can be transcribed, or `None` to keep
/// collecting.
///
/// A pause is preferred, but a long uninterrupted stretch is cut anyway: the
/// words may suffer at the seam, waiting would cost more.
pub fn chunk_cut(samples: &[f32], rate: u32) -> Option<usize> {
let rate = rate.max(1) as usize;
let minimum = (MIN_CHUNK_SECONDS * rate as f32) as usize;
if samples.len() < minimum {
return None;
}
if let Some(cut) = last_silence(samples, rate) {
if cut >= minimum {
return Some(cut);
}
}
let maximum = (MAX_CHUNK_SECONDS * rate as f32) as usize;
(samples.len() >= maximum).then_some(samples.len())
}
/// Plays `samples` (mono `f32`) at `sample_rate`, blocking until playback ends.
///
/// Callers run this on a background thread (the voice engine), never on the GUI
/// thread.
pub fn play_blocking(samples: &[f32], sample_rate: u32) -> Result<(), AudioError> {
if samples.is_empty() {
return Ok(());
}
let host = cpal::default_host();
let device = host
.default_output_device()
.ok_or(AudioError::NoOutputDevice)?;
let supported = device
.default_output_config()
.map_err(|error| AudioError::Config(error.to_string()))?;
let output_rate = supported.sample_rate();
let format = supported.sample_format();
let config = supported.config();
// Resample once so the callback is a simple copy.
let source = Arc::new(resample_linear(samples, sample_rate, output_rate));
let position = Arc::new(AtomicUsize::new(0));
let finished = Arc::new(AtomicBool::new(false));
let stream = build_output(
&device,
config,
format,
source,
position.clone(),
finished.clone(),
)?;
stream
.play()
.map_err(|error| AudioError::Play(error.to_string()))?;
while !finished.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(20));
}
// Give the device a moment to flush the last buffer.
std::thread::sleep(Duration::from_millis(80));
drop(stream);
Ok(())
}
/// Linear resampling between two sample rates (good enough for speech).
pub fn resample_linear(input: &[f32], source_rate: u32, target_rate: u32) -> Vec<f32> {
if input.is_empty() || source_rate == target_rate || source_rate == 0 {
return input.to_vec();
}
let ratio = source_rate as f64 / target_rate as f64;
let out_len = ((input.len() as f64) / ratio).max(1.0) as usize;
let last = input.len() - 1;
(0..out_len)
.map(|i| {
let src = i as f64 * ratio;
let index = src.floor() as usize;
let frac = (src - index as f64) as f32;
let a = input[index.min(last)];
let b = input[(index + 1).min(last)];
a + (b - a) * frac
})
.collect()
}
fn build_input(
device: &cpal::Device,
config: StreamConfig,
format: SampleFormat,
sink: Arc<Mutex<Vec<f32>>>,
) -> Result<cpal::Stream, AudioError> {
match format {
SampleFormat::F32 => input_stream::<f32>(device, config, sink),
SampleFormat::I16 => input_stream::<i16>(device, config, sink),
SampleFormat::U16 => input_stream::<u16>(device, config, sink),
SampleFormat::I32 => input_stream::<i32>(device, config, sink),
other => Err(AudioError::Config(format!(
"format d'entrée non pris en charge : {other:?}"
))),
}
}
fn input_stream<T>(
device: &cpal::Device,
config: StreamConfig,
sink: Arc<Mutex<Vec<f32>>>,
) -> Result<cpal::Stream, AudioError>
where
T: SizedSample + 'static,
f32: FromSample<T>,
{
let channels = config.channels as usize;
device
.build_input_stream::<T, _, _>(
config,
move |data, _| push_mono::<T>(data, channels, &sink),
|_error| {},
None,
)
.map_err(|error| AudioError::Build(error.to_string()))
}
fn push_mono<T>(data: &[T], channels: usize, sink: &Arc<Mutex<Vec<f32>>>)
where
T: Sample,
f32: FromSample<T>,
{
if channels == 0 {
return;
}
let mut out = match sink.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
for frame in data.chunks(channels) {
let sum: f32 = frame.iter().map(|sample| sample.to_sample::<f32>()).sum();
out.push(sum / channels as f32);
}
}
fn build_output(
device: &cpal::Device,
config: StreamConfig,
format: SampleFormat,
source: Arc<Vec<f32>>,
position: Arc<AtomicUsize>,
finished: Arc<AtomicBool>,
) -> Result<cpal::Stream, AudioError> {
match format {
SampleFormat::F32 => output_stream::<f32>(device, config, source, position, finished),
SampleFormat::I16 => output_stream::<i16>(device, config, source, position, finished),
SampleFormat::U16 => output_stream::<u16>(device, config, source, position, finished),
SampleFormat::I32 => output_stream::<i32>(device, config, source, position, finished),
other => Err(AudioError::Config(format!(
"format de sortie non pris en charge : {other:?}"
))),
}
}
fn output_stream<T>(
device: &cpal::Device,
config: StreamConfig,
source: Arc<Vec<f32>>,
position: Arc<AtomicUsize>,
finished: Arc<AtomicBool>,
) -> Result<cpal::Stream, AudioError>
where
T: SizedSample + 'static,
T: FromSample<f32>,
{
let channels = config.channels as usize;
device
.build_output_stream::<T, _, _>(
config,
move |data, _| fill_from_source::<T>(data, channels, &source, &position, &finished),
|_error| {},
None,
)
.map_err(|error| AudioError::Build(error.to_string()))
}
fn fill_from_source<T>(
output: &mut [T],
channels: usize,
source: &Arc<Vec<f32>>,
position: &Arc<AtomicUsize>,
finished: &Arc<AtomicBool>,
) where
T: Sample,
T: FromSample<f32>,
{
if channels == 0 {
return;
}
let len = source.len();
let mut index = position.load(Ordering::Relaxed);
for frame in output.chunks_mut(channels) {
let value = if index < len { source[index] } else { 0.0 };
let sample = T::from_sample(value);
for out in frame.iter_mut() {
*out = sample;
}
if index < len {
index += 1;
}
}
position.store(index, Ordering::Relaxed);
if index >= len {
finished.store(true, Ordering::SeqCst);
}
}
#[cfg(test)]
mod tests {
use super::{chunk_cut, resample_linear, MAX_CHUNK_SECONDS, MIN_CHUNK_SECONDS};
const RATE: u32 = 16_000;
/// A second of loud voice, then half a second of silence.
fn speech_then_pause() -> Vec<f32> {
let mut samples = vec![0.3_f32; RATE as usize];
samples.extend(std::iter::repeat_n(0.0, RATE as usize / 2));
samples
}
#[test]
fn a_short_buffer_is_not_cut() {
let samples = vec![0.3_f32; (RATE as f32 * 0.5) as usize];
assert_eq!(chunk_cut(&samples, RATE), None);
}
#[test]
fn a_pause_is_the_preferred_cut() {
let samples = speech_then_pause();
let cut = chunk_cut(&samples, RATE).expect("a pause after 1.2 s is cuttable");
assert_eq!(cut, samples.len(), "the whole pause is kept in the chunk");
assert!(cut as f32 / RATE as f32 <= MAX_CHUNK_SECONDS);
}
#[test]
fn a_word_is_never_split_when_a_pause_exists() {
// Two seconds of speech, a pause, then the start of the next sentence.
let mut samples = vec![0.4_f32; 2 * RATE as usize];
samples.extend(std::iter::repeat_n(0.0, RATE as usize / 3));
let after_pause = samples.len();
samples.extend(vec![0.4_f32; RATE as usize / 4]);
let cut = chunk_cut(&samples, RATE).expect("the pause must be found");
// The cut lands inside the pause, never in the words around it.
assert!(
(2 * RATE as usize..=after_pause).contains(&cut),
"cut at {cut}, the pause ended at {after_pause}"
);
}
#[test]
fn continuous_speech_is_cut_at_the_hard_limit() {
let samples = vec![0.3_f32; (RATE as f32 * (MAX_CHUNK_SECONDS + 0.5)) as usize];
let cut = chunk_cut(&samples, RATE).expect("a long stretch must be cut");
assert_eq!(cut, samples.len());
assert!((cut as f32 / RATE as f32) >= MAX_CHUNK_SECONDS);
}
#[test]
fn a_pause_that_is_too_early_is_ignored() {
// Silence almost immediately: cutting there would send a sliver with
// nothing in it, so the buffer keeps growing.
let mut samples = vec![0.0_f32; RATE as usize / 10];
samples.extend(std::iter::repeat_n(0.4, (RATE as f32 * 0.6) as usize));
assert!(MIN_CHUNK_SECONDS > 0.6);
assert_eq!(chunk_cut(&samples, RATE), None);
}
#[test]
fn silence_is_cut_at_the_shorter_threshold() {
// A gap right after the minimum: no need to wait for the hard limit.
let samples = vec![0.0_f32; (RATE as f32 * MIN_CHUNK_SECONDS) as usize];
assert_eq!(chunk_cut(&samples, RATE), Some(samples.len()));
}
#[test]
fn resample_is_identity_at_the_same_rate() {
let input = vec![0.1, -0.2, 0.3];
assert_eq!(resample_linear(&input, 16_000, 16_000), input);
}
#[test]
fn resample_downsamples_to_the_expected_length() {
let input: Vec<f32> = (0..48_000).map(|i| (i as f32 / 48_000.0).sin()).collect();
let output = resample_linear(&input, 48_000, 16_000);
assert_eq!(output.len(), 16_000);
}
#[test]
fn resample_preserves_constant_signal() {
let input = vec![0.5_f32; 44_100];
let output = resample_linear(&input, 44_100, 16_000);
assert!(output.iter().all(|sample| (sample - 0.5).abs() < 1e-3));
}
#[test]
fn resample_handles_empty_input() {
assert!(resample_linear(&[], 44_100, 16_000).is_empty());
}
}