feat(frontend): add native Rust client with SSE chat and local voice
Keep speech-to-text and text-to-speech on the machine so only text travels to the backend while the backend still speaks JSON to Ollama.
This commit is contained in:
17 files changed
+8014
No files matched your search
@@ -0,0 +1,311 @@
|
||||
//! 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 {}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::resample_linear;
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user