mod playback;
use std::{
io::{self, Read, Write},
path::PathBuf,
};
use anyhow::{Context, Result, bail};
use clap::{Args, Parser, Subcommand};
use tracing_subscriber::EnvFilter;
use voxcpm_rs_core::{
BUILTIN_PRESETS, DEFAULT_MODEL_REPO, DEFAULT_QUEUE_CAPACITY, InferenceEngine, SaveVoiceInput,
StreamEvent, SynthesisRequest, VERSION, VoiceName, VoicePrompt, VoiceStore,
audio::write_wav_pcm16, expand_model_shorthand, resolve_model_files,
};
#[derive(Debug, Parser)]
#[command(
name = "voxcpm",
version = VERSION,
about = "Apple Silicon MLX local TTS & voice cloning CLI for VoxCPM2"
)]
struct Cli {
#[arg(long, global = true, env = "VOXCPM_VOICES_DIR")]
voices_dir: Option<PathBuf>,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
#[command(alias = "synth")]
Speak(Box<SpeakArgs>),
Voice {
#[command(subcommand)]
action: VoiceAction,
},
Presets,
Download(DownloadArgs),
Info,
}
#[derive(Debug, Subcommand)]
enum VoiceAction {
List,
Save(VoiceSaveArgs),
Show {
name: String,
},
Delete {
name: String,
},
}
#[derive(Debug, Args)]
struct VoiceSaveArgs {
name: String,
#[arg(long, short = 'd')]
description: Option<String>,
#[arg(long, short = 'i')]
instruct: Option<String>,
#[arg(long)]
ref_audio: Option<PathBuf>,
#[arg(long)]
prompt_audio: Option<PathBuf>,
#[arg(long)]
prompt_text: Option<String>,
#[arg(long)]
no_trim_silence: bool,
}
#[derive(Debug, Args)]
struct SpeakArgs {
text: Option<String>,
#[arg(long, short = 'f')]
file: Option<PathBuf>,
#[arg(long, short = 'o')]
output: Option<PathBuf>,
#[arg(long, short = 'p')]
play: bool,
#[arg(long, short = 'm', default_value = DEFAULT_MODEL_REPO, env = "VOXCPM_MODEL")]
model: String,
#[arg(long, short = 'v')]
voice: Option<String>,
#[arg(long)]
preset: Option<String>,
#[arg(long, short = 'i')]
instruct: Option<String>,
#[arg(long)]
ref_audio: Option<PathBuf>,
#[arg(long)]
prompt_audio: Option<PathBuf>,
#[arg(long)]
prompt_text: Option<String>,
#[arg(long)]
no_trim_silence: bool,
#[arg(long, default_value_t = 10)]
steps: usize,
#[arg(long, default_value_t = 2.0)]
cfg: f32,
#[arg(long)]
no_cfg_zero_star: bool,
#[arg(long, short = 's', default_value_t = 1.0)]
speed: f32,
#[arg(long)]
no_preserve_pitch: bool,
#[arg(long, default_value_t = 0.0, allow_hyphen_values = true)]
pitch: f32,
#[arg(long, default_value_t = 1.0)]
temperature: f32,
#[arg(long, default_value_t = 2000)]
max_tokens: usize,
#[arg(long)]
seed: Option<u64>,
#[arg(long)]
stream: bool,
#[arg(long, default_value_t = 2)]
stream_chunk_patches: usize,
#[arg(long)]
no_chunk: bool,
#[arg(long, default_value_t = 180)]
chunk_max_units: usize,
}
#[derive(Debug, Args)]
struct DownloadArgs {
#[arg(default_value = DEFAULT_MODEL_REPO)]
model: String,
}
fn open_voice_store(custom_dir: Option<PathBuf>) -> Result<VoiceStore> {
let dir = custom_dir.unwrap_or_else(VoiceStore::default_dir);
VoiceStore::open(&dir).with_context(|| format!("failed to open voice store {}", dir.display()))
}
async fn read_input_text(args: &SpeakArgs) -> Result<String> {
if let Some(path) = &args.file {
return tokio::fs::read_to_string(path)
.await
.with_context(|| format!("failed to read text file {}", path.display()));
}
match args.text.as_deref() {
Some("-") => {
let mut buf = String::new();
io::stdin()
.read_to_string(&mut buf)
.context("failed to read text from stdin")?;
Ok(buf)
}
Some(t) => Ok(t.to_string()),
None => bail!("provide text as an argument, '-', or via --file <path>"),
}
}
fn build_voice_prompt(args: &SpeakArgs) -> Result<Option<VoicePrompt>> {
let trim = !args.no_trim_silence;
if args.ref_audio.is_none() && args.prompt_audio.is_none() {
return Ok(None);
}
if args.prompt_audio.is_some() && args.prompt_text.is_none() {
bail!("--prompt-text is required when --prompt-audio is specified");
}
let ref_audio = match &args.ref_audio {
Some(path) => Some(
voxcpm_rs_core::audio::read_wav_mono(path)
.with_context(|| format!("failed to read ref audio {}", path.display()))?,
),
None => None,
};
let prompt_audio = match &args.prompt_audio {
Some(path) => Some(
voxcpm_rs_core::audio::read_wav_mono(path)
.with_context(|| format!("failed to read prompt audio {}", path.display()))?,
),
None => None,
};
Ok(Some(VoicePrompt {
ref_audio,
prompt_audio,
prompt_text: args.prompt_text.clone(),
trim_silence_vad: trim,
}))
}
#[tokio::main]
async fn main() -> Result<()> {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("warn,voxcpm_rs_core=info,voxcpm=info"));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(false)
.with_writer(io::stderr)
.init();
let cli = Cli::parse();
match cli.command {
Command::Info => run_info(cli.voices_dir),
Command::Presets => run_presets(),
Command::Download(args) => run_download(args),
Command::Voice { action } => run_voice(cli.voices_dir, action).await,
Command::Speak(args) => run_speak(cli.voices_dir, *args).await,
}
}
fn run_info(voices_dir: Option<PathBuf>) -> Result<()> {
let voices_path = voices_dir.unwrap_or_else(VoiceStore::default_dir);
let mut out = io::stdout().lock();
writeln!(out, "voxcpm {VERSION} (Apple Silicon MLX Rust Engine)")?;
writeln!(out, "Default model : {DEFAULT_MODEL_REPO}")?;
writeln!(
out,
"Shorthands : 8bit (~3.2 GB) | 4bit (~2.3 GB) | bf16 (~4.6 GB)"
)?;
writeln!(out, "Output format : 48,000 Hz mono PCM (AudioVAE V2)")?;
writeln!(out, "Voice library : {}", voices_path.display())?;
writeln!(out, "Metal enabled : {}", cfg!(target_os = "macos"))?;
let active_mb = mlx_rs::memory::active_memory().unwrap_or(0) as f64 / (1024.0 * 1024.0);
writeln!(out, "MLX active mem: {active_mb:.2} MiB")?;
Ok(())
}
fn run_presets() -> Result<()> {
let mut out = io::stdout().lock();
writeln!(
out,
"{:<20} {:<15} {:<38} INSTRUCT",
"ID", "CATEGORY", "LABEL (EN / 中文)"
)?;
writeln!(out, "{}", "-".repeat(110))?;
for preset in BUILTIN_PRESETS {
writeln!(
out,
"{:<20} {:<15} {:<38} {}",
preset.id,
preset.category,
format!("{} / {}", preset.label, preset.label_zh),
preset.instruct
)?;
}
Ok(())
}
async fn run_voice(voices_dir: Option<PathBuf>, action: VoiceAction) -> Result<()> {
let store = open_voice_store(voices_dir)?;
match action {
VoiceAction::List => {
let profiles = store.list()?;
let mut out = io::stdout().lock();
if profiles.is_empty() {
writeln!(
out,
"No saved voices in {}. Use `voxcpm voice save <name> --ref-audio <wav>` to \
add one.",
store.root().display()
)?;
return Ok(());
}
writeln!(
out,
"{:<22} {:<8} {:<10} {:<6} DESCRIPTION / INSTRUCT",
"NAME", "REF", "PROMPT", "VAD"
)?;
writeln!(out, "{}", "-".repeat(88))?;
for p in profiles {
let ref_str = p
.ref_duration_secs
.map_or_else(|| "-".to_string(), |d| format!("{d:.1}s"));
let prompt_str = p
.prompt_duration_secs
.map_or_else(|| "-".to_string(), |d| format!("{d:.1}s"));
let note = p
.description
.as_deref()
.or(p.instruct.as_deref())
.unwrap_or("");
writeln!(
out,
"{:<22} {:<8} {:<10} {:<6} {note}",
p.name.as_str(),
ref_str,
prompt_str,
if p.trim_silence_vad { "on" } else { "off" }
)?;
}
}
VoiceAction::Save(args) => {
let name = VoiceName::parse(&args.name)?;
let ref_wav_bytes = match &args.ref_audio {
Some(p) => Some(
tokio::fs::read(p)
.await
.with_context(|| format!("failed to read {}", p.display()))?,
),
None => None,
};
let prompt_wav_bytes = match &args.prompt_audio {
Some(p) => Some(
tokio::fs::read(p)
.await
.with_context(|| format!("failed to read {}", p.display()))?,
),
None => None,
};
let meta = store.save(SaveVoiceInput {
name,
description: args.description,
instruct: args.instruct,
ref_wav_bytes,
prompt_wav_bytes,
prompt_text: args.prompt_text,
trim_silence_vad: !args.no_trim_silence,
})?;
let mut out = io::stdout().lock();
writeln!(
out,
"Saved voice '{}' in {} (ref={}, prompt={})",
meta.name,
store.root().display(),
meta.ref_duration_secs
.map_or_else(|| "none".into(), |d| format!("{d:.2}s")),
meta.prompt_duration_secs
.map_or_else(|| "none".into(), |d| format!("{d:.2}s")),
)?;
}
VoiceAction::Show { name } => {
let name = VoiceName::parse(&name)?;
let meta = store.get(&name)?;
let mut out = io::stdout().lock();
writeln!(out, "Name : {}", meta.name)?;
if let Some(d) = meta.description {
writeln!(out, "Description : {d}")?;
}
if let Some(i) = meta.instruct {
writeln!(out, "Instruct : {i}")?;
}
writeln!(
out,
"Ref audio : {}",
meta.ref_duration_secs
.map_or_else(|| "none".into(), |d| format!("{d:.2}s"))
)?;
writeln!(
out,
"Prompt audio: {}",
meta.prompt_duration_secs
.map_or_else(|| "none".into(), |d| format!("{d:.2}s"))
)?;
if let Some(pt) = meta.prompt_text {
writeln!(out, "Prompt text : {pt}")?;
}
writeln!(out, "VAD trim : {}", meta.trim_silence_vad)?;
}
VoiceAction::Delete { name } => {
let name = VoiceName::parse(&name)?;
store.delete(&name)?;
let mut out = io::stdout().lock();
writeln!(out, "Deleted voice '{name}'")?;
}
}
Ok(())
}
fn run_download(args: DownloadArgs) -> Result<()> {
let repo = expand_model_shorthand(&args.model);
let resolved =
resolve_model_files(&repo).with_context(|| format!("failed to download model '{repo}'"))?;
let mut out = io::stdout().lock();
writeln!(out, "Model directory : {}", resolved.model_dir.display())?;
writeln!(out, "Config : {}", resolved.config_path.display())?;
writeln!(
out,
"Tokenizer : {}",
resolved.tokenizer_path.display()
)?;
writeln!(out, "Weight shards : {}", resolved.weight_files.len())?;
for w in &resolved.weight_files {
writeln!(out, " - {}", w.display())?;
}
Ok(())
}
async fn run_speak(voices_dir: Option<PathBuf>, args: SpeakArgs) -> Result<()> {
if args.output.is_none() && !args.play {
bail!("specify --output <path.wav> and/or --play");
}
let text = read_input_text(&args).await?;
let inline_prompt = build_voice_prompt(&args)?;
let model_spec = expand_model_shorthand(&args.model);
let mut req = SynthesisRequest::builder()
.text(text)
.inference_timesteps(args.steps)
.cfg_value(args.cfg)
.use_cfg_zero_star(!args.no_cfg_zero_star)
.temperature(args.temperature)
.speed(args.speed)
.preserve_pitch(!args.no_preserve_pitch)
.pitch_semitones(args.pitch)
.max_tokens(args.max_tokens)
.stream_chunk_patches(args.stream_chunk_patches)
.auto_chunk(!args.no_chunk)
.chunk_max_units(args.chunk_max_units)
.build();
req.instruct = args.instruct;
req.voice_prompt = inline_prompt;
req.seed = args.seed;
if let Some(voice_name) = &args.voice {
let store = open_voice_store(voices_dir)?;
let parsed = VoiceName::parse(voice_name)?;
req = req.with_saved_voice(&store, &parsed)?;
}
if let Some(preset_id) = &args.preset {
req = req.with_preset(preset_id)?;
}
let handle = InferenceEngine::spawn(&model_spec, DEFAULT_QUEUE_CAPACITY)
.await
.with_context(|| format!("failed to load model '{model_spec}'"))?;
let engine = handle.engine();
let sample_rate = engine.sample_rate();
let use_stream = args.stream || args.play;
let mut collected: Vec<f32> = Vec::new();
let stats = if use_stream {
let player = if args.play {
Some(playback::StreamingPlayer::open(sample_rate)?)
} else {
None
};
let mut rx = engine.synthesize_stream(req, 16).await?;
let mut final_stats = None;
while let Some(event) = rx.recv().await {
match event {
StreamEvent::Chunk(chunk) => {
if let Some(p) = &player {
p.push(&chunk.samples)?;
}
if args.output.is_some() {
collected.extend_from_slice(&chunk.samples);
}
}
StreamEvent::Done(s) => {
final_stats = Some(s);
break;
}
StreamEvent::Error(e) => {
handle.shutdown().await;
return Err(e.into());
}
}
}
if let Some(p) = &player {
p.drain().await;
}
final_stats.ok_or_else(|| anyhow::anyhow!("synthesis stream ended unexpectedly"))?
} else {
let (samples, stats) = engine.synthesize(req).await?;
collected = samples;
stats
};
if let Some(out_path) = &args.output {
write_wav_pcm16(out_path, &collected, sample_rate)
.with_context(|| format!("failed to write {}", out_path.display()))?;
}
handle.shutdown().await;
let mut err = io::stderr().lock();
writeln!(
err,
"Done | audio={:.2}s | ttfa={}ms | elapsed={:.2}s | RTF={:.3} (<1.0 faster than realtime) \
| patches={} | peak_mem={:.2} GB",
stats.audio_duration_secs,
stats.ttfa.as_millis(),
stats.elapsed.as_secs_f64(),
stats.rtf,
stats.audio_patches,
stats.peak_memory_bytes as f64 / 1e9,
)?;
if let Some(out_path) = &args.output {
writeln!(err, "Saved: {}", out_path.display())?;
}
Ok(())
}