Skip to content

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

Rust

Engine: the beatbox sequencer on the fixed sub-block cadence; beat exports

Jameson Hodge45ba6ea4b514
diff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rs
index 9666a4a..6c9390e 100644
--- a/crates/chimera-wasm/src/lib.rs
+++ b/crates/chimera-wasm/src/lib.rs
@@ -22,15 +22,26 @@
//! | 240 | u8 | label length in bytes (255: no label) |
//! | 241 | 24 × u8 | label, UTF-8, cut at a character boundary |
//! | 265 | 7 × u8 | padding |
+//!
+//! # Beat-step records ([`STEP_RECORD`] = 48 bytes, in the same record area)
+//! | offset | type | field |
+//! |-------:|----------|-------|
+//! | 0 | u8 | id length in bytes (255: a rest) |
+//! | 1 | 24 × u8 | sound id, UTF-8 |
+//! | 25 | 7 × u8 | padding |
+//! | 32 | f64 | note (MIDI; NaN: absent) |
+//! | 40 | f64 | accent (NaN: absent) |
pub mod api;
use chimera::anatomy::human::{ArticPatch, BodyName, N_ARTIC};
use chimera::control::score::{Gesture, Label, N_CONTROL, Targets};
use chimera::engine::{Engine, MAX_SCHEDULE};
+use chimera::phonetics::beatbox::BeatStep;
use chimera::voice::human_voice::{SourcePatch, VoiceTelemetry};
pub const GESTURE_RECORD: usize = 272;
+pub const STEP_RECORD: usize = 48;
pub const LAYOUT_VERSION: u32 = 1;
/// Largest `engine_render` request (frames).
pub const MAX_RENDER: usize = 4096;
@@ -382,3 +393,60 @@ pub unsafe extern "C" fn engine_telemetry(h: *mut Handle) -> *const f64 {
pub unsafe extern "C" fn engine_tele_labels(h: *mut Handle) -> *const u8 {
handle!(h).tele_labels.as_ptr()
}
+
+/// Decode a beat-step record (see the module docs).
+pub fn read_step(b: &[u8]) -> Option<BeatStep> {
+ let len = b[0];
+ if len == 255 {
+ return None;
+ }
+ let f = |o: usize| f64::from_le_bytes(b[o..o + 8].try_into().unwrap());
+ Some(BeatStep { id: Label::from_bytes(&b[1..1 + (len as usize).min(Label::CAP)]), note: opt(f(32)), accent: opt(f(40)) })
+}
+
+/// The sequencer. `count` step records in the record area replace the pattern if `has_steps`;
+/// `bpm`/`swing` NaN keep the current value; `playing` 0 stop, 1 start, other: unchanged.
+///
+/// # Safety
+/// `h` must be a live handle.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn engine_set_beat(h: *mut Handle, has_steps: u32, count: usize, bpm: f64, swing: f64, playing: u32) {
+ let h = handle!(h);
+ if has_steps != 0 {
+ let count = count.min(128);
+ let mut steps = [None; 128];
+ for (i, s) in steps.iter_mut().enumerate().take(count) {
+ *s = read_step(&h.records[i * STEP_RECORD..(i + 1) * STEP_RECORD]);
+ }
+ h.engine.set_beat_steps(&steps[..count]);
+ }
+ if !bpm.is_nan() || !swing.is_nan() {
+ h.engine.set_beat_tempo(opt(bpm), opt(swing));
+ }
+ match playing {
+ 0 => h.engine.set_beat_playing(false),
+ 1 => h.engine.set_beat_playing(true),
+ _ => {}
+ }
+}
+
+/// Play the sound of the first step record of the record area as soon as the mouth can.
+///
+/// # Safety
+/// `h` must be a live handle.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn engine_beat_hit(h: *mut Handle) {
+ let h = handle!(h);
+ if let Some(step) = read_step(&h.records[..STEP_RECORD]) {
+ h.engine.beat_hit(&step);
+ }
+}
+
+/// The beat step under the playhead (−1: stopped).
+///
+/// # Safety
+/// `h` must be a live handle.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn engine_beat_step(h: *mut Handle) -> f64 {
+ handle!(h).engine.beat_step() as f64
+}
diff --git a/crates/chimera/src/engine.rs b/crates/chimera/src/engine.rs
index b53ad6d..f0de0f8 100644
--- a/crates/chimera/src/engine.rs
+++ b/crates/chimera/src/engine.rs
@@ -10,7 +10,9 @@
//! warm. A body or creature switch builds a new airway network (it allocates).
use crate::anatomy::human::{ArticPatch, BodyName};
+use crate::control::beat_player::BeatPlayer;
use crate::control::score::{Gesture, GestureScore};
+use crate::phonetics::beatbox::{BeatStep, MAX_SOUND_GESTURES};
use crate::voice::human_voice::{HumanVoice, SourcePatch, VoiceTelemetry};
/// Samples per sub-block: the browser's render quantum, kept for every host.
@@ -44,13 +46,14 @@ pub struct Engine {
/// samples rendered so far (sub-block phase)
pos: u64,
scratch: Vec<Gesture>,
+ beat: BeatPlayer,
}
impl Engine {
pub fn new(sample_rate: f64) -> Engine {
crate::init();
let body = BodyName::Male;
- Engine { sample_rate, body, voice: Self::make_voice(sample_rate, body), gate_level: 0.0, pos: 0, scratch: Vec::with_capacity(MAX_SCHEDULE) }
+ Engine { sample_rate, body, voice: Self::make_voice(sample_rate, body), gate_level: 0.0, pos: 0, scratch: Vec::with_capacity(MAX_SCHEDULE), beat: BeatPlayer::new() }
}
fn make_voice(fs: f64, body: BodyName) -> HumanVoice {
@@ -86,6 +89,11 @@ impl Engine {
self.voice.set_articulation(&target, Some(prev.artic.tip_free));
// the performer's breath, not the voice's (which includes breath from the score)
self.voice.set_gate(self.gate_level);
+ // the new voice's clock starts at zero: keep the beat's phase across the switch, and
+ // queue again the hits the old voice's score was holding (built for the new body)
+ self.beat.body = body;
+ self.beat.rebase(self.voice.clock - prev.clock);
+ self.beat.rewind(self.voice.clock);
self.info()
}
@@ -153,8 +161,56 @@ impl Engine {
}
}
- /// Per-sub-block bookkeeping (the sequencer's tick).
- fn sub_block_start(&mut self) {}
+ /// Per-sub-block bookkeeping: the sequencer schedules the hits within its horizon.
+ fn sub_block_start(&mut self) {
+ let voice = &mut self.voice;
+ let clock = voice.clock;
+ self.beat.tick(clock, &mut |gs| voice.schedule(gs));
+ }
+
+ // ---------------------------------------------------------------- beatbox sequencer
+
+ /// Replace the pattern (at most 128 steps; `None` is a rest).
+ pub fn set_beat_steps(&mut self, steps: &[Option<BeatStep>]) {
+ self.beat.set_steps(steps);
+ }
+
+ /// Change tempo/swing (`None`: keep). The next unscheduled step keeps its time.
+ pub fn set_beat_tempo(&mut self, bpm: Option<f64>, swing: Option<f64>) {
+ let b = &mut self.beat;
+ b.set_tempo(bpm.unwrap_or(b.bpm), swing.unwrap_or(b.swing));
+ }
+
+ /// Start or stop the sequencer. Stopping also silences hits already scheduled.
+ pub fn set_beat_playing(&mut self, playing: bool) {
+ if playing && !self.beat.playing {
+ self.beat.start(self.voice.clock);
+ }
+ if !playing && self.beat.playing {
+ self.beat.stop();
+ // hits already scheduled within the horizon would still sound
+ self.voice.cancel_score();
+ }
+ }
+
+ pub fn beat(&self) -> &BeatPlayer {
+ &self.beat
+ }
+
+ /// Play one beatbox sound as soon as the mouth can make it.
+ pub fn beat_hit(&mut self, step: &BeatStep) {
+ self.scratch.clear();
+ let hit = self.voice.clock + BeatPlayer::lead_in_with(step.id.as_str(), self.body.as_str(), &mut self.scratch);
+ self.scratch.clear();
+ self.beat.gestures(step, hit, 0.18, &mut self.scratch);
+ debug_assert!(self.scratch.len() <= MAX_SOUND_GESTURES);
+ self.voice.schedule(&self.scratch);
+ }
+
+ /// The beat step under the playhead (−1 when the sequencer is stopped).
+ pub fn beat_step(&self) -> i64 {
+ self.beat.step_at(self.voice.clock)
+ }
pub fn telemetry(&mut self, out: &mut VoiceTelemetry) {
self.voice.telemetry(out);
diff --git a/crates/chimera/src/lib.rs b/crates/chimera/src/lib.rs
index b8fd9c0..1225033 100644
--- a/crates/chimera/src/lib.rs
+++ b/crates/chimera/src/lib.rs
@@ -52,5 +52,7 @@ pub mod phonetics;
/// Parse every embedded data table now (an `Engine` does this when it is created), so nothing
/// initialises lazily on an audio thread later.
pub fn init() {
- phonetics::planner::vowel_table();
+ phonetics::planner::init();
+ phonetics::inventory::init();
+ phonetics::beatbox::init();
}
diff --git a/crates/chimera/tests/engine.rs b/crates/chimera/tests/engine.rs
new file mode 100644
index 0000000..50a1aeb
--- /dev/null
+++ b/crates/chimera/tests/engine.rs
@@ -0,0 +1,87 @@
+//! The instrument as a whole: the beatbox bar of the TypeScript worklet's scheduling reproduced
+//! through `Engine`, and output independent of the host's block size with the sequencer playing,
+//! a body switch, schedules and releases at fixed absolute sample positions.
+mod common;
+use chimera::anatomy::human::{ArticKey, ArticPatch, BodyName};
+use chimera::control::score::{Gesture, Targets};
+use chimera::engine::Engine;
+use chimera::phonetics::beatbox::{BeatStep, beat_ready, parse_beat};
+use chimera::voice::human_voice::SourcePatch;
+use common::*;
+
+#[test]
+fn engine_plays_the_beatbox_bar_like_the_typescript_worklet() {
+ let g = load("planning");
+ let a = &g["audio"];
+ let reference = load_f32("beatbox-bar");
+ let mut e = Engine::new(num(&a["fs"]));
+ e.set_source(&SourcePatch::f0(num(&a["f0"])));
+ e.set_artic(&beat_ready("male"), None);
+ e.set_beat_steps(&parse_beat(a["text"].as_str().unwrap()));
+ e.set_beat_tempo(Some(num(&a["bpm"])), Some(num(&a["swing"])));
+ e.set_beat_playing(true);
+ let n = a["samples"].as_u64().unwrap() as usize;
+ let tempo_at = a["tempoAt"].as_u64().unwrap() as usize * 128;
+ let tempo = nums(&a["tempo"]);
+ let mut out = vec![0.0f32; n];
+ e.render(&mut out[..tempo_at]);
+ e.set_beat_tempo(Some(tempo[0]), Some(tempo[1]));
+ e.render(&mut out[tempo_at..]);
+ let d = compare_audio(&reference, &out, 1e-6, 480);
+ println!("beatbox bar through Engine: max err {:.2e} of peak, first >1e-6 at {:?}", d.max_err, d.first_diverge);
+ assert!(d.first_diverge.is_none(), "{d:?}");
+}
+
+/// Commands at absolute sample positions, then the samples, rendered in blocks of `block`.
+fn session(block: usize) -> Vec<f32> {
+ let fs = 48000.0;
+ let mut e = Engine::new(fs);
+ let n = 2 * 48000;
+ let mut out = vec![0.0f32; n];
+ let mut note = Targets::default();
+ note.set(ArticKey::TbX, 3.6).set(chimera::control::score::ControlKey::F0, 180.0).set(chimera::control::score::ControlKey::BREATH, 1.0);
+ let held = [Gesture::new(0.0, 1e9, 0.03, 0.08, 4.0, note).tag(3.0).label("ɑ")];
+ // (sample, command)
+ let events: Vec<(usize, Box<dyn Fn(&mut Engine)>)> = vec![
+ (0, Box::new(|e: &mut Engine| e.set_beat_steps(&parse_beat("B t Pf t | B B Pf ^K")))),
+ (0, Box::new(|e: &mut Engine| e.set_beat_tempo(Some(120.0), Some(0.15)))),
+ (0, Box::new(|e: &mut Engine| e.set_beat_playing(true))),
+ (20000, Box::new(|e: &mut Engine| e.beat_hit(&BeatStep::new("K")))),
+ (30000, Box::new(|e: &mut Engine| e.set_beat_tempo(Some(90.0), None))),
+ (41000, Box::new(|e: &mut Engine| {
+ e.set_body(BodyName::Female);
+ })),
+ (55000, Box::new(|e: &mut Engine| e.set_beat_playing(false))),
+ (56000, Box::new(move |e: &mut Engine| {
+ e.schedule(&held, 0.01, false);
+ })),
+ (60000, Box::new(|e: &mut Engine| e.set_artic(&ArticPatch::default().with(ArticKey::Jaw, 1.2), None))),
+ (75000, Box::new(|e: &mut Engine| e.release(3.0))),
+ (80000, Box::new(|e: &mut Engine| e.set_gate(1.0))),
+ ];
+ let mut i = 0;
+ let mut ei = 0;
+ while i < n {
+ while ei < events.len() && events[ei].0 <= i {
+ (events[ei].1)(&mut e);
+ ei += 1;
+ }
+ let next = if ei < events.len() { events[ei].0 } else { n };
+ let end = n.min(i + block).min(next.max(i + 1));
+ e.render(&mut out[i..end]);
+ i = end;
+ }
+ out
+}
+
+#[test]
+fn output_does_not_depend_on_the_host_block_size() {
+ let reference = session(128);
+ let peak = reference.iter().fold(0.0f32, |m, x| m.max(x.abs()));
+ assert!(peak > 0.05, "the session should make sound (peak {peak})");
+ for block in [1usize, 77, 4096, 48000] {
+ let got = session(block);
+ let first = reference.iter().zip(&got).position(|(a, b)| a.to_bits() != b.to_bits());
+ assert_eq!(first, None, "block size {block}: differs from 128-sample blocks at sample {first:?}");
+ }
+}
diff --git a/src/wasm/wire.ts b/src/wasm/wire.ts
index 47613bc..750035c 100644
--- a/src/wasm/wire.ts
+++ b/src/wasm/wire.ts
@@ -74,3 +74,33 @@ export function writeGestures(buf: ArrayBuffer, at: number, gestures: readonly G
}
return n;
}
+
+export const STEP_RECORD = 48;
+
+/** A beatbox pattern step as the engine takes it. */
+export interface BeatStepRecord {
+ id: string;
+ note?: number;
+ accent?: number;
+}
+
+/** Write beat steps (null: rest) as 48-byte records at byte offset `at`. Returns the count written. */
+export function writeSteps(buf: ArrayBuffer, at: number, steps: readonly (BeatStepRecord | null)[], max = 128): number {
+ const n = Math.min(steps.length, max);
+ const dv = new DataView(buf, at, n * STEP_RECORD);
+ const bytes = new Uint8Array(buf, at, n * STEP_RECORD);
+ for (let i = 0; i < n; i++) {
+ const s = steps[i];
+ const o = i * STEP_RECORD;
+ if (!s) {
+ bytes[o] = 255;
+ continue;
+ }
+ const b = utf8(s.id).slice(0, LABEL_CAP);
+ bytes[o] = b.length;
+ bytes.set(b, o + 1);
+ dv.setFloat64(o + 32, s.note ?? NaN, true);
+ dv.setFloat64(o + 40, s.accent ?? NaN, true);
+ }
+ return n;
+}