diff --git a/README.md b/README.md index 66060d8..eae10b9 100644 --- a/README.md +++ b/README.md @@ -325,14 +325,16 @@ reverb network. 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. In mono calls, the output and reverb wet peaks measure the audio +`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. In mono calls, the output and reverb wet peaks measure the audio after the downmix. The dry path has the 1,593-frame delay. Resampled voices, choir delays and effects use different delays. @@ -566,10 +568,11 @@ bindings. `controlActivity()` returns a `ControlActivity` object with camelCase boolean flags for the choir, harmony and reverb controls. `telemetry()` and -`takeTelemetry()` return a `Telemetry` object. +`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/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index ad18b1d..9385dde 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -13,6 +13,7 @@ const pkgDir = path.join(repoRoot, "pkg"); /** Exact Rust intra-doc link and literal replacements for TypeScript JSDoc. */ const EXACT_REPLACEMENTS = [ ["[`voiced`](Self::voiced)", "`voiced`"], + ["[`period_samples`](Self::period_samples)", "`periodSamples`"], ["[`voice_ratios`](Self::voice_ratios)", "`voiceRatios`"], ["[`voice_gains`](Self::voice_gains)", "`voiceGains`"], ["[`voice_count`](Self::voice_count)", "`voiceCount`"], @@ -31,6 +32,10 @@ const EXACT_REPLACEMENTS = [ ["[`Processor::process_mono_in_place_f32`]", "the native `f32` mono method"], ["[`Processor`]", "the native processor"], ["[`Feedback::processed_frames`]", "`Feedback.processedFrames`"], + ["[`Feedback::resample_ratio`]", "`Feedback.resampleRatio`"], + ["[`Feedback::period_samples`]", "`Feedback.periodSamples`"], + ["[`Feedback::frequency_hz`]", "`Feedback.frequencyHz`"], + ["[`Feedback::target_midi_note`]", "`Feedback.targetMidiNote`"], ["[`Feedback::voiced`]", "`Feedback.voiced`"], [ "[`crate::ResynthesisConfig::choir_voices`]", @@ -125,6 +130,10 @@ const PROSE_REPLACEMENTS = [ /\s+`Default`\s+gives\s+a\s+snapshot\s+with\s+all\s+zeros\s+and\s+no\s+target\.\s+It\s+does\s+not\s+read\s+the\s+nominal\s+latency\s+of\s+a\s+prepared\s+processor\./g, "", ], + [ + /\s+`Default`\s+gives\s+a\s+snapshot\s+with\s+all\s+zeros\s+and\s+no\s+target\./g, + "", + ], [/\s+`Default`\s+gives\s+a\s+snapshot\s+with\s+all\s+zeros\./g, ""], [ /The\s+default\s+is\s+\[`PitchConfig::default`\]\./g, diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index be2bc0f..94b3e81 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -322,6 +322,12 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", + " const initialTelemetry = processor.telemetry();", + " assert.ok(initialTelemetry.voiceRatios instanceof Float32Array);", + " assert.ok(initialTelemetry.voiceGains instanceof Float32Array);", + " assert.equal(initialTelemetry.voiceRatios.length, initialTelemetry.voiceCount);", + " assert.equal(initialTelemetry.voiced, false);", + " assert.equal(initialTelemetry.targetMidiNote, undefined);", "", " const twoVoiceConfig = processor.config();", " twoVoiceConfig.resynthesis.harmony.voices = 2;", @@ -727,6 +733,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " type ProcessorConfig,", " type ResynthesisConfig,", " type SyncInitInput as RootSyncInitInput,", + " type Telemetry,", `} from ${pkgLiteral};`, "import init, {", " initSync as wasmInitSync,", @@ -784,6 +791,11 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const processor = new Tunelet(48000, 128, configWithUndefined);", " processor.setConfig(configWithUndefined);", " const activity: ControlActivity = processor.controlActivity();", + " const telemetry: Telemetry = processor.telemetry();", + " const voiceSlices: [Float32Array, Float32Array] = [", + " telemetry.voiceRatios,", + " telemetry.voiceGains,", + " ];", " const views = new TuneletAudioViews(exportsFromRoot.memory, processor);", " const ptrs: [number, number, number] = [", " processor.inputF32Ptr,", @@ -834,6 +846,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " views.dispose();", " processor.free();", " void activity;", + " void voiceSlices;", " void ptrs;", " void stereoOut;", " void stereoTail;", @@ -1189,6 +1202,25 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { controlActivityInterfaceMatch[2].includes("`ReverbConfig.brightnessHz`"), ); + const telemetryInterfaceMatch = + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export interface Telemetry \{([\s\S]*?)\n\}/.exec( + dts, + ); + assert.ok(telemetryInterfaceMatch, "Expected Telemetry interface"); + const telemetryDoc = extractJsDocBlocks( + telemetryInterfaceMatch[1], + )[0].replace(/\s+/g, " "); + assert.ok(telemetryDoc.includes("`Tunelet.telemetry`")); + assert.ok(telemetryDoc.includes("`Tunelet.takeTelemetry`")); + assert.ok(!telemetryDoc.includes("`Default`")); + assert.ok(telemetryInterfaceMatch[2].includes("`Feedback.resampleRatio`")); + assert.ok(telemetryInterfaceMatch[2].includes("`Feedback.periodSamples`")); + assert.ok(telemetryInterfaceMatch[2].includes("`Feedback.frequencyHz`")); + assert.ok(telemetryInterfaceMatch[2].includes("`Feedback.targetMidiNote`")); + assert.ok(telemetryInterfaceMatch[2].includes("`periodSamples`")); + assert.ok(telemetryInterfaceMatch[2].includes("voiceRatios: Float32Array;")); + assert.ok(telemetryInterfaceMatch[2].includes("voiceGains: Float32Array;")); + const latencyDoc = extractMemberJsDoc( dts, /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+readonly latencyFrames: number;/, diff --git a/src/lib.rs b/src/lib.rs index 171bca7..5dab237 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,12 +69,12 @@ //! [`Processor::control_activity`] and [`ProcessorConfig::control_activity`] //! give [`ControlActivity`], which shows the active choir, harmony and reverb //! controls. [`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. In mono calls, the feedback and -//! telemetry peaks measure the audio after the downmix. -//! [`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. +//! pitch, the voice ratios and gains, the peaks, the clarity and the effect +//! state. In mono calls, the feedback and telemetry peaks measure the audio +//! after the downmix. [`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 c728916..343e093 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -540,14 +540,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); @@ -557,6 +558,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, @@ -1016,21 +1022,22 @@ 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 /// [`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::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Deserialize, tsify::Tsify), serde(rename_all = "camelCase"), tsify(large_number_types_as_bigints) )] @@ -1057,12 +1064,46 @@ pub struct Telemetry { /// measure the wet signal after the downmix. 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 @@ -1081,7 +1122,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). @@ -1091,7 +1138,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 effective linear gain of Punch at the current envelope level. /// @@ -1124,3 +1177,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 6bb06fa..4cfefd8 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -54,10 +54,11 @@ use crate::{ ControlActivity, ControlEvent, Error, Feedback, MidiEvent, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Array, Float32Array, Int16Array, Reflect}; +use js_sys::{Array, Float32Array, Int16Array, Object, Reflect}; use serde::{Deserialize, Serialize}; use tsify::{serde_wasm_bindgen, Ts, Tsify}; use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; /// The events for one call that processes audio (`TimedEvent[]` in TypeScript). /// @@ -707,16 +708,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. @@ -730,7 +733,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) } @@ -1061,3 +1064,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) +}