voxcpm-cli 0.2.0

Unified Apple Silicon MLX CLI, Studio WebUI, and HTTP streaming TTS server (`voxcpm`) for VoxCPM2.
//! Real-time streaming CoreAudio playback via `cpal`.

use std::{
    collections::VecDeque,
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use anyhow::{Context, Result, anyhow};
use cpal::{
    FromSample, SizedSample, Stream,
    traits::{DeviceTrait, HostTrait, StreamTrait},
};
use voxcpm_rs_core::audio::resample_mono;

/// Streaming audio player that accepts 48 kHz mono `f32` chunks and plays them
/// on the default system output device with automatic channel & sample-rate adaptation.
pub struct StreamingPlayer {
    _stream: Stream,
    queue: Arc<Mutex<VecDeque<f32>>>,
    finished: Arc<AtomicBool>,
    source_sr: u32,
    device_sr: u32,
}

impl StreamingPlayer {
    /// Open the default audio output stream ready to play chunks arriving at `source_sr`.
    pub fn open(source_sr: u32) -> Result<Self> {
        let host = cpal::default_host();
        let device = host
            .default_output_device()
            .ok_or_else(|| anyhow!("no default audio output device found"))?;
        let supported = device
            .default_output_config()
            .context("failed to query default audio output config")?;

        let device_sr = supported.sample_rate();
        let channels = usize::from(supported.channels());
        let queue: Arc<Mutex<VecDeque<f32>>> =
            Arc::new(Mutex::new(VecDeque::with_capacity(96_000)));
        let finished = Arc::new(AtomicBool::new(false));

        let err_fn = |err: cpal::Error| {
            tracing::warn!(error = %err, "audio playback stream error");
        };

        let stream_config: cpal::StreamConfig = supported.into();
        let stream = match supported.sample_format() {
            cpal::SampleFormat::F32 => {
                build_stream::<f32>(&device, stream_config, channels, Arc::clone(&queue), err_fn)?
            }
            cpal::SampleFormat::I16 => {
                build_stream::<i16>(&device, stream_config, channels, Arc::clone(&queue), err_fn)?
            }
            cpal::SampleFormat::U16 => {
                build_stream::<u16>(&device, stream_config, channels, Arc::clone(&queue), err_fn)?
            }
            fmt => {
                return Err(anyhow!("unsupported output sample format: {fmt:?}"));
            }
        };

        stream
            .play()
            .context("failed to start audio playback stream")?;

        Ok(Self {
            _stream: stream,
            queue,
            finished,
            source_sr,
            device_sr,
        })
    }

    /// Enqueue a chunk of mono `f32` PCM samples at `source_sr` for immediate playback.
    pub fn push(&self, samples: &[f32]) -> Result<()> {
        if samples.is_empty() {
            return Ok(());
        }
        let adapted = if self.device_sr != self.source_sr {
            resample_mono(samples, self.source_sr, self.device_sr)
                .context("failed to resample audio chunk for output device")?
        } else {
            samples.to_vec()
        };

        let mut guard = self
            .queue
            .lock()
            .map_err(|_| anyhow!("audio playback queue lock poisoned"))?;
        guard.extend(adapted);
        Ok(())
    }

    /// Block asynchronously until all queued audio has drained through the output hardware.
    pub async fn drain(&self) {
        self.finished.store(true, Ordering::SeqCst);
        loop {
            let remaining = self.queue.lock().map(|q| q.len()).unwrap_or(0);
            if remaining == 0 {
                // Allow one final hardware buffer period (~60 ms) to finish playing out.
                tokio::time::sleep(Duration::from_millis(60)).await;
                break;
            }
            tokio::time::sleep(Duration::from_millis(15)).await;
        }
    }
}

fn build_stream<T>(
    device: &cpal::Device,
    config: cpal::StreamConfig,
    channels: usize,
    queue: Arc<Mutex<VecDeque<f32>>>,
    err_fn: impl FnMut(cpal::Error) + Send + 'static,
) -> Result<Stream>
where
    T: SizedSample + FromSample<f32>,
{
    device
        .build_output_stream(
            config,
            move |output: &mut [T], _| {
                if let Ok(mut guard) = queue.lock() {
                    for frame in output.chunks_mut(channels) {
                        let sample = guard.pop_front().unwrap_or(0.0);
                        let converted = T::from_sample(sample.clamp(-1.0, 1.0));
                        for ch in frame.iter_mut() {
                            *ch = converted;
                        }
                    }
                } else {
                    for sample in output.iter_mut() {
                        *sample = T::EQUILIBRIUM;
                    }
                }
            },
            err_fn,
            None,
        )
        .context("failed to build audio output stream")
}