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.
This commit is contained in:
BlackAngelTV committed 2026-10-06 20:24:03 +02:00
1 parent 9808b38198
commit 15dadb3afb
3 files changed
+331 -26

No files matched your search

+174 -10
View File
@@ -34,12 +34,26 @@ impl std::fmt::Display for AudioError {
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 {
@@ -67,19 +81,102 @@ impl Recorder {
stream,
sink,
sample_rate,
read: 0,
})
}
/// Stops the capture and returns the recorded mono samples and their rate.
pub fn stop(self) -> (Vec<f32>, u32) {
drop(self.stream);
let samples = self
.sink
.lock()
.map(|guard| guard.clone())
.unwrap_or_default();
(samples, self.sample_rate)
/// 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.
@@ -282,7 +379,74 @@ fn fill_from_source<T>(
#[cfg(test)]
mod tests {
use super::resample_linear;
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() {
+27 -3
View File
@@ -62,6 +62,10 @@ fn is_file(path: &Path) -> bool {
/// Result of a voice job, delivered back to the GUI thread.
#[derive(Debug, Clone)]
pub enum VoiceEvent {
/// A piece of audio transcribed while the capture is still running. The UI
/// shows it as it arrives; it is not the question yet.
TranscribedPart(String),
/// The capture ended: this is the complete transcript of what was said.
Transcribed(String),
/// Playback of a synthesized answer finished.
Spoken,
@@ -70,7 +74,13 @@ pub enum VoiceEvent {
}
enum VoiceCommand {
Transcribe { samples: Vec<f32>, sample_rate: u32 },
Transcribe {
samples: Vec<f32>,
sample_rate: u32,
/// Whether this closes the capture: the last piece decides which event
/// the app receives.
final_chunk: bool,
},
Speak { text: String },
}
@@ -91,11 +101,23 @@ impl VoiceHandle {
self.tts_ready
}
/// Queues a transcription job (safe to call from the GUI thread).
/// Queues a transcription of the whole capture; the result is the question.
pub fn transcribe(&self, samples: Vec<f32>, sample_rate: u32) {
self.send_transcription(samples, sample_rate, true);
}
/// Queues a transcription of a piece of the capture. Pieces are inferred in
/// the order they are queued, so the app can start on the beginning of a
/// sentence while the end is still being spoken.
pub fn transcribe_part(&self, samples: Vec<f32>, sample_rate: u32) {
self.send_transcription(samples, sample_rate, false);
}
fn send_transcription(&self, samples: Vec<f32>, sample_rate: u32, final_chunk: bool) {
let _ = self.tx.send(VoiceCommand::Transcribe {
samples,
sample_rate,
final_chunk,
});
}
@@ -126,6 +148,7 @@ where
VoiceCommand::Transcribe {
samples,
sample_rate,
final_chunk,
} => {
let Some(model) = worker_config.whisper_model.as_deref() else {
on_event(VoiceEvent::TranscriptionError(
@@ -147,7 +170,8 @@ where
.expect("stt initialised above")
.transcribe(&samples, sample_rate, &worker_config.language)
{
Ok(text) => on_event(VoiceEvent::Transcribed(text)),
Ok(text) if final_chunk => on_event(VoiceEvent::Transcribed(text)),
Ok(text) => on_event(VoiceEvent::TranscribedPart(text)),
Err(error) => {
on_event(VoiceEvent::TranscriptionError(error.to_string()))
}