capri-voice: add player module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent 89404d1294
commit 49000487e2
1 file changed
+314
+314
View File
@@ -0,0 +1,314 @@
//! Sequential reply playback through rodio, level meter and mouth shapes (Capri `voice-player.mjs`, `avatar-mouth.mjs`).
use std::collections::VecDeque;
use std::num::NonZero;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use parking_lot::Mutex;
pub const RATE: u32 = 24_000;
const BLOCK: usize = 256; // Capri's analyser window
/// Synthesized audio for one sentence (24 kHz mono, effects already applied). Empty `text` = effects tail.
#[derive(Clone, Debug)]
pub struct Chunk {
pub turn_id: String,
pub sequence: u32,
pub text: String,
pub pcm: Vec<f32>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum PlaybackEvent {
Started { turn_id: String, sequence: u32, text: String, duration_ms: u64 },
Ended { turn_id: String, sequence: u32 },
Stopped,
/// Queue drained: nothing left to play.
Idle,
}
#[derive(Default)]
struct State {
queue: VecDeque<Chunk>,
current: Option<(Chunk, usize)>,
events: Vec<PlaybackEvent>,
busy: bool,
}
/// Shared playback queue; cheap to clone. The audio thread pulls from it in 256-sample blocks.
#[derive(Clone, Default)]
pub struct Playback {
state: Arc<Mutex<State>>,
level: Arc<AtomicU32>,
/// Last time audio was audible, for own-speech suppression in music capture.
pub last_audible: Arc<Mutex<Option<Instant>>>,
}
impl Playback {
pub fn push(&self, chunk: Chunk) {
let mut s = self.state.lock();
if s.queue.len() < 100 {
s.queue.push_back(chunk);
s.busy = true;
}
}
/// Immediate stop: clears the queue and the current chunk.
pub fn stop(&self) {
let mut s = self.state.lock();
let was = s.busy || s.current.is_some();
s.queue.clear();
s.current = None;
s.busy = false;
if was {
s.events.push(PlaybackEvent::Stopped);
}
self.level.store(0, Ordering::Relaxed);
}
pub fn busy(&self) -> bool {
self.state.lock().busy
}
/// RMS of the last 256 output samples; 0 when silent.
pub fn level(&self) -> f32 {
f32::from_bits(self.level.load(Ordering::Relaxed))
}
pub fn take_events(&self) -> Vec<PlaybackEvent> {
std::mem::take(&mut self.state.lock().events)
}
/// Fills one block, emitting chunk start/end events.
fn fill(&self, out: &mut [f32]) {
let mut s = self.state.lock();
let mut i = 0;
while i < out.len() {
if s.current.is_none() {
let Some(chunk) = s.queue.pop_front() else { break };
if !chunk.text.is_empty() {
let duration_ms = chunk.pcm.len() as u64 * 1000 / RATE as u64;
s.events.push(PlaybackEvent::Started { turn_id: chunk.turn_id.clone(), sequence: chunk.sequence, text: chunk.text.clone(), duration_ms });
}
s.current = Some((chunk, 0));
}
let (chunk, pos) = s.current.as_mut().unwrap();
let n = (chunk.pcm.len() - *pos).min(out.len() - i);
out[i..i + n].copy_from_slice(&chunk.pcm[*pos..*pos + n]);
*pos += n;
i += n;
if *pos == chunk.pcm.len() {
let (chunk, _) = s.current.take().unwrap();
if !chunk.text.is_empty() {
s.events.push(PlaybackEvent::Ended { turn_id: chunk.turn_id, sequence: chunk.sequence });
}
}
}
out[i..].fill(0.0);
if s.busy && s.current.is_none() && s.queue.is_empty() {
s.busy = false;
s.events.push(PlaybackEvent::Idle);
}
drop(s);
let rms = (out.iter().map(|x| x * x).sum::<f32>() / out.len() as f32).sqrt();
self.level.store(rms.to_bits(), Ordering::Relaxed);
if rms > 0.001 {
*self.last_audible.lock() = Some(Instant::now());
}
}
pub fn source(&self) -> PlaybackSource {
PlaybackSource { playback: self.clone(), block: [0.0; BLOCK], index: BLOCK }
}
}
/// Endless mono 24 kHz source: silence when nothing is queued.
pub struct PlaybackSource {
playback: Playback,
block: [f32; BLOCK],
index: usize,
}
impl Iterator for PlaybackSource {
type Item = f32;
fn next(&mut self) -> Option<f32> {
if self.index == BLOCK {
self.playback.fill(&mut self.block);
self.index = 0;
}
self.index += 1;
Some(self.block[self.index - 1])
}
}
impl rodio::Source for PlaybackSource {
fn current_span_len(&self) -> Option<usize> {
None
}
fn channels(&self) -> rodio::ChannelCount {
NonZero::new(1).unwrap()
}
fn sample_rate(&self) -> rodio::SampleRate {
NonZero::new(RATE).unwrap()
}
fn total_duration(&self) -> Option<Duration> {
None
}
}
/// The default output device, held by its own thread (cpal streams are not `Send`). Dropping it closes the device.
pub struct Speaker {
stop: Arc<AtomicBool>,
}
impl Speaker {
pub fn open(playback: &Playback) -> Result<Self> {
let stop = Arc::new(AtomicBool::new(false));
let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
let source = playback.source();
let flag = stop.clone();
std::thread::Builder::new().name("capri-speaker".into()).spawn(move || {
let sink = match rodio::DeviceSinkBuilder::open_default_sink() {
Ok(mut sink) => {
sink.log_on_drop(false);
sink
}
Err(e) => {
let _ = ready_tx.send(Err(anyhow::anyhow!("{e}")));
return;
}
};
sink.mixer().add(source);
let _ = ready_tx.send(Ok(()));
while !flag.load(Ordering::Relaxed) {
std::thread::park_timeout(Duration::from_millis(200));
}
})?;
ready_rx.recv().context("Audio output thread failed")??;
Ok(Self { stop })
}
}
impl Drop for Speaker {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
}
}
/// Mouth layers driven by playback amplitude.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Mouth {
#[default]
Closed,
Small,
Round,
Wide,
}
#[derive(Default)]
pub struct MouthSampler {
at: Option<Instant>,
level: f32,
shape: Mouth,
}
impl MouthSampler {
pub fn sample(&mut self, now: Instant, speaking: bool, amplitude: f32) -> Mouth {
if !speaking || !amplitude.is_finite() || amplitude < 0.006 {
(self.at, self.level, self.shape) = (None, 0.0, Mouth::Closed);
return self.shape;
}
if self.at.is_some_and(|at| now.duration_since(at) < Duration::from_millis(90)) {
return self.shape;
}
self.at = Some(now);
self.level = self.level * 0.25 + amplitude * 0.75;
self.shape = if self.level > if self.shape == Mouth::Wide { 0.055 } else { 0.075 } {
Mouth::Wide
} else if self.level > if self.shape == Mouth::Round { 0.022 } else { 0.03 } {
Mouth::Round
} else {
Mouth::Small
};
self.shape
}
}
/// Capri's default wake tone: 740 Hz then 1110 Hz partials gliding up 8 %, at 24 kHz.
pub fn wake_tone(volume: f32) -> Vec<f32> {
let gain = 0.085 * volume.clamp(0.0, 1.0);
let mut out = vec![0.0f32; (0.24 * RATE as f32) as usize];
for (start, freq, length) in [(0.006f32, 740.0f32, 0.115f32), (0.091, 1110.0, 0.140)] {
let mut phase = 0.0f32;
let n = (length * RATE as f32) as usize;
for i in 0..n {
let t = i as f32 / RATE as f32;
let f = freq * 1.08f32.powf(t / length);
phase += f / RATE as f32;
let envelope = if t < 0.008 { t / 0.008 } else { 0.001f32.powf((t - 0.008) / (length - 0.008)) };
if let Some(slot) = out.get_mut((start * RATE as f32) as usize + i) {
*slot += gain * envelope * (std::f32::consts::TAU * phase).sin();
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn chunk(sequence: u32, text: &str, samples: usize) -> Chunk {
Chunk { turn_id: "t".into(), sequence, text: text.into(), pcm: vec![0.5; samples] }
}
#[test]
fn plays_in_order_with_events_and_level() {
let playback = Playback::default();
playback.push(chunk(0, "One.", 300));
playback.push(chunk(0, "", 100)); // effects tail: no subtitle event
playback.push(chunk(1, "Two.", 24_000));
let mut source = playback.source();
let first: Vec<f32> = (&mut source).take(512).collect();
assert!(first[..400].iter().all(|x| *x == 0.5));
assert!((playback.level() - 0.5).abs() < 1e-6);
assert_eq!(
playback.take_events(),
vec![
PlaybackEvent::Started { turn_id: "t".into(), sequence: 0, text: "One.".into(), duration_ms: 12 },
PlaybackEvent::Ended { turn_id: "t".into(), sequence: 0 },
PlaybackEvent::Started { turn_id: "t".into(), sequence: 1, text: "Two.".into(), duration_ms: 1000 },
]
);
assert!(playback.busy());
playback.stop();
assert_eq!(playback.take_events(), vec![PlaybackEvent::Stopped]);
assert!(source.take(256).all(|x| x == 0.0));
assert_eq!(playback.level(), 0.0);
}
#[test]
fn drained_queue_reports_idle() {
let playback = Playback::default();
playback.push(chunk(0, "Hi.", 10));
let _: Vec<f32> = playback.source().take(256).collect();
assert_eq!(playback.take_events().last(), Some(&PlaybackEvent::Idle));
assert!(!playback.busy());
}
#[test]
fn mouth_follows_amplitude_with_hysteresis() {
let t = Instant::now();
let mut m = MouthSampler::default();
assert_eq!(m.sample(t, true, 0.2), Mouth::Wide);
assert_eq!(m.sample(t + Duration::from_millis(50), true, 0.0101), Mouth::Wide, "updates at most every 90 ms");
assert_eq!(m.sample(t + Duration::from_millis(100), true, 0.04), Mouth::Wide, "0.25*0.15+0.75*0.04 > 0.055");
assert_eq!(m.sample(t + Duration::from_millis(200), true, 0.01), Mouth::Small);
assert_eq!(m.sample(t + Duration::from_millis(300), false, 0.2), Mouth::Closed);
let tone = wake_tone(1.0);
assert!(tone.iter().all(|x| x.abs() <= 0.17) && tone.iter().any(|x| x.abs() > 0.05));
}
}