From 99164e6c4b47991eb90bba3144d9c675295d8577 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 05:13:56 +0000 Subject: [PATCH 1/2] feat: add control activity queries and fix telemetry - Add ControlActivity queries in Rust, Wasm and TypeScript - Scale harmony voice gains by harmony_gain and count active voices - Extend pitch acquisition to 305 lags for 40 Hz fundamentals - Enforce PitchConfig frequency bounds on pitch state and correction - Rebuild active formant synthesis banks when width or stretch changes - Read formant_generation from the active playback stamp - Document control activity, telemetry and formant envelopes --- README.md | 49 +++++++++++----- src/config.rs | 123 +++++++++++++++++++++++++++++++++++++++- src/formant.rs | 132 ++++++++++++++++++++++++++++--------------- src/index.ts | 3 +- src/lib.rs | 25 ++++---- src/pitch.rs | 39 +++++++++---- src/pitch/tracker.rs | 13 +++-- src/processor.rs | 71 ++++++++++++++--------- src/resynthesis.rs | 83 ++++++++++++++++++++------- src/wasm.rs | 31 +++++++--- 10 files changed, 424 insertions(+), 145 deletions(-) diff --git a/README.md b/README.md index 83a8f47..a43888c 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,7 @@ These calls read the state of the processor. They do not change the audio. | Call | Data | | -------------------- | ----------------------------------------------------------------- | +| `control_activity()` | Which choir, harmony and reverb controls are active | | `feedback()` | The pitch, the stereo peak, the correction ratio, the frame count | | `take_feedback()` | The same data as `feedback()`, and clears the peak window | | `telemetry()` | Data for meters and displays (refer to the list below) | @@ -302,13 +303,24 @@ These calls read the state of the processor. They do not change the audio. | `latency_frames()` | 1,593 frames of nominal resynthesis latency at both sample rates | | `formant_envelope()` | The LPC envelopes before and after the formant controls | +`Processor::control_activity()` and `ProcessorConfig::control_activity()` +return a `ControlActivity` struct. A `false` flag means that the related +control makes no sample change in the active voice mode, harmony source or +reverb network. + The telemetry includes these items: -- The pitch ratio and the gain of each voice. +- The active voice count, the pitch ratio and the gain of each voice. In + Harmony mode, `voice_gains` includes `harmony_gain`, and `voice_count` is 1 + plus the number of harmony voices with a positive gain. - 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 pitch tracking flag and the pitch clarity, from 0 to 1, inside the + frequency bounds of `resynthesis.pitch`. - The current gains of Punch and Warm, and the position in the Alien loop. +- The generation of the active formant model, `formant_generation`. It + increases when playback reaches a new analysis bank and when `width` or + `stretch` changes. 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 @@ -317,11 +329,13 @@ have different timing. `formant_envelope()` writes two LPC envelopes into slices of equal length: - The vocal-tract envelope from the analysis. -- The envelope after the width and stretch controls. +- The envelope after the current `width` and `stretch` controls. -The values are linear and have no absolute level. The formant stage must be -enabled. The envelopes are those of the model that the audio used for the -last frame. The method returns `Result`: +A change to `width` or `stretch` updates the output envelope immediately, +also before the next audio block. The values are linear and have no absolute +level. The formant stage must be enabled. The envelopes are those of the +model that the audio used for the last frame. The method returns +`Result`: | Result | Description | | ----------- | ---------------------------------------------------------------- | @@ -419,6 +433,7 @@ page that opens the JavaScript. | Mono PCM to planar stereo | `process(input, left, right, events?)` | | In-place mono downmix | `processMono(audio, events?)` | | Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | +| Control activity | `controlActivity()` | | Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | | Feedback | `feedback()`, `takeFeedback()` | | Telemetry | `telemetry()`, `takeTelemetry()` | @@ -482,23 +497,29 @@ bindings. ### Feedback, telemetry and formant envelopes -`telemetry()` and `takeTelemetry()` return a `Telemetry` object. +`controlActivity()` returns a `ControlActivity` object with camelCase boolean +flags for the choir, harmony and reverb controls. `telemetry()` and +`takeTelemetry()` return a `Telemetry` object. In feedback, `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. -- The estimated frequency is outside the inclusive reporting bounds +- The estimated frequency is outside the inclusive frequency bounds `resynthesis.pitch.minFrequencyHz` and `resynthesis.pitch.maxFrequencyHz`. +Estimates outside those bounds also bypass pitch correction. + `formantEnvelope(maxFrequencyHz, input, output)` fills two `Float32Array` buffers of equal length and returns `false` if no envelope is available. -In that case, it fills both buffers with zeros. If the lengths are not equal -or the frequency is not valid, it throws and does not change the buffers. The -frequency must be finite, more than zero and not more than half of the sample -rate. The class keeps a buffer for the points, so only the first call and a -call with more points than before reserve memory. +In that case, it fills both buffers with zeros. A change to `width` or +`stretch` updates `output` immediately, also before the next audio block. If +the lengths are not equal or the frequency is not valid, the method throws +and does not change the buffers. The frequency must be finite, more than zero +and not more than half of the sample rate. The class keeps a buffer for the +points, so only the first call and a call with more points than before +reserve memory. ### Memory allocation @@ -510,7 +531,7 @@ Wasm. These items can allocate: - Object conversion. - Supplied events. - Errors. -- Feedback and telemetry. +- Control activity, feedback and telemetry. - The formant envelopes. The generated glue can also make temporary views. This binding is for general diff --git a/src/config.rs b/src/config.rs index 75bcd82..12fe773 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,9 +2,11 @@ use crate::effects::alien::AlienConfig; use crate::effects::punch::PunchConfig; -use crate::effects::reverb::ReverbConfig; +use crate::effects::reverb::{ReverbConfig, ReverbMode}; use crate::effects::warm::WarmConfig; use crate::error::{check_range, ConfigProblem}; +use crate::harmony::HarmonySource; +use crate::resynthesis::MultiVoiceMode; use crate::Error; use crate::ResynthesisConfig; use std::num::NonZeroUsize; @@ -203,6 +205,125 @@ impl ProcessorConfig { self.reverb.validate()?; validate_output_gain(self.output_gain) } + + /// Returns which choir, harmony and reverb controls change the audio in + /// the active modes. + /// + /// A `false` flag means that the related control makes no sample change in + /// the active voice mode, harmony source or reverb network. This method + /// does not allocate memory and does not validate ranges. + pub fn control_activity(self) -> ControlActivity { + let choir = self.resynthesis.mode == MultiVoiceMode::Choir; + let multi_choir = choir && self.resynthesis.choir_voices > 1; + let harmony = self.resynthesis.mode == MultiVoiceMode::Harmony; + let source = self.resynthesis.harmony.source; + let interval = matches!( + source, + HarmonySource::FixedInterval | HarmonySource::SmartInterval + ); + let interval_voices = self.resynthesis.harmony.voices > 0; + let named_or_degree = matches!( + source, + HarmonySource::ChordByDegree | HarmonySource::ChordByName + ); + let chord = named_or_degree || source == HarmonySource::ChordViaMidi; + let reverb = self.reverb.enabled; + let reverb_mode = self.reverb.mode; + ControlActivity { + choir_voices: choir, + choir_detune: multi_choir, + choir_delay: multi_choir, + choir_spread_percent: multi_choir && self.resynthesis.stereo_output, + harmony_source: harmony, + harmony_key: harmony + && ((source == HarmonySource::SmartInterval && interval_voices) || named_or_degree), + harmony_scale: harmony + && ((source == HarmonySource::SmartInterval && interval_voices) + || source == HarmonySource::ChordByDegree), + harmony_chromatic_intervals: harmony + && source == HarmonySource::FixedInterval + && interval_voices, + harmony_diatonic_intervals: harmony + && source == HarmonySource::SmartInterval + && interval_voices, + harmony_chord: harmony && source == HarmonySource::ChordByName, + harmony_degree: harmony && source == HarmonySource::ChordByDegree, + harmony_inversion: harmony && named_or_degree, + harmony_register_percent: harmony && chord, + harmony_voicing_spread_percent: harmony && chord, + harmony_portamento_ms: harmony && (!interval || interval_voices), + harmony_voices: harmony && interval, + harmony_gain: harmony && (!interval || interval_voices), + reverb_mode: reverb, + reverb_mix: reverb, + reverb_diffusion: reverb + && !matches!(reverb_mode, ReverbMode::Schroeder | ReverbMode::SmallRoom), + reverb_decay: reverb && reverb_mode != ReverbMode::Binaural, + reverb_brightness_hz: reverb + && !matches!(reverb_mode, ReverbMode::Echo | ReverbMode::Schroeder), + } + } +} + +/// Flags that show which choir, harmony and reverb controls are active in a +/// [`ProcessorConfig`]. +/// +/// Get this snapshot from [`ProcessorConfig::control_activity`] or +/// [`crate::Processor::control_activity`]. A `false` flag means that the +/// related control produces no sample change in the current voice mode, +/// harmony source or reverb network. `Default` sets all flags to `false`. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub struct ControlActivity { + /// `true` if [`ResynthesisConfig::choir_voices`] is active. + pub choir_voices: bool, + /// `true` if [`ResynthesisConfig::choir_detune`] is active. + pub choir_detune: bool, + /// `true` if [`ResynthesisConfig::choir_delay`] is active. + pub choir_delay: bool, + /// `true` if [`ResynthesisConfig::choir_spread_percent`] is active. + pub choir_spread_percent: bool, + /// `true` if [`crate::HarmonyConfig::source`] is active. + pub harmony_source: bool, + /// `true` if [`crate::HarmonyConfig::key`] is active. + pub harmony_key: bool, + /// `true` if [`crate::HarmonyConfig::scale`] is active. + pub harmony_scale: bool, + /// `true` if [`crate::HarmonyConfig::chromatic_intervals`] is active. + pub harmony_chromatic_intervals: bool, + /// `true` if [`crate::HarmonyConfig::diatonic_intervals`] is active. + pub harmony_diatonic_intervals: bool, + /// `true` if [`crate::HarmonyConfig::chord`] is active. + pub harmony_chord: bool, + /// `true` if [`crate::HarmonyConfig::degree`] is active. + pub harmony_degree: bool, + /// `true` if [`crate::HarmonyConfig::inversion`] is active. + pub harmony_inversion: bool, + /// `true` if [`crate::HarmonyConfig::register_percent`] is active. + pub harmony_register_percent: bool, + /// `true` if [`crate::HarmonyConfig::voicing_spread_percent`] is active. + pub harmony_voicing_spread_percent: bool, + /// `true` if [`crate::HarmonyConfig::portamento_ms`] is active. + pub harmony_portamento_ms: bool, + /// `true` if [`crate::HarmonyConfig::voices`] is active. + pub harmony_voices: bool, + /// `true` if [`ResynthesisConfig::harmony_gain`] is active. + pub harmony_gain: bool, + /// `true` if [`ReverbConfig::mode`] is active. + pub reverb_mode: bool, + /// `true` if [`ReverbConfig::mix`] is active. + pub reverb_mix: bool, + /// `true` if [`ReverbConfig::diffusion`] is active. + pub reverb_diffusion: bool, + /// `true` if [`ReverbConfig::decay`] is active. + pub reverb_decay: bool, + /// `true` if [`ReverbConfig::brightness_hz`] is active. + pub reverb_brightness_hz: bool, } /// Checks the output gain range. diff --git a/src/formant.rs b/src/formant.rs index bf9ee5a..2b5bc2f 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -164,12 +164,18 @@ pub(crate) struct Formant { temporary: Vec, /// The Q14 coefficient banks for the inverse filter. inverse: Vec<[i32; ORDER]>, + /// The Q14 reflection coefficients of each bank, for synthesis rebuilds. + parcor: Vec<[i32; ORDER]>, + /// `true` for each bank where the Durbin analysis succeeded. + valid_parcor: [bool; BANKS], /// The Q14 coefficient banks for the forward filter. `orders` holds the /// active lengths. models: Vec<[i32; MAX_ORDER]>, /// The valid synthesis order for each bank. Zero means that there is no /// feedback model. orders: [usize; BANKS], + /// The analysis generation of each bank. + generations: [u32; BANKS], /// One record of a bank pair and a blend for each frame of input history. stamps: Vec, /// The index of the current coefficient bank. @@ -233,9 +239,10 @@ pub(crate) struct Formant { /// The Q14 compensation, from the aspiration cutoff divided by the /// sample rate. noise_amplitude: i32, - /// The wrapping count of model designs that the stage tried. Only the - /// telemetry reads it. + /// The wrapping count of model designs that the stage tried. generation: u32, + /// The wrapping count of live width or stretch edits while enabled. + edit_generation: u32, } /// Multiplies `coefficients` with the samples before `index` in `ring`. @@ -272,8 +279,11 @@ impl Formant { input: vec![0; HISTORY_FRAMES], temporary: vec![0_i32; (2 * (rate.as_u32() as usize / 40) + MAX_ORDER + 256).max(2865)], inverse: vec![[0; ORDER]; BANKS], + parcor: vec![[0; ORDER]; BANKS], + valid_parcor: [false; BANKS], models: vec![[0; MAX_ORDER]; BANKS], orders: [0; BANKS], + generations: [0; BANKS], stamps: vec![Stamp::default(); HISTORY_FRAMES], current: 1, previous: 0, @@ -299,17 +309,21 @@ impl Formant { noise_gain: 0_i32, noise_amplitude: 0_i32, generation: 0, + edit_generation: 0, }; result.set_config(config); result } /// Quantizes the validated controls, prepares the Q7 map for the area - /// interpolation and updates the coefficients of the aspiration filter. + /// interpolation, rebuilds active synthesis models when width or stretch + /// changes, and updates the coefficients of the aspiration filter. /// - /// The histories do not change. A valid stretch gives a model with 25 to - /// 99 entries. Thus, the last point of the map and the denominators of - /// the interpolation are always defined. + /// The audio histories do not change. A valid stretch gives a model with + /// 25 to 99 entries. Thus, the last point of the map and the denominators + /// of the interpolation are always defined. pub(crate) fn set_config(&mut self, config: FormantConfig) { + let model_changed = + self.config.width != config.width || self.config.stretch != config.stretch; self.config = config; self.width = (config.width as f64 * 16384.0) as i32; self.width_squared = (config.width as f64 * config.width as f64 * 16384.0) as i32; @@ -321,6 +335,16 @@ impl Formant { self.stretch_map[i] = ((ORDER - 1) as f64 * fraction * 128.0) as i32; } self.stretch_map[self.stretch_count - 1] = ((ORDER - 1) * 128) as i32; + if model_changed { + for bank in 0..BANKS { + if self.valid_parcor[bank] { + self.build_model(bank); + } + } + if config.enabled { + self.edit_generation = self.edit_generation.wrapping_add(1); + } + } self.noise_gain = (config.aspiration_mix as f64 * 16384.0) as i32; let frequency = (config.aspiration_cutoff_hz as i32) .min((self.rate.hz() as f64 * 0.48) as i32) @@ -347,7 +371,9 @@ impl Formant { self.history_index = 0; self.current = BANKS - 1; self.next_filter(); + self.generations[0] = self.generation; self.next_filter(); + self.generations[1] = self.generation; self.design_counter = 0; self.noise_filter.reset(); self.smooth_reset = true; @@ -410,9 +436,54 @@ impl Formant { } self.blend = 0; self.inverse[self.current].fill(0_i32); - + self.parcor[self.current].fill(0_i32); + self.valid_parcor[self.current] = false; self.models[self.current].fill(0_i32); self.orders[self.current] = 0; + self.generations[self.current] = 0; + } + + /// Builds the synthesis filter for `bank` from its kept reflection and + /// inverse coefficients and the current width and stretch controls. + fn build_model(&mut self, bank: usize) { + let one = 16384; + self.models[bank].fill(0_i32); + self.orders[bank] = 0; + if self.width != one || self.stretch != one { + if let Some(scale) = lpc::parcor_to_areas(&self.parcor[bank], &mut self.areas) { + for i in 0..self.stretch_count { + let map = self.stretch_map[i]; + let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; + let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); + self.stretched_areas[i] = mul14( + mul14(one.wrapping_sub(fraction), self.areas[index]) + .wrapping_add(mul14(fraction, self.areas[index + 1])), + self.width_squared, + ); + if self.stretched_areas[i] == 0_i32 { + self.stretched_areas[i] = 1; + } + } + let mut stretched_parcor = [0_i32; MAX_ORDER]; + let mut scratch = [0_i32; 112]; + if lpc::areas_to_parcor( + &self.stretched_areas[..self.stretch_count], + &mut stretched_parcor, + scale, + ) { + lpc::parcor_to_pef( + &stretched_parcor[..self.stretch_count], + &mut self.models[bank], + &mut scratch, + 14, + ); + self.orders[bank] = self.stretch_count; + } + } + } else { + self.models[bank][..ORDER].copy_from_slice(&self.inverse[bank]); + self.orders[bank] = ORDER; + } } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. @@ -602,52 +673,21 @@ impl Formant { // order stays zero until all necessary model changes complete. self.next_filter(); self.generation = self.generation.wrapping_add(1); + self.generations[self.current] = self.generation; let design_gain = ((db_to_gain(-60.0) + 1.0) * 16384.0) as i32; correlations[0] = mul14(correlations[0], design_gain).wrapping_add(200); - let mut parcor = [0; MAX_ORDER]; let mut scratch = [0; 112]; let valid = lpc::durbin( &correlations, &mut self.inverse[self.current], - &mut parcor, + &mut self.parcor[self.current], &mut scratch, ); + self.valid_parcor[self.current] = valid; if valid { - if self.width != one || self.stretch != one { - if let Some(scale) = lpc::parcor_to_areas(&parcor[..ORDER], &mut self.areas) { - for i in 0..self.stretch_count { - let map = self.stretch_map[i]; - let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; - let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); - self.stretched_areas[i] = mul14( - mul14(one.wrapping_sub(fraction), self.areas[index]) - .wrapping_add(mul14(fraction, self.areas[index + 1])), - self.width_squared, - ); - if self.stretched_areas[i] == 0_i32 { - self.stretched_areas[i] = 1; - } - } - if lpc::areas_to_parcor( - &self.stretched_areas[..self.stretch_count], - &mut parcor, - scale, - ) { - lpc::parcor_to_pef( - &parcor[..self.stretch_count], - &mut self.models[self.current], - &mut scratch, - 14, - ); - self.orders[self.current] = self.stretch_count; - } - } - } else { - self.models[self.current][..ORDER].copy_from_slice(&self.inverse[self.current]); - self.orders[self.current] = ORDER; - } + self.build_model(self.current); } else { self.smooth_reset = true; } @@ -740,9 +780,11 @@ impl Formant { } &output[..order] } - /// Returns the wrapping count of model designs that the stage tried. - pub(crate) fn generation(&self) -> u32 { - self.generation + /// Returns the wrapping generation of the model stamp at a signed history + /// frame, plus any live width or stretch edits. + pub(crate) fn generation(&self, position: i32) -> u32 { + let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; + self.generations[usize::from(stamp.current)].wrapping_add(self.edit_generation) } /// Finds and blends the analysis coefficients of the stamp at a signed /// history frame, in the same way as [`Self::coefficients`]. diff --git a/src/index.ts b/src/index.ts index 8526d77..0390391 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,7 +5,8 @@ * configuration. Both environments use the same generated bindings and the * same Wasm binary. This module re-exports all named exports of the module * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * `initSync` and the configuration, control-activity, event, feedback and + * telemetry types. */ import init from "../pkg/tunelet.js"; import type { InitInput, InitOutput } from "../pkg/tunelet.js"; diff --git a/src/lib.rs b/src/lib.rs index f17bc85..e2a856f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,17 +51,18 @@ //! [`Processor::feedback`] gives the pitch, the correction ratio, the //! accumulated stereo peak and the frame count. //! [`Processor::take_feedback`] also clears the peak window. The pitch -//! reporting bounds change only the reports. They do not change the detection -//! or the audio signal. [`Processor::latency_frames`] gives a nominal -//! 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. +//! frequency bounds filter the reports, the tracking state and the pitch +//! correction. [`Processor::latency_frames`] gives a nominal resynthesis +//! delay. Voice delays, pitch changes and effects have their own timing. +//! +//! [`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. [`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 @@ -121,7 +122,7 @@ mod scale; #[cfg(all(feature = "wasm", target_arch = "wasm32"))] pub mod wasm; -pub use config::{PrepareConfig, ProcessorConfig, SampleRate}; +pub use config::{ControlActivity, PrepareConfig, ProcessorConfig, SampleRate}; pub use effects::alien::AlienConfig; pub use effects::punch::PunchConfig; pub use effects::reverb::{ReverbConfig, ReverbMode}; diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..9b6e65d 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -2,16 +2,18 @@ //! estimates. //! //! Acquisition checks that repeated minima agree. Tracking refines the period -//! in a window of 40 lags. The reporting bounds filter only the feedback to -//! the host. +//! in a window of 40 lags. The frequency bounds filter the feedback, the +//! tracking state and the pitch correction. mod search; pub(crate) mod tracker; use crate::error::{check_range, ConfigProblem}; -use crate::Error; +use crate::numeric::fixed::Q6; +use crate::{Error, SampleRate}; -/// The acquisition sensitivity and the bounds for pitch reports to the host. +/// The acquisition sensitivity and the frequency bounds for pitch tracking and +/// correction. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -26,18 +28,20 @@ pub struct PitchConfig { /// This value controls acquisition. It is not an output gain or an /// amplitude gate. pub threshold: f32, - /// The lower bound of the feedback in hertz (inclusive), 40..=2000. + /// The lower bound of tracked pitch in hertz (inclusive), 40..=2000. /// /// The default is 40. It must be strictly less than `max_frequency_hz`. - /// These bounds do not change the tracking, the correction or the - /// resampling. A feedback query applies the current bounds to the kept - /// analysis. It does not process another sample. + /// Estimates outside the inclusive bounds are reported as unvoiced and + /// untracked, and they bypass pitch correction. A feedback query applies + /// the current bounds to the kept analysis and does not process another + /// sample. pub min_frequency_hz: f32, - /// The upper bound of the feedback in hertz (inclusive), 40..=2000. + /// The upper bound of tracked pitch in hertz (inclusive), 40..=2000. /// /// The default is 1100. It must be strictly greater than - /// `min_frequency_hz`. Results outside the bounds are reported as - /// unvoiced, with zero frequency and zero period. + /// `min_frequency_hz`. Estimates outside the inclusive bounds are reported + /// as unvoiced and untracked, with zero frequency and zero period, and + /// they bypass pitch correction. pub max_frequency_hz: f32, } @@ -52,7 +56,18 @@ impl Default for PitchConfig { } impl PitchConfig { - /// Applies only the bounds for host reports to a kept estimate. + /// Returns `true` if `period` gives a frequency inside the inclusive + /// bounds at `rate`. + pub(crate) fn contains_period(self, rate: SampleRate, period: Q6) -> bool { + if period <= Q6::ZERO { + return false; + } + let period_samples = (period.to_bits() as f64 / 64.0) as f32; + let frequency_hz = rate.hz() / period_samples; + frequency_hz >= self.min_frequency_hz && frequency_hz <= self.max_frequency_hz + } + + /// Applies the frequency bounds for host reports to a kept estimate. /// /// If the estimate is not voiced or is out of range, the result is the /// unvoiced value with all fields zero. The function does not change the diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index c46ed9b..f3dbba0 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -10,8 +10,8 @@ //! The 40-lag window moves to keep the minimum near its center. If the //! minimum is at a boundary or the curvature is not usable, acquisition //! starts again. The last usable period stays available as a fallback for -//! resynthesis. The public frequency bounds apply only to feedback reports. -//! They do not change the size of these windows. +//! resynthesis. Resynthesis enforces the public frequency bounds. They do not +//! change the size of these windows. use super::search::{tracking_minimum, TRACKING_LAGS}; use crate::filter::{Biquad, Design}; @@ -44,7 +44,7 @@ pub(crate) struct PitchStep { } /// The number of lags that acquisition compares. -const ACQUISITION_LAGS: usize = 137; +const ACQUISITION_LAGS: usize = 305; /// The two-stage pitch tracker. /// @@ -178,6 +178,11 @@ impl PitchTracker { self.detecting } + /// Returns the latest refined Q6 period, or zero during acquisition. + pub(crate) fn period(&self) -> Q6 { + self.period + } + /// Returns how periodic the tracked input is at the last refined lag, /// from 0 to 1. /// @@ -321,7 +326,7 @@ impl PitchTracker { &mut self.cross[lag..end], ); index1 = if count == index1 + 1 { - 273 + 2 * ACQUISITION_LAGS - 1 } else { index1 - count }; diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..e539cd3 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -8,7 +8,7 @@ use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ControlActivity, ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -319,6 +319,16 @@ impl Processor { self.config } + /// Returns which choir, harmony and reverb controls change the audio in + /// the current configuration. + /// + /// A `false` flag means that the related control makes no sample change in + /// the active voice mode, harmony source or reverb network. This method + /// does not allocate memory and does not change state. + pub fn control_activity(&self) -> ControlActivity { + self.config.control_activity() + } + /// Returns the nominal resynthesis latency: 1,593 frames at both rates. /// /// The dry path has a delay of 1,543 frames. Resampled voices, choir delays @@ -411,10 +421,12 @@ impl Processor { /// last frame. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the width and stretch controls. Point - /// `k` of `n` is at the frequency `max_frequency_hz * k / (n - 1)`. The - /// values are linear magnitudes. They have no absolute level, because the - /// analysis normalizes the signal energy. Scale them for a display. + /// `output` gets the envelope after the current width and stretch + /// controls. A change to width or stretch updates `output` immediately, + /// also before the next audio block. Point `k` of `n` is at the frequency + /// `max_frequency_hz * k / (n - 1)`. The values are linear magnitudes. + /// They have no absolute level, because the analysis normalizes the signal + /// energy. Scale them for a display. /// /// `max_frequency_hz` must be finite, more than zero and not more than /// half of the sample rate. The two slices must have the same length. @@ -725,7 +737,7 @@ pub struct Feedback { pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// - /// It is zero if the input is unvoiced or outside the reporting bounds of + /// It is zero if the input is unvoiced or outside the frequency bounds of /// [`crate::PitchConfig`]. pub period_samples: f32, /// The reported input pitch frequency in hertz. @@ -749,11 +761,11 @@ pub struct Feedback { /// /// The value is `None` if [`voiced`](Self::voiced) is `false`, and only /// then. This occurs if the input is unvoiced or if its frequency is - /// outside the current reporting bounds. A target table that has no + /// outside the current frequency bounds. A target table that has no /// selected target does not give `None`. pub target_midi_note: Option, /// This field is `true` if the current pitch estimate is positive and - /// inside the current reporting bounds. + /// inside the current frequency bounds. /// /// This is not an amplitude gate or a confidence score. A tracking result /// can stay between detector updates. @@ -822,38 +834,40 @@ pub struct Telemetry { /// 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 + /// period. It is 0 for a signal with no relation between cycles, during + /// pitch acquisition and outside the frequency bounds of + /// [`crate::PitchConfig`]. Use it as a confidence score for /// [`Feedback::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 - /// `false` during pitch acquisition. + /// This field is `true` if the pitch tracker follows a period inside the + /// frequency bounds of [`crate::PitchConfig`]. It is `false` during pitch + /// acquisition and outside those bounds. pub tracking: bool, - /// The number of valid entries in [`voice_ratios`](Self::voice_ratios) - /// and [`voice_gains`](Self::voice_gains). + /// The number of active voices. /// - /// The value is 5 in Harmony mode. In Choir mode, it is + /// In Harmony mode, the value is 1 plus the number of harmony voices with + /// a positive gain, in 1..=5. In Choir mode, it is /// [`crate::ResynthesisConfig::choir_voices`], in 1..=16. pub voice_count: u8, /// The pitch ratio of each voice on the last frame, where 1 is the input /// pitch. /// /// Entry zero is the lead voice. In Harmony mode, entries 1 to 4 are the - /// 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. + /// four harmony voice slots, and entries 5 to 15 are zero. In Choir mode, + /// the entries after the lead are the secondary voices, and the entries + /// after [`voice_count`](Self::voice_count) are zero. Each ratio includes + /// the correction, the configured pitch shift and the ratio of the voice. pub voice_ratios: [f32; 16], /// The linear gain of each voice, in the order of /// [`voice_ratios`](Self::voice_ratios). /// /// The lead and the choir voices have a gain of 1. The gain of a harmony - /// voice includes the MIDI velocity gain, in 0..=3.98095703125. MIDI - /// 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. + /// voice includes [`crate::ResynthesisConfig::harmony_gain`] and the MIDI + /// velocity gain, in 0..=3.98095703125. MIDI velocity 127 at unity + /// `harmony_gain` gives the maximum, approximately +12 dB. The gain is + /// zero for a voice that does not sound. It does not include the stereo + /// pan. The harmony controller updates its envelope every 101 frames. pub voice_gains: [f32; 16], /// The current drive of Punch, divided by its base drive. /// @@ -877,10 +891,11 @@ pub struct Telemetry { /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. pub alien_phase_frames: u32, - /// The wrapping count of formant analyses since construction. + /// The wrapping generation of the active formant synthesis model. /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if - /// [`Processor::formant_envelope`] can give a new result. + /// While the formant stage is enabled, the count increases when playback + /// reaches a new analysis bank and when width or stretch changes. Compare + /// two values to find if [`Processor::formant_envelope`] can give a new + /// result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..b2a0cf0 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -166,7 +166,7 @@ impl CorrectionConfig { tsify(large_number_types_as_bigints) )] pub struct ResynthesisConfig { - /// The acquisition sensitivity and the reporting bounds. The + /// The acquisition sensitivity and the pitch bounds. The /// default is [`PitchConfig::default`]. pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled @@ -434,8 +434,12 @@ pub(crate) struct Resynthesis { /// telemetry reads them. voice_ratios: [Q14; HARMONY_VOICES + 1], /// The signed history frame that the formant model used for the last - /// frame. The audio path sets it, and only the formant envelope reads it. + /// frame. The audio path sets it, and the formant telemetry and envelope + /// read it. formant_position: i32, + /// The last refined Q6 period inside the configured frequency bounds. An + /// audio reset keeps it. + kept_period: Q6, /// Two cascaded anti-alias filter sections. If the shift is not upward, /// they have coefficients of 1.0 and zero. post: [Biquad; 2], @@ -536,6 +540,7 @@ impl Resynthesis { harmony_gains: [Q12::ZERO; HARMONY_VOICES], voice_ratios: [Q14::ONE; HARMONY_VOICES + 1], formant_position: 0, + kept_period: Q6::ZERO, post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, correction_decay: Q14::ZERO, @@ -650,6 +655,12 @@ impl Resynthesis { let old = self.config; self.config = config; self.pitch.set_config(config.pitch); + if old.pitch != config.pitch + && !config.pitch.contains_period(self.rate, self.pitch.period()) + { + self.correction = Q14::ONE; + self.scale_initialized = false; + } self.formant.set_config(config.formant); self.harmony.apply_config(config.harmony); if old.correction.notes != config.correction.notes @@ -827,21 +838,30 @@ impl Resynthesis { /// Returns how periodic the tracked input is, from 0 to 1. Refer to /// `PitchTracker::clarity`. pub(crate) fn clarity(&self) -> f32 { - self.pitch.clarity() + if self.is_tracking() { + self.pitch.clarity() + } else { + 0.0 + } } - /// Returns `true` if the pitch tracker follows a period, and `false` - /// during acquisition. + /// Returns `true` if the pitch tracker follows a period inside the + /// configured frequency bounds, and `false` otherwise. pub(crate) fn is_tracking(&self) -> bool { !self.pitch.is_detecting() + && self + .config + .pitch + .contains_period(self.rate, self.pitch.period()) } /// Writes the effective ratio and the linear gain of each voice from the - /// last frame, and returns the number of voices. + /// last frame, and returns the number of active voices. /// /// Slot zero is the lead. In Harmony mode, slots 1 to 4 are the harmony - /// voices, and the gain is the envelope of the harmony controller. In - /// Choir mode, the slots after the lead are the secondary voices with a - /// gain of 1. Each ratio includes the correction, the global shift and - /// the ratio of the voice. The entries after the count do not change. + /// voices, the gain includes `harmony_gain`, and the returned count is 1 + /// plus the number of harmony voices with a positive gain. In Choir mode, + /// the slots after the lead are the secondary voices with a gain of 1. + /// Each ratio includes the correction, the global shift and the ratio of + /// the voice. pub(crate) fn voices(&self, ratios: &mut [f32; 16], gains: &mut [f32; 16]) -> u8 { let lead = (self.voice_ratios[0].to_bits() as f64 / 16384.0) as f32; ratios[0] = lead; @@ -855,17 +875,24 @@ impl Resynthesis { } count as u8 } else { + let mut active = 1; for voice in 0..HARMONY_VOICES { ratios[voice + 1] = (self.voice_ratios[voice + 1].to_bits() as f64 / 16384.0) as f32; - gains[voice + 1] = (self.harmony_gains[voice].to_bits() as f64 / 4096.0) as f32; + let gain = ((self.harmony_gains[voice].to_bits() as f64 / 4096.0) + * self.config.harmony_gain as f64) as f32; + gains[voice + 1] = gain; + if gain > 0.0 { + active += 1; + } } - (HARMONY_VOICES + 1) as u8 + active } } - /// Returns the wrapping count of formant model designs. + /// Returns the wrapping generation of the active formant stamp, plus any + /// live width or stretch edits. pub(crate) fn formant_generation(&self) -> u32 { - self.formant.generation() + self.formant.generation(self.formant_position) } /// Writes the formant envelopes of the model that the audio used for the /// last frame. Refer to `Formant::envelope`. @@ -894,9 +921,14 @@ impl Resynthesis { /// global shift is part of the normalization. /// /// If correction is disabled or the active table is empty, the ratio moves - /// toward 1.0. If the target selection starts again and the shifted - /// period is not positive, the ratio becomes 1.0 immediately. + /// toward 1.0. If the period is outside the configured frequency bounds or + /// the shifted period is not positive, the ratio becomes 1.0 immediately. fn update_correction(&mut self, period: Q6) { + if !self.config.pitch.contains_period(self.rate, period) { + self.correction = Q14::ONE; + self.scale_initialized = false; + return; + } let mut target_ratio = Q14::ONE; if self.config.correction.enabled && self.scale.count != 0 { let count = self.scale.count; @@ -1107,8 +1139,17 @@ impl Resynthesis { self.written += 1; } self.raw[self.write] = sample; - let was_tracking = !self.pitch.is_detecting(); + let was_tracking = !self.pitch.is_detecting() + && (self.pitch.period() == Q6::ZERO + || self + .config + .pitch + .contains_period(self.rate, self.pitch.period())); let step = self.pitch.process_sample(sample.to_bits()); + let in_bounds = self.config.pitch.contains_period(self.rate, step.period); + if in_bounds { + self.kept_period = step.period; + } let write = self.write; // Readers have signed fractional coordinates. When the writer wraps, // move the origin of these coordinates with it. Do not apply a modulo @@ -1125,7 +1166,7 @@ impl Resynthesis { } self.old_position = self.old_position - position_of(HISTORY as i32); } - if step.restarted { + if step.restarted || (step.period != Q6::ZERO && !in_bounds) { self.correction = Q14::ONE; self.scale_initialized = false; } @@ -1154,8 +1195,8 @@ impl Resynthesis { self.drift_ratio[0] = Q14::ONE; } } - self.periods[write] = step.period; - self.previous_periods[write] = step.previous_period; + self.periods[write] = if in_bounds { step.period } else { Q6::ZERO }; + self.previous_periods[write] = self.kept_period; self.ratios[write] = self.correction; self.overlap_index += 1; if self.overlap_index == OVERLAP_FRAMES { @@ -1168,7 +1209,7 @@ impl Resynthesis { previous.to_bits(), self.periods.as_slice(), write, - step.previous_period.to_bits(), + self.kept_period.to_bits(), )) } else { self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..5e7b9fa 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -32,7 +32,7 @@ //! //! - The decode of events. //! - The conversion of configurations. -//! - Feedback and telemetry objects. +//! - Feedback, control-activity and telemetry objects. //! - The buffers of the formant envelopes. //! - Errors. //! @@ -42,7 +42,8 @@ //! `free()` method. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + ControlActivity, Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, + Telemetry, TimedEvent, }; use js_sys::{Float32Array, Int16Array}; use serde::{Deserialize, Serialize}; @@ -366,7 +367,7 @@ impl WasmProcessor { /// /// - The kept pitch estimate is unvoiced. This includes the time before /// the first detection and after a reset or a drain completion. - /// - The estimated frequency is outside the inclusive reporting bounds + /// - The estimated frequency is outside the inclusive frequency bounds /// `minFrequencyHz` and `maxFrequencyHz` of the pitch configuration. /// /// # Errors @@ -392,6 +393,21 @@ impl WasmProcessor { Ok(feedback) } + /// Returns which choir, harmony and reverb controls change the audio in + /// the active configuration. + /// + /// A `false` flag means that the related control makes no sample change in + /// the current voice mode, harmony source or reverb network. The audio + /// state does not change. + /// + /// # Errors + /// + /// If the conversion to a JavaScript object fails, this method throws. + #[wasm_bindgen(js_name = controlActivity)] + pub fn control_activity(&self) -> Result, JsError> { + Ok(self.processor.control_activity().into_ts()?) + } + /// 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 @@ -426,10 +442,11 @@ impl WasmProcessor { /// `Float32Array` buffers of equal length. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the width and stretch controls. Point - /// `k` of `n` is at the frequency `maxFrequencyHz * k / (n - 1)`. The - /// values are linear magnitudes with no absolute level. Scale them for a - /// display. + /// `output` gets the envelope after the current width and stretch + /// controls. A change to width or stretch updates `output` immediately, + /// also before the next audio block. Point `k` of `n` is at the frequency + /// `maxFrequencyHz * k / (n - 1)`. The values are linear magnitudes with + /// no absolute level. Scale them for a display. /// /// `maxFrequencyHz` must be finite, more than zero and not more than half /// of the sample rate. From abffc6bb1c800f249df5bb2b78f7dfea17b2c1aa 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 09:23:29 +0000 Subject: [PATCH 2/2] refactor: keep only additive control activity queries - Revert resynthesis, formant and pitch changes to main. - Revert telemetry, feedback and formant documentation to main. - Keep ControlActivity queries in Rust, WebAssembly and TypeScript. --- README.md | 37 +++++------- src/config.rs | 8 +-- src/formant.rs | 132 +++++++++++++++---------------------------- src/index.ts | 4 +- src/lib.rs | 15 +++-- src/pitch.rs | 39 ++++--------- src/pitch/tracker.rs | 13 ++--- src/processor.rs | 59 +++++++++---------- src/resynthesis.rs | 84 +++++++-------------------- src/wasm.rs | 13 ++--- 10 files changed, 141 insertions(+), 263 deletions(-) diff --git a/README.md b/README.md index c3361c3..e26cfd7 100644 --- a/README.md +++ b/README.md @@ -311,17 +311,11 @@ reverb network. The telemetry includes these items: -- The active voice count, the pitch ratio and the gain of each voice. In - Harmony mode, `voice_gains` includes `harmony_gain`, and `voice_count` is 1 - plus the number of harmony voices with a positive gain. +- The pitch ratio and the gain of each voice. - The peaks of the input, of the two output channels and of the reverb wet signal. -- The pitch tracking flag and the pitch clarity, from 0 to 1, inside the - frequency bounds of `resynthesis.pitch`. +- 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 generation of the active formant model, `formant_generation`. It - increases when playback reaches a new analysis bank and when `width` or - `stretch` changes. 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 @@ -331,13 +325,11 @@ choir delays and effects use different delays. `formant_envelope()` writes two LPC envelopes into slices of equal length: - The vocal-tract envelope from the analysis. -- The envelope after the current `width` and `stretch` controls. +- The envelope after the width and stretch controls. -A change to `width` or `stretch` updates the output envelope immediately, -also before the next audio block. The values are linear and have no absolute -level. The formant stage must be enabled. The envelopes are those of the -model that the audio used for the last frame. The method returns -`Result`: +The values are linear and have no absolute level. The formant stage must be +enabled. The envelopes are those of the model that the audio used for the +last frame. The method returns `Result`: | Result | Description | | ----------- | ---------------------------------------------------------------- | @@ -352,6 +344,7 @@ allocate memory, acquire locks or do I/O: - Processing - Configuration +- Control activity - MIDI - Feedback - Telemetry @@ -508,20 +501,16 @@ 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. -- The estimated frequency is outside the inclusive frequency bounds +- The estimated frequency is outside the inclusive reporting bounds `resynthesis.pitch.minFrequencyHz` and `resynthesis.pitch.maxFrequencyHz`. -Estimates outside those bounds also bypass pitch correction. - `formantEnvelope(maxFrequencyHz, input, output)` fills two `Float32Array` buffers of equal length and returns `false` if no envelope is available. -In that case, it fills both buffers with zeros. A change to `width` or -`stretch` updates `output` immediately, also before the next audio block. If -the lengths are not equal or the frequency is not valid, the method throws -and does not change the buffers. The frequency must be finite, more than zero -and not more than half of the sample rate. The class keeps a buffer for the -points, so only the first call and a call with more points than before -reserve memory. +In that case, it fills both buffers with zeros. If the lengths are not equal +or the frequency is not valid, it throws and does not change the buffers. The +frequency must be finite, more than zero and not more than half of the sample +rate. The class keeps a buffer for the points, so only the first call and a +call with more points than before reserve memory. ### Memory allocation diff --git a/src/config.rs b/src/config.rs index 12fe773..741d08c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -265,13 +265,13 @@ impl ProcessorConfig { } } -/// Flags that show which choir, harmony and reverb controls are active in a -/// [`ProcessorConfig`]. +/// The flags that show which choir, harmony and reverb controls are active in +/// a [`ProcessorConfig`]. /// /// Get this snapshot from [`ProcessorConfig::control_activity`] or /// [`crate::Processor::control_activity`]. A `false` flag means that the -/// related control produces no sample change in the current voice mode, -/// harmony source or reverb network. `Default` sets all flags to `false`. +/// related control makes no sample change in the active voice mode, harmony +/// source or reverb network. `Default` sets all flags to `false`. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[non_exhaustive] #[cfg_attr( diff --git a/src/formant.rs b/src/formant.rs index 2455baf..7c59008 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -164,18 +164,12 @@ pub(crate) struct Formant { temporary: Vec, /// The Q14 coefficient banks for the inverse filter. inverse: Vec<[i32; ORDER]>, - /// The Q14 reflection coefficients of each bank, for synthesis rebuilds. - parcor: Vec<[i32; ORDER]>, - /// `true` for each bank where the Durbin analysis succeeded. - valid_parcor: [bool; BANKS], /// The Q14 coefficient banks for the forward filter. `orders` holds the /// active lengths. models: Vec<[i32; MAX_ORDER]>, /// The valid synthesis order for each bank. Zero means that there is no /// feedback model. orders: [usize; BANKS], - /// The analysis generation of each bank. - generations: [u32; BANKS], /// One record of a bank pair and a blend for each frame of input history. stamps: Vec, /// The index of the current coefficient bank. @@ -239,10 +233,9 @@ pub(crate) struct Formant { /// The Q14 compensation, from the aspiration cutoff divided by the /// sample rate. noise_amplitude: i32, - /// The wrapping count of model designs that the stage tried. + /// The wrapping count of model designs that the stage tried. Only the + /// telemetry reads it. generation: u32, - /// The wrapping count of live width or stretch edits while enabled. - edit_generation: u32, } /// Multiplies `coefficients` with `samples` in tap order and returns the @@ -272,11 +265,8 @@ impl Formant { input: vec![0; HISTORY_FRAMES + ORDER], temporary: vec![0_i32; (2 * (rate.as_u32() as usize / 40) + MAX_ORDER + 256).max(2865)], inverse: vec![[0; ORDER]; BANKS], - parcor: vec![[0; ORDER]; BANKS], - valid_parcor: [false; BANKS], models: vec![[0; MAX_ORDER]; BANKS], orders: [0; BANKS], - generations: [0; BANKS], stamps: vec![Stamp::default(); HISTORY_FRAMES], current: 1, previous: 0, @@ -302,21 +292,17 @@ impl Formant { noise_gain: 0_i32, noise_amplitude: 0_i32, generation: 0, - edit_generation: 0, }; result.set_config(config); result } /// Quantizes the validated controls, prepares the Q7 map for the area - /// interpolation, rebuilds active synthesis models when width or stretch - /// changes, and updates the coefficients of the aspiration filter. + /// interpolation and updates the coefficients of the aspiration filter. /// - /// The audio histories do not change. A valid stretch gives a model with - /// 25 to 99 entries. Thus, the last point of the map and the denominators - /// of the interpolation are always defined. + /// The histories do not change. A valid stretch gives a model with 25 to + /// 99 entries. Thus, the last point of the map and the denominators of + /// the interpolation are always defined. pub(crate) fn set_config(&mut self, config: FormantConfig) { - let model_changed = - self.config.width != config.width || self.config.stretch != config.stretch; self.config = config; self.width = (config.width as f64 * 16384.0) as i32; self.width_squared = (config.width as f64 * config.width as f64 * 16384.0) as i32; @@ -328,16 +314,6 @@ impl Formant { self.stretch_map[i] = ((ORDER - 1) as f64 * fraction * 128.0) as i32; } self.stretch_map[self.stretch_count - 1] = ((ORDER - 1) * 128) as i32; - if model_changed { - for bank in 0..BANKS { - if self.valid_parcor[bank] { - self.build_model(bank); - } - } - if config.enabled { - self.edit_generation = self.edit_generation.wrapping_add(1); - } - } self.noise_gain = (config.aspiration_mix as f64 * 16384.0) as i32; let frequency = (config.aspiration_cutoff_hz as i32) .min((self.rate.hz() as f64 * 0.48) as i32) @@ -364,9 +340,7 @@ impl Formant { self.history_index = 0; self.current = BANKS - 1; self.next_filter(); - self.generations[0] = self.generation; self.next_filter(); - self.generations[1] = self.generation; self.design_counter = 0; self.noise_filter.reset(); self.smooth_reset = true; @@ -434,54 +408,9 @@ impl Formant { } self.blend = 0; self.inverse[self.current].fill(0_i32); - self.parcor[self.current].fill(0_i32); - self.valid_parcor[self.current] = false; + self.models[self.current].fill(0_i32); self.orders[self.current] = 0; - self.generations[self.current] = 0; - } - - /// Builds the synthesis filter for `bank` from its kept reflection and - /// inverse coefficients and the current width and stretch controls. - fn build_model(&mut self, bank: usize) { - let one = 16384; - self.models[bank].fill(0_i32); - self.orders[bank] = 0; - if self.width != one || self.stretch != one { - if let Some(scale) = lpc::parcor_to_areas(&self.parcor[bank], &mut self.areas) { - for i in 0..self.stretch_count { - let map = self.stretch_map[i]; - let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; - let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); - self.stretched_areas[i] = mul14( - mul14(one.wrapping_sub(fraction), self.areas[index]) - .wrapping_add(mul14(fraction, self.areas[index + 1])), - self.width_squared, - ); - if self.stretched_areas[i] == 0_i32 { - self.stretched_areas[i] = 1; - } - } - let mut stretched_parcor = [0_i32; MAX_ORDER]; - let mut scratch = [0_i32; 112]; - if lpc::areas_to_parcor( - &self.stretched_areas[..self.stretch_count], - &mut stretched_parcor, - scale, - ) { - lpc::parcor_to_pef( - &stretched_parcor[..self.stretch_count], - &mut self.models[bank], - &mut scratch, - 14, - ); - self.orders[bank] = self.stretch_count; - } - } - } else { - self.models[bank][..ORDER].copy_from_slice(&self.inverse[bank]); - self.orders[bank] = ORDER; - } } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. @@ -671,21 +600,52 @@ impl Formant { // order stays zero until all necessary model changes complete. self.next_filter(); self.generation = self.generation.wrapping_add(1); - self.generations[self.current] = self.generation; let design_gain = ((db_to_gain(-60.0) + 1.0) * 16384.0) as i32; correlations[0] = mul14(correlations[0], design_gain).wrapping_add(200); + let mut parcor = [0; MAX_ORDER]; let mut scratch = [0; 112]; let valid = lpc::durbin( &correlations, &mut self.inverse[self.current], - &mut self.parcor[self.current], + &mut parcor, &mut scratch, ); - self.valid_parcor[self.current] = valid; if valid { - self.build_model(self.current); + if self.width != one || self.stretch != one { + if let Some(scale) = lpc::parcor_to_areas(&parcor[..ORDER], &mut self.areas) { + for i in 0..self.stretch_count { + let map = self.stretch_map[i]; + let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; + let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); + self.stretched_areas[i] = mul14( + mul14(one.wrapping_sub(fraction), self.areas[index]) + .wrapping_add(mul14(fraction, self.areas[index + 1])), + self.width_squared, + ); + if self.stretched_areas[i] == 0_i32 { + self.stretched_areas[i] = 1; + } + } + if lpc::areas_to_parcor( + &self.stretched_areas[..self.stretch_count], + &mut parcor, + scale, + ) { + lpc::parcor_to_pef( + &parcor[..self.stretch_count], + &mut self.models[self.current], + &mut scratch, + 14, + ); + self.orders[self.current] = self.stretch_count; + } + } + } else { + self.models[self.current][..ORDER].copy_from_slice(&self.inverse[self.current]); + self.orders[self.current] = ORDER; + } } else { self.smooth_reset = true; } @@ -782,11 +742,9 @@ impl Formant { } &output[..order] } - /// Returns the wrapping generation of the model stamp at a signed history - /// frame, plus any live width or stretch edits. - pub(crate) fn generation(&self, position: i32) -> u32 { - let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; - self.generations[usize::from(stamp.current)].wrapping_add(self.edit_generation) + /// Returns the wrapping count of model designs that the stage tried. + pub(crate) fn generation(&self) -> u32 { + self.generation } /// Finds and blends the analysis coefficients of the stamp at a signed /// history frame, in the same way as [`Self::coefficients`]. diff --git a/src/index.ts b/src/index.ts index 0390391..151a4ae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,8 +5,8 @@ * configuration. Both environments use the same generated bindings and the * same Wasm binary. This module re-exports all named exports of the module * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, control-activity, event, feedback and - * telemetry types. + * `initSync` and the configuration, control-activity, event and feedback + * types. */ import init from "../pkg/tunelet.js"; import type { InitInput, InitOutput } from "../pkg/tunelet.js"; diff --git a/src/lib.rs b/src/lib.rs index cf61af5..34a4ba9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,10 +51,10 @@ //! [`Processor::feedback`] gives the pitch, the correction ratio, the //! accumulated output peak and the frame count. //! [`Processor::take_feedback`] also clears the peak window. The pitch -//! frequency bounds filter the reports, the tracking state and the pitch -//! correction. [`Processor::latency_frames`] gives a nominal resynthesis -//! delay, which the dry path also uses. Voice delays, pitch changes and -//! effects have their own timing. +//! reporting bounds change only the reports. They do not change the detection +//! or the audio signal. [`Processor::latency_frames`] gives a nominal +//! resynthesis delay, which the dry path also uses. Voice delays, pitch +//! changes and effects have their own timing. //! //! [`Processor::control_activity`] and [`ProcessorConfig::control_activity`] //! give [`ControlActivity`], which shows the active choir, harmony and reverb @@ -62,10 +62,9 @@ //! 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. +//! [`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/pitch.rs b/src/pitch.rs index 9b6e65d..6b682ca 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -2,18 +2,16 @@ //! estimates. //! //! Acquisition checks that repeated minima agree. Tracking refines the period -//! in a window of 40 lags. The frequency bounds filter the feedback, the -//! tracking state and the pitch correction. +//! in a window of 40 lags. The reporting bounds filter only the feedback to +//! the host. mod search; pub(crate) mod tracker; use crate::error::{check_range, ConfigProblem}; -use crate::numeric::fixed::Q6; -use crate::{Error, SampleRate}; +use crate::Error; -/// The acquisition sensitivity and the frequency bounds for pitch tracking and -/// correction. +/// The acquisition sensitivity and the bounds for pitch reports to the host. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -28,20 +26,18 @@ pub struct PitchConfig { /// This value controls acquisition. It is not an output gain or an /// amplitude gate. pub threshold: f32, - /// The lower bound of tracked pitch in hertz (inclusive), 40..=2000. + /// The lower bound of the feedback in hertz (inclusive), 40..=2000. /// /// The default is 40. It must be strictly less than `max_frequency_hz`. - /// Estimates outside the inclusive bounds are reported as unvoiced and - /// untracked, and they bypass pitch correction. A feedback query applies - /// the current bounds to the kept analysis and does not process another - /// sample. + /// These bounds do not change the tracking, the correction or the + /// resampling. A feedback query applies the current bounds to the kept + /// analysis. It does not process another sample. pub min_frequency_hz: f32, - /// The upper bound of tracked pitch in hertz (inclusive), 40..=2000. + /// The upper bound of the feedback in hertz (inclusive), 40..=2000. /// /// The default is 1100. It must be strictly greater than - /// `min_frequency_hz`. Estimates outside the inclusive bounds are reported - /// as unvoiced and untracked, with zero frequency and zero period, and - /// they bypass pitch correction. + /// `min_frequency_hz`. Results outside the bounds are reported as + /// unvoiced, with zero frequency and zero period. pub max_frequency_hz: f32, } @@ -56,18 +52,7 @@ impl Default for PitchConfig { } impl PitchConfig { - /// Returns `true` if `period` gives a frequency inside the inclusive - /// bounds at `rate`. - pub(crate) fn contains_period(self, rate: SampleRate, period: Q6) -> bool { - if period <= Q6::ZERO { - return false; - } - let period_samples = (period.to_bits() as f64 / 64.0) as f32; - let frequency_hz = rate.hz() / period_samples; - frequency_hz >= self.min_frequency_hz && frequency_hz <= self.max_frequency_hz - } - - /// Applies the frequency bounds for host reports to a kept estimate. + /// Applies only the bounds for host reports to a kept estimate. /// /// If the estimate is not voiced or is out of range, the result is the /// unvoiced value with all fields zero. The function does not change the diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index 4a49e43..a736e3a 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -10,8 +10,8 @@ //! The 40-lag window moves to keep the minimum near its center. If the //! minimum is at a boundary or the curvature is not usable, acquisition //! starts again. The last usable period stays available as a fallback for -//! resynthesis. Resynthesis enforces the public frequency bounds. They do not -//! change the size of these windows. +//! resynthesis. The public frequency bounds apply only to feedback reports. +//! They do not change the size of these windows. use super::search::{tracking_minimum, TRACKING_LAGS}; use crate::filter::{Biquad, Design}; @@ -44,7 +44,7 @@ pub(crate) struct PitchStep { } /// The number of lags that acquisition compares. -const ACQUISITION_LAGS: usize = 305; +const ACQUISITION_LAGS: usize = 137; /// The two-stage pitch tracker. /// @@ -178,11 +178,6 @@ impl PitchTracker { self.detecting } - /// Returns the latest refined Q6 period, or zero during acquisition. - pub(crate) fn period(&self) -> Q6 { - self.period - } - /// Returns how periodic the tracked input is at the last refined lag, /// from 0 to 1. /// @@ -331,7 +326,7 @@ impl PitchTracker { &mut self.cross[lag..end], ); index1 = if count == index1 + 1 { - 2 * ACQUISITION_LAGS - 1 + 273 } else { index1 - count }; diff --git a/src/processor.rs b/src/processor.rs index 2c971b4..16b26fd 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -430,12 +430,10 @@ impl Processor { /// last frame. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the current width and stretch - /// controls. A change to width or stretch updates `output` immediately, - /// also before the next audio block. Point `k` of `n` is at the frequency - /// `max_frequency_hz * k / (n - 1)`. The values are linear magnitudes. - /// They have no absolute level, because the analysis normalizes the signal - /// energy. Scale them for a display. + /// `output` gets the envelope after the width and stretch controls. Point + /// `k` of `n` is at the frequency `max_frequency_hz * k / (n - 1)`. The + /// values are linear magnitudes. They have no absolute level, because the + /// analysis normalizes the signal energy. Scale them for a display. /// /// `max_frequency_hz` must be finite, more than zero and not more than /// half of the sample rate. The two slices must have the same length. @@ -750,7 +748,7 @@ pub struct Feedback { pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// - /// It is zero if the input is unvoiced or outside the frequency bounds of + /// It is zero if the input is unvoiced or outside the reporting bounds of /// [`crate::PitchConfig`]. pub period_samples: f32, /// The reported input pitch frequency in hertz. @@ -774,11 +772,11 @@ pub struct Feedback { /// /// The value is `None` if [`voiced`](Self::voiced) is `false`, and only /// then. This occurs if the input is unvoiced or if its frequency is - /// outside the current frequency bounds. A target table that has no + /// outside the current reporting bounds. A target table that has no /// selected target does not give `None`. pub target_midi_note: Option, /// This field is `true` if the current pitch estimate is positive and - /// inside the current frequency bounds. + /// inside the current reporting bounds. /// /// This is not an amplitude gate or a confidence score. A tracking result /// can stay between detector updates. @@ -849,40 +847,38 @@ pub struct Telemetry { /// 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, during - /// pitch acquisition and outside the frequency bounds of - /// [`crate::PitchConfig`]. Use it as a confidence score for + /// 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 /// frame. pub clarity: f32, - /// This field is `true` if the pitch tracker follows a period inside the - /// frequency bounds of [`crate::PitchConfig`]. It is `false` during pitch - /// acquisition and outside those bounds. + /// This field is `true` if the pitch tracker follows a period. It is + /// `false` during pitch acquisition. pub tracking: bool, - /// The number of active voices. + /// The number of valid entries in [`voice_ratios`](Self::voice_ratios) + /// and [`voice_gains`](Self::voice_gains). /// - /// In Harmony mode, the value is 1 plus the number of harmony voices with - /// a positive gain, in 1..=5. In Choir mode, it is + /// The value is 5 in Harmony mode. In Choir mode, it is /// [`crate::ResynthesisConfig::choir_voices`], in 1..=16. pub voice_count: u8, /// The pitch ratio of each voice on the last frame, where 1 is the input /// pitch. /// /// Entry zero is the lead voice. In Harmony mode, entries 1 to 4 are the - /// four harmony voice slots, and entries 5 to 15 are zero. In Choir mode, - /// the entries after the lead are the secondary voices, and the entries - /// after [`voice_count`](Self::voice_count) are zero. Each ratio includes - /// the correction, the configured pitch shift and the ratio of the voice. + /// 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. pub voice_ratios: [f32; 16], /// The linear gain of each voice, in the order of /// [`voice_ratios`](Self::voice_ratios). /// /// The lead and the choir voices have a gain of 1. The gain of a harmony - /// voice includes [`crate::ResynthesisConfig::harmony_gain`] and the MIDI - /// velocity gain, in 0..=3.98095703125. MIDI velocity 127 at unity - /// `harmony_gain` gives the maximum, approximately +12 dB. The gain is - /// zero for a voice that does not sound. It does not include the stereo - /// pan. The harmony controller updates its envelope every 101 frames. + /// voice includes the MIDI velocity gain, in 0..=3.98095703125. MIDI + /// 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. pub voice_gains: [f32; 16], /// The effective linear gain of Punch at the current envelope level. /// @@ -908,11 +904,10 @@ pub struct Telemetry { /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. pub alien_phase_frames: u32, - /// The wrapping generation of the active formant synthesis model. + /// The wrapping count of formant analyses since construction. /// - /// While the formant stage is enabled, the count increases when playback - /// reaches a new analysis bank and when width or stretch changes. Compare - /// two values to find if [`Processor::formant_envelope`] can give a new - /// result. + /// The count increases every 441 frames while the formant stage is + /// enabled. Compare two values to find if + /// [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index acb276f..ae25310 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -164,7 +164,7 @@ impl CorrectionConfig { tsify(large_number_types_as_bigints) )] pub struct ResynthesisConfig { - /// The acquisition sensitivity and the pitch bounds. The + /// The acquisition sensitivity and the reporting bounds. The /// default is [`PitchConfig::default`]. pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled @@ -431,12 +431,8 @@ pub(crate) struct Resynthesis { /// telemetry reads them. voice_ratios: [Q14; HARMONY_VOICES + 1], /// The signed history frame that the formant model used for the last - /// frame. The audio path sets it, and the formant telemetry and envelope - /// read it. + /// frame. The audio path sets it, and only the formant envelope reads it. formant_position: i32, - /// The last refined Q6 period inside the configured frequency bounds. An - /// audio reset keeps it. - kept_period: Q6, /// Two cascaded anti-alias filter sections. If the shift is not upward, /// they have coefficients of 1.0 and zero. post: [Biquad; 2], @@ -527,7 +523,6 @@ impl Resynthesis { harmony_gains: [Q12::ZERO; HARMONY_VOICES], voice_ratios: [Q14::ONE; HARMONY_VOICES + 1], formant_position: 0, - kept_period: Q6::ZERO, post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, correction_decay: Q14::ZERO, @@ -642,12 +637,6 @@ impl Resynthesis { let old = self.config; self.config = config; self.pitch.set_config(config.pitch); - if old.pitch != config.pitch - && !config.pitch.contains_period(self.rate, self.pitch.period()) - { - self.correction = Q14::ONE; - self.scale_initialized = false; - } self.formant.set_config(config.formant); self.harmony.apply_config(config.harmony); if old.correction.notes != config.correction.notes @@ -826,30 +815,21 @@ impl Resynthesis { /// Returns how periodic the tracked input is, from 0 to 1. Refer to /// `PitchTracker::clarity`. pub(crate) fn clarity(&self) -> f32 { - if self.is_tracking() { - self.pitch.clarity() - } else { - 0.0 - } + self.pitch.clarity() } - /// Returns `true` if the pitch tracker follows a period inside the - /// configured frequency bounds, and `false` otherwise. + /// Returns `true` if the pitch tracker follows a period, and `false` + /// during acquisition. pub(crate) fn is_tracking(&self) -> bool { !self.pitch.is_detecting() - && self - .config - .pitch - .contains_period(self.rate, self.pitch.period()) } /// Writes the effective ratio and the linear gain of each voice from the - /// last frame, and returns the number of active voices. + /// last frame, and returns the number of voices. /// /// Slot zero is the lead. In Harmony mode, slots 1 to 4 are the harmony - /// voices, the gain includes `harmony_gain`, and the returned count is 1 - /// plus the number of harmony voices with a positive gain. In Choir mode, - /// the slots after the lead are the secondary voices with a gain of 1. - /// Each ratio includes the correction, the global shift and the ratio of - /// the voice. + /// voices, and the gain is the envelope of the harmony controller. In + /// Choir mode, the slots after the lead are the secondary voices with a + /// gain of 1. Each ratio includes the correction, the global shift and + /// the ratio of the voice. The entries after the count do not change. pub(crate) fn voices(&self, ratios: &mut [f32; 16], gains: &mut [f32; 16]) -> u8 { let lead = (self.voice_ratios[0].to_bits() as f64 / 16384.0) as f32; ratios[0] = lead; @@ -863,24 +843,17 @@ impl Resynthesis { } count as u8 } else { - let mut active = 1; for voice in 0..HARMONY_VOICES { ratios[voice + 1] = (self.voice_ratios[voice + 1].to_bits() as f64 / 16384.0) as f32; - let gain = ((self.harmony_gains[voice].to_bits() as f64 / 4096.0) - * self.config.harmony_gain as f64) as f32; - gains[voice + 1] = gain; - if gain > 0.0 { - active += 1; - } + gains[voice + 1] = (self.harmony_gains[voice].to_bits() as f64 / 4096.0) as f32; } - active + (HARMONY_VOICES + 1) as u8 } } - /// Returns the wrapping generation of the active formant stamp, plus any - /// live width or stretch edits. + /// Returns the wrapping count of formant model designs. pub(crate) fn formant_generation(&self) -> u32 { - self.formant.generation(self.formant_position) + self.formant.generation() } /// Writes the formant envelopes of the model that the audio used for the /// last frame. Refer to `Formant::envelope`. @@ -909,15 +882,9 @@ impl Resynthesis { /// global shift is part of the normalization. /// /// If correction is disabled or the active table is empty, the ratio moves - /// toward 1.0. If the period is outside the configured frequency bounds or - /// the shifted period is not positive, the ratio becomes 1.0 immediately. - /// Then the target selection starts again. + /// toward 1.0. If the shifted period is not positive, the ratio becomes + /// 1.0 immediately and the target selection starts again. fn update_correction(&mut self, period: Q6) { - if !self.config.pitch.contains_period(self.rate, period) { - self.correction = Q14::ONE; - self.scale_initialized = false; - return; - } let mut target_ratio = Q14::ONE; if self.config.correction.enabled && self.scale.count != 0 { let count = self.scale.count; @@ -1137,17 +1104,8 @@ impl Resynthesis { self.written += 1; } self.raw[self.write] = sample; - let was_tracking = !self.pitch.is_detecting() - && (self.pitch.period() == Q6::ZERO - || self - .config - .pitch - .contains_period(self.rate, self.pitch.period())); + let was_tracking = !self.pitch.is_detecting(); let step = self.pitch.process_sample(sample.to_bits()); - let in_bounds = self.config.pitch.contains_period(self.rate, step.period); - if in_bounds { - self.kept_period = step.period; - } let write = self.write; // Readers have signed fractional coordinates. When the writer wraps, // move the origin of these coordinates with it. Do not apply a modulo @@ -1164,7 +1122,7 @@ impl Resynthesis { } self.old_position = self.old_position - position_of(HISTORY as i32); } - if step.restarted || (step.period != Q6::ZERO && !in_bounds) { + if step.restarted { self.correction = Q14::ONE; self.scale_initialized = false; } @@ -1193,8 +1151,8 @@ impl Resynthesis { self.drift_ratio[0] = Q14::ONE; } } - self.periods[write] = if in_bounds { step.period } else { Q6::ZERO }; - self.previous_periods[write] = self.kept_period; + self.periods[write] = step.period; + self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; self.overlap_index += 1; if self.overlap_index == OVERLAP_FRAMES { @@ -1207,7 +1165,7 @@ impl Resynthesis { previous.to_bits(), self.periods.as_slice(), write, - self.kept_period.to_bits(), + step.previous_period.to_bits(), )) } else { self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] diff --git a/src/wasm.rs b/src/wasm.rs index 80bb6ae..7990a23 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -380,7 +380,7 @@ impl WasmProcessor { /// /// - The kept pitch estimate is unvoiced. This includes the time before /// the first detection and after a reset or a drain completion. - /// - The estimated frequency is outside the inclusive frequency bounds + /// - The estimated frequency is outside the inclusive reporting bounds /// `minFrequencyHz` and `maxFrequencyHz` of the pitch configuration. /// /// # Errors @@ -410,7 +410,7 @@ impl WasmProcessor { /// the active configuration. /// /// A `false` flag means that the related control makes no sample change in - /// the current voice mode, harmony source or reverb network. The audio + /// the active voice mode, harmony source or reverb network. The audio /// state does not change. /// /// # Errors @@ -455,11 +455,10 @@ impl WasmProcessor { /// `Float32Array` buffers of equal length. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the current width and stretch - /// controls. A change to width or stretch updates `output` immediately, - /// also before the next audio block. Point `k` of `n` is at the frequency - /// `maxFrequencyHz * k / (n - 1)`. The values are linear magnitudes with - /// no absolute level. Scale them for a display. + /// `output` gets the envelope after the width and stretch controls. Point + /// `k` of `n` is at the frequency `maxFrequencyHz * k / (n - 1)`. The + /// values are linear magnitudes with no absolute level. Scale them for a + /// display. /// /// `maxFrequencyHz` must be finite, more than zero and not more than half /// of the sample rate.