From 04f631eb8258ed9a19bce043d0185897cc328c59 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:32:05 +0000 Subject: [PATCH 1/2] feat!: add pitch fields to Telemetry and trim Wasm voice slices - Add the five Feedback pitch fields to Telemetry - Populate the pitch fields in Processor::telemetry - Add active_voice_ratios and active_voice_gains on Telemetry - Serialize active Wasm voices into Float32Array slices - Type voiceRatios and voiceGains as Float32Array in TypeScript - Update the telemetry rustdoc and README.md --- README.md | 16 +++--- src/lib.rs | 11 ++-- src/processor.rs | 92 +++++++++++++++++++++++++++++---- src/wasm.rs | 129 ++++++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 220 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 83a8f47..17c2739 100644 --- a/README.md +++ b/README.md @@ -304,14 +304,16 @@ These calls read the state of the processor. They do not change the audio. The telemetry includes these items: -- The pitch ratio and the gain of each voice. +- The pitch, the correction ratio and the frame count from the feedback. +- The pitch ratio and the gain of each active voice. - The peaks of the input, of the two output channels and of the reverb wet signal. - The pitch clarity, which is a confidence score from 0 to 1. - The current gains of Punch and Warm, and the position in the Alien loop. -The peak windows of the telemetry are independent of the peak window of the -feedback. The latency is nominal. Dry mixes, resampled voices and effects +`active_voice_ratios()` and `active_voice_gains()` return slices for the active +voices. The peak windows of the telemetry are independent of the peak window of +the feedback. The latency is nominal. Dry mixes, resampled voices and effects have different timing. `formant_envelope()` writes two LPC envelopes into slices of equal length: @@ -482,10 +484,12 @@ bindings. ### Feedback, telemetry and formant envelopes -`telemetry()` and `takeTelemetry()` return a `Telemetry` object. +`telemetry()` and `takeTelemetry()` return a `Telemetry` object. In +`Telemetry`, `voiceRatios` and `voiceGains` are `Float32Array` values of length +`voiceCount`. -In feedback, `targetMidiNote` is `undefined` in these cases, which are also -the cases where `voiced` is `false`: +In feedback and telemetry, `targetMidiNote` is `undefined` in these cases, +which are also the cases where `voiced` is `false`: - The kept pitch estimate is unvoiced. This includes the time before the first detection and after a reset or a drain completion. diff --git a/src/lib.rs b/src/lib.rs index f17bc85..75cb260 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,12 +56,11 @@ //! resynthesis delay. Voice delays, pitch changes and effects have their own //! timing. //! -//! [`Processor::telemetry`] gives data for meters and displays: the ratio and -//! the gain of each voice, the input and output peaks, the pitch clarity and -//! the state of the effects. [`Processor::take_telemetry`] also clears the -//! peak windows of the telemetry. [`Processor::formant_envelope`] writes the -//! LPC envelopes before and after the formant controls. These calls do not -//! change the audio. +//! [`Processor::telemetry`] gives data for meters and displays. It includes +//! the pitch, the voice ratios and gains, the peaks, the clarity and the +//! effect state. [`Processor::take_telemetry`] also clears the peak windows of +//! the telemetry. [`Processor::formant_envelope`] writes the LPC envelopes +//! before and after the formant controls. These calls do not change the audio. //! //! After the last input block, call [`Processor::begin_drain`] one time. Then //! render drain blocks until a call returns zero. Each call fills the unused diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..94faeba 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -352,14 +352,15 @@ impl Processor { result } - /// Returns the state of the voices, the levels and the effects, and does - /// not clear the peak windows. + /// Returns the pitch, the state of the voices, the levels and the effects, + /// and does not clear the peak windows. /// /// The telemetry is for meters and displays. It does not change the /// audio. To start new peak windows, use /// [`take_telemetry`](Self::take_telemetry). The peak windows of the /// telemetry are independent of the peak window of [`Feedback`]. pub fn telemetry(&self) -> Telemetry { + let estimate = self.resynthesis.estimate(); let mut voice_ratios = [0.0; 16]; let mut voice_gains = [0.0; 16]; let voice_count = self.resynthesis.voices(&mut voice_ratios, &mut voice_gains); @@ -369,6 +370,11 @@ impl Processor { input_peak: self.input_peak as f32 / 32_768.0, output_peak: self.output_peaks.map(|peak| peak as f32 / 32_768.0), reverb_wet_peak: self.reverb.wet_peak(), + resample_ratio: self.last_resample_ratio, + period_samples: estimate.period_samples, + frequency_hz: estimate.frequency_hz, + target_midi_note: self.resynthesis.target_note(), + voiced: estimate.voiced, clarity: self.resynthesis.clarity(), tracking: self.resynthesis.is_tracking(), voice_count, @@ -780,12 +786,12 @@ pub struct Feedback { pub latency_frames: usize, } -/// A snapshot of the voices, the levels and the effect state that you can -/// copy. +/// A snapshot of the pitch, the voices, the levels and the effect state that +/// you can copy. /// /// Get it with [`Processor::telemetry`] or [`Processor::take_telemetry`]. The /// telemetry is for meters and displays. No audio calculation reads it. -/// `Default` gives a snapshot with all zeros. +/// `Default` gives a snapshot with all zeros and no target. /// /// The three peak fields measure a window. The window starts at /// construction, at a reset, at a change of stereo output or at a call to @@ -794,7 +800,7 @@ pub struct Feedback { #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Deserialize, tsify::Tsify), serde(rename_all = "camelCase"), tsify(large_number_types_as_bigints) )] @@ -819,12 +825,46 @@ pub struct Telemetry { /// gain. It is the larger of the two channels. While the reverb is /// disabled, the window gets no new values. pub reverb_wet_peak: f32, + /// The pitch-correction ratio from the last processed frame, where 1 is + /// unity, as [`Feedback::resample_ratio`] gives. + /// + /// It does not include the configured pitch shift or the ratios of + /// individual voices. It is zero before the first frame, after a reset or + /// after a change of stereo output. + pub resample_ratio: f32, + /// The reported input pitch period in samples, with fractional samples, as + /// [`Feedback::period_samples`] gives. + /// + /// If [`voiced`](Self::voiced) is `false`, this value is zero. The bounds + /// of [`crate::PitchConfig`] apply to this report. + pub period_samples: f32, + /// The reported input pitch frequency in hertz, as + /// [`Feedback::frequency_hz`] gives. + /// + /// The value comes from the sample rate and + /// [`period_samples`](Self::period_samples). If [`voiced`](Self::voiced) + /// is `false`, this value is zero. + pub frequency_hz: f32, + /// The correction target or the input pitch, as a MIDI note number, as + /// [`Feedback::target_midi_note`] gives. + /// + /// If correction selects a note from a non-empty table, the value is that + /// pitch class in the nearest octave. In other cases, the value is the + /// fractional MIDI note of the input. If [`voiced`](Self::voiced) is + /// `false`, and only then, this value is `None`. + pub target_midi_note: Option, + /// This field is `true` if the current pitch estimate is positive and + /// inside the bounds of [`crate::PitchConfig`]. + /// + /// This is not an amplitude gate or a confidence score. A result can stay + /// between detector updates. + pub voiced: bool, /// How periodic the tracked input is, in 0..=1. /// /// The value is 1 for a signal that repeats exactly at the tracked /// period. It is 0 for a signal with no relation between cycles and /// during pitch acquisition. Use it as a confidence score for - /// [`Feedback::voiced`]. The tracker updates the related sums on each + /// [`voiced`](Self::voiced). The tracker updates the related sums on each /// frame. pub clarity: f32, /// This field is `true` if the pitch tracker follows a period. It is @@ -843,7 +883,13 @@ pub struct Telemetry { /// harmony voices. In Choir mode, the entries after the lead are the /// secondary voices. Each ratio includes the correction, the configured /// pitch shift and the ratio of the voice. The entries after - /// [`voice_count`](Self::voice_count) are zero. + /// [`voice_count`](Self::voice_count) are zero. In JavaScript, this field + /// is a `Float32Array` of length `voiceCount`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(deserialize_with = "crate::wasm::deserialize_voice_array"), + tsify(type = "Float32Array") + )] pub voice_ratios: [f32; 16], /// The linear gain of each voice, in the order of /// [`voice_ratios`](Self::voice_ratios). @@ -853,7 +899,13 @@ pub struct Telemetry { /// velocity 127 gives the maximum, approximately +12 dB. The gain is zero /// for a voice that does not sound. It does not include the configured /// harmony level or the pan. The harmony controller updates it every 101 - /// frames. + /// frames. In JavaScript, this field is a `Float32Array` of length + /// `voiceCount`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(deserialize_with = "crate::wasm::deserialize_voice_array"), + tsify(type = "Float32Array") + )] pub voice_gains: [f32; 16], /// The current drive of Punch, divided by its base drive. /// @@ -884,3 +936,25 @@ pub struct Telemetry { /// [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, } + +impl Telemetry { + /// Returns the pitch ratios of the active voices, from `0` to + /// [`voice_count`](Self::voice_count). + /// + /// If `voice_count` is more than 16, this method limits the slice length + /// to 16. + pub fn active_voice_ratios(&self) -> &[f32] { + let count = usize::from(self.voice_count).min(self.voice_ratios.len()); + &self.voice_ratios[..count] + } + + /// Returns the linear gains of the active voices, from `0` to + /// [`voice_count`](Self::voice_count). + /// + /// If `voice_count` is more than 16, this method limits the slice length + /// to 16. + pub fn active_voice_gains(&self) -> &[f32] { + let count = usize::from(self.voice_count).min(self.voice_gains.len()); + &self.voice_gains[..count] + } +} diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..7e652af 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -44,10 +44,11 @@ use crate::{ Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Float32Array, Int16Array}; +use js_sys::{Array, Float32Array, Int16Array, Object}; use serde::{Deserialize, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; /// The events for one call that processes audio (`TimedEvent[]` in TypeScript). /// @@ -394,16 +395,18 @@ impl WasmProcessor { /// Returns a new telemetry object and does not clear its peak windows. /// - /// The telemetry is for meters and displays. It gives the ratio and the - /// gain of each voice, the input and output peaks, the pitch clarity and - /// the state of the effects. `processedFrames` is a `bigint`. See - /// `Telemetry` for each measurement. + /// The telemetry is for meters and displays. It gives the pitch, the + /// active voice ratios and gains, the peaks, the clarity and the effect + /// state. `voiceRatios` and `voiceGains` are `Float32Array` values of + /// length `voiceCount`. If `voiced` is `false`, `targetMidiNote` is + /// `undefined`. `processedFrames` is a `bigint`. See `Telemetry` for each + /// measurement. /// /// # Errors /// /// If the conversion to a JavaScript object fails, this method throws. pub fn telemetry(&self) -> Result, JsError> { - Ok(self.processor.telemetry().into_ts()?) + Ok(serialize_telemetry(&self.processor.telemetry())) } /// Returns the telemetry and clears only its three peak windows. @@ -417,7 +420,7 @@ impl WasmProcessor { /// object. #[wasm_bindgen(js_name = takeTelemetry)] pub fn take_telemetry(&mut self) -> Result, JsError> { - let telemetry = self.processor.telemetry().into_ts()?; + let telemetry = serialize_telemetry(&self.processor.telemetry()); self.processor.take_telemetry(); Ok(telemetry) } @@ -523,3 +526,115 @@ pub(crate) fn serialize_frame_count( ) -> Result { serializer.serialize_u32(*frames as u32) } + +#[wasm_bindgen] +extern "C" { + type JsTelemetry; + + #[wasm_bindgen(method, setter = processedFrames)] + fn set_processed_frames(this: &JsTelemetry, value: u64); + #[wasm_bindgen(method, setter = inputPeak)] + fn set_input_peak(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = outputPeak)] + fn set_output_peak(this: &JsTelemetry, value: &Array); + #[wasm_bindgen(method, setter = reverbWetPeak)] + fn set_reverb_wet_peak(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = resampleRatio)] + fn set_resample_ratio(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = periodSamples)] + fn set_period_samples(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = frequencyHz)] + fn set_frequency_hz(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = targetMidiNote)] + fn set_target_midi_note(this: &JsTelemetry, value: Option); + #[wasm_bindgen(method, setter = voiced)] + fn set_voiced(this: &JsTelemetry, value: bool); + #[wasm_bindgen(method, setter = clarity)] + fn set_clarity(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = tracking)] + fn set_tracking(this: &JsTelemetry, value: bool); + #[wasm_bindgen(method, setter = voiceCount)] + fn set_voice_count(this: &JsTelemetry, value: u8); + #[wasm_bindgen(method, setter = voiceRatios)] + fn set_voice_ratios(this: &JsTelemetry, value: &Float32Array); + #[wasm_bindgen(method, setter = voiceGains)] + fn set_voice_gains(this: &JsTelemetry, value: &Float32Array); + #[wasm_bindgen(method, setter = punchGain)] + fn set_punch_gain(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = warmGain)] + fn set_warm_gain(this: &JsTelemetry, value: f32); + #[wasm_bindgen(method, setter = alienLoopFrames)] + fn set_alien_loop_frames(this: &JsTelemetry, value: u32); + #[wasm_bindgen(method, setter = alienPhaseFrames)] + fn set_alien_phase_frames(this: &JsTelemetry, value: u32); + #[wasm_bindgen(method, setter = formantGeneration)] + fn set_formant_generation(this: &JsTelemetry, value: u32); +} + +/// Copies a slice of `f32` values into a new `Float32Array` of equal length. +fn float32_array(values: &[f32]) -> Float32Array { + let array = Float32Array::new_with_length(values.len() as u32); + array.copy_from(values); + array +} + +/// Builds a JavaScript telemetry object with `Float32Array` slices for the +/// active voices. +fn telemetry_object(telemetry: &Telemetry) -> JsTelemetry { + let object: JsTelemetry = Object::new().unchecked_into(); + let output_peak = Array::new(); + output_peak.set(0, JsValue::from_f64(f64::from(telemetry.output_peak[0]))); + output_peak.set(1, JsValue::from_f64(f64::from(telemetry.output_peak[1]))); + let ratios = float32_array(telemetry.active_voice_ratios()); + let gains = float32_array(telemetry.active_voice_gains()); + object.set_processed_frames(telemetry.processed_frames); + object.set_input_peak(telemetry.input_peak); + object.set_output_peak(&output_peak); + object.set_reverb_wet_peak(telemetry.reverb_wet_peak); + object.set_resample_ratio(telemetry.resample_ratio); + object.set_period_samples(telemetry.period_samples); + object.set_frequency_hz(telemetry.frequency_hz); + object.set_target_midi_note(telemetry.target_midi_note.map(f64::from)); + object.set_voiced(telemetry.voiced); + object.set_clarity(telemetry.clarity); + object.set_tracking(telemetry.tracking); + object.set_voice_count(telemetry.voice_count); + object.set_voice_ratios(&ratios); + object.set_voice_gains(&gains); + object.set_punch_gain(telemetry.punch_gain); + object.set_warm_gain(telemetry.warm_gain); + object.set_alien_loop_frames(telemetry.alien_loop_frames); + object.set_alien_phase_frames(telemetry.alien_phase_frames); + object.set_formant_generation(telemetry.formant_generation); + object +} + +/// Wraps a `Telemetry` snapshot in its typed JavaScript handle. +fn serialize_telemetry(telemetry: &Telemetry) -> Ts { + Ts::new_unchecked(telemetry_object(telemetry).into()) +} + +impl Serialize for Telemetry { + fn serialize(&self, serializer: S) -> Result { + let object = telemetry_object(self); + tsify::serde_wasm_bindgen::preserve::serialize(&object, serializer) + } +} + +/// Copies a JavaScript `Float32Array` of at most 16 entries into a stack +/// array. +pub(crate) fn deserialize_voice_array<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result<[f32; 16], D::Error> { + let array: Float32Array = tsify::serde_wasm_bindgen::preserve::deserialize(deserializer)?; + let length = array.length() as usize; + if length > 16 { + return Err(serde::de::Error::invalid_length( + length, + &"a Float32Array with at most 16 entries", + )); + } + let mut values = [0.0; 16]; + array.copy_to(&mut values[..length]); + Ok(values) +} From c8b52ef231a1483dfd6da7b45b5961c9b25fa747 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:58:41 +0000 Subject: [PATCH 2/2] feat!: mark Telemetry as non-exhaustive - Add #[non_exhaustive] to Telemetry in src/processor.rs --- src/processor.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/processor.rs b/src/processor.rs index 040eb60..d929541 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -811,6 +811,7 @@ pub struct Feedback { /// [`Processor::take_telemetry`]. This window is independent of the peak /// window of [`Feedback`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Deserialize, tsify::Tsify),