Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

chimera CLI: render notes --artic, the articulators over time for lip sync

Jameson Hodgeabd93d4b3d43
diff --git a/crates/chimera-cli/src/main.rs b/crates/chimera-cli/src/main.rs
index 342ecc9..38d61cb 100644
--- a/crates/chimera-cli/src/main.rs
+++ b/crates/chimera-cli/src/main.rs
@@ -18,7 +18,8 @@ usage: chimera <command> [args] [--float]
render speech <out> [\"ipa / ipa\"] [male|female|child]
render text <out> [\"English text.\"] [male|female|child]
render song [outdir] [male|female|child]
- render notes <in.json> <out> [male|female|child] (melody file; midi <= 0 is a rest)
+ render notes <in.json> <out> [male|female|child] [--artic tracks.json]
+ (melody file; midi <= 0 is a rest; --artic also writes the articulators at 100 Hz)
render beatbox [outdir] [preset name | pattern] [male|female|child] [bpm] [bars]
render creature [creatureId] [outdir]
render vowels [male|female|child] [out]
diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rs
index c67f5a3..67c2feb 100644
--- a/crates/chimera-cli/src/render.rs
+++ b/crates/chimera-cli/src/render.rs
@@ -3,6 +3,7 @@
use crate::js::{fixed, num, pad_end, pad_start};
use crate::{Ctx, FS, arg, body, peak, repo_path, wav_name};
use chimera::analysis::lpc::{FormantOpts, estimate_formants};
+use chimera::anatomy::human::ArticKey;
use chimera::analysis::pitch::{YinOpts, yin_pitch};
use chimera::control::beat_player::BeatPlayer;
use chimera::control::score::Gesture;
@@ -338,11 +339,40 @@ pub fn song(ctx: &Ctx, a: &[String]) -> Result<(), String> {
Ok(())
}
+/// Articulator tracks are sampled at this rate (Hz): 480 samples at 48 kHz.
+const ARTIC_RATE: usize = 100;
+
+/// Render like `render_blocks`, and record the articulators at `ARTIC_RATE`: frame i is the state
+/// at i / ARTIC_RATE s. The voice runs sample by sample, so the sound is the same either way.
+fn render_tracked(v: &mut HumanVoice, out: &mut [f32]) -> Vec<Vec<f64>> {
+ let hop = FS as usize / ARTIC_RATE;
+ let frame = |v: &HumanVoice| ArticKey::ALL.iter().map(|k| js_round(v.artic.x.get(*k) * 1e4) / 1e4).collect();
+ let mut frames = vec![frame(v)];
+ for chunk in out.chunks_mut(hop) {
+ render_blocks(v, chunk);
+ frames.push(frame(v));
+ }
+ frames
+}
+
/// A melody from a JSON file: `{"bpm", "lyrics", "notes": [[midi, beats], ...], "vibrato"?}`.
/// One lyric syllable per sounding note; a note with midi <= 0 is a rest, which splits the
-/// melody into phrases planned separately on one voice. `render notes <in.json> <out> [body]`
+/// melody into phrases planned separately on one voice.
+/// `render notes <in.json> <out> [body] [--artic tracks.json]`: `--artic` also writes the
+/// articulators over time (`{"rate", "body", "keys", "frames"}`), to animate a face in sync.
pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
- let input = a.first().ok_or("render notes <in.json> <out> [male|female|child]")?;
+ let mut artic_out: Option<String> = None;
+ let mut rest = Vec::new();
+ let mut it = a.iter();
+ while let Some(x) = it.next() {
+ if x == "--artic" {
+ artic_out = Some(it.next().ok_or("--artic needs a file")?.clone());
+ } else {
+ rest.push(x.clone());
+ }
+ }
+ let a = &rest[..];
+ let input = a.first().ok_or("render notes <in.json> <out> [male|female|child] [--artic tracks.json]")?;
let out_name = wav_name(arg(a, 1, "out/notes"));
let body_name = arg(a, 2, "male");
let b = body(body_name)?;
@@ -396,9 +426,20 @@ pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
flush(&mut phrase, start, &mut v, &mut end);
let n = js_round(FS * (end + 0.4)) as usize;
let mut out = vec![0f32; n];
- render_blocks(&mut v, &mut out);
+ let frames = match &artic_out {
+ Some(_) => render_tracked(&mut v, &mut out),
+ None => {
+ render_blocks(&mut v, &mut out);
+ Vec::new()
+ }
+ };
ctx.write_wav(&out_name, &out)?;
println!("{out_name}: {} s, peak {}, {} notes", fixed(n as f64 / FS, 2), fixed(peak(&out), 3), sounding);
+ if let Some(path) = &artic_out {
+ let j = serde_json::json!({"rate": ARTIC_RATE, "body": body_name, "keys": ArticKey::NAMES, "frames": frames});
+ std::fs::write(path, j.to_string()).map_err(|e| format!("{path}: {e}"))?;
+ println!("{path}: {} frames at {ARTIC_RATE} Hz", frames.len());
+ }
Ok(())
}
diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rs
index 25def9a..ebbae05 100644
--- a/crates/chimera-cli/tests/cli.rs
+++ b/crates/chimera-cli/tests/cli.rs
@@ -151,3 +151,35 @@ fn calibrate_vowels_reproduces_the_committed_table() {
differing.len()
);
}
+
+#[test]
+fn render_notes_artic_tracks_follow_the_sound_without_changing_it() {
+ let melody = tmp("melody.json");
+ std::fs::write(
+ &melody,
+ r#"{"bpm": 120, "t0": 0, "lyrics": "Take my hand", "notes": [[0, 1], [67, 1], [63, 0.5], [60, 1.5]]}"#,
+ )
+ .unwrap();
+ let (plain, tracked, tracks) = (tmp("notes-plain"), tmp("notes-tracked"), tmp("notes-artic.json"));
+ chimera(&["render", "notes", &melody, &plain, "female"]);
+ let stdout = chimera(&["render", "notes", &melody, &tracked, "female", "--artic", &tracks]);
+ let a = std::fs::read(format!("{plain}.wav")).unwrap();
+ let b = std::fs::read(format!("{tracked}.wav")).unwrap();
+ assert!(a == b, "--artic changed the sound");
+
+ let j: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tracks).unwrap()).unwrap();
+ assert_eq!(j["rate"], 100);
+ let keys: Vec<&str> = j["keys"].as_array().unwrap().iter().map(|k| k.as_str().unwrap()).collect();
+ assert_eq!(keys.len(), 17);
+ let frames = j["frames"].as_array().unwrap();
+ // one frame at t = 0 and one per 480 samples rendered
+ let samples = (a.len() - 44) / 2;
+ assert_eq!(frames.len(), 1 + samples.div_ceil(480), "{stdout}");
+ assert!(frames.iter().all(|f| f.as_array().unwrap().len() == 17));
+ // the lips close for the /m/ of "my" (its note starts at 1 s) and open for its vowel
+ let lip = keys.iter().position(|k| *k == "lipAp").unwrap();
+ let ap = |i: usize| frames[i][lip].as_f64().unwrap();
+ let closed = (85..105).map(ap).fold(f64::MAX, f64::min);
+ let open = (105..125).map(ap).fold(f64::MIN, f64::max);
+ assert!(closed < 0.1 && open > 0.5, "lipAp closed {closed}, open {open}");
+}