From 79540931ffbff7789eb996f6916bbdb74a30641f Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:45:01 +0000 Subject: [PATCH 1/3] feat(resynthesis): add humanize and flex-tune controls - Add humanize and flex_tune fields to CorrectionConfig. - Accept absent humanize and flexTune fields in JavaScript. - Validate both fields in 0..=1 before state changes. - Relax the correction decay on sustained target bins. - Reset the dwell progress on target changes and restarts. - Reduce the target pull outside the inner flex-tune zone. - Preserve the default audio output at both sample rates. - Document the controls in rustdoc, wasm and the README. --- README.md | 14 +++-- src/resynthesis.rs | 142 ++++++++++++++++++++++++++++++++++++++++----- src/wasm.rs | 1 + 3 files changed, 140 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index d2993dc..b9162ec 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,11 @@ voice. It disables the effects and the formant stage. | Reverb | Echo, Schroeder, SmallRoom, Binaural, MediumHall, LargeHall | Disabled | `reverb` | | Output gain | Linear gain, 0..=64 | 1 | `output_gain` | +`resynthesis.correction.humanize` sets the sustained-note relaxation, in +`0..=1`. The default is 0. `resynthesis.correction.flex_tune` sets the +expressive deadband width around each target note, in `0..=1`. The default +is 0. + `resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The dry path starts after Warm and has a delay of 1,543 frames. @@ -444,10 +449,11 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +JavaScript `Error`. The optional `resynthesis.correction.humanize` and +`resynthesis.correction.flexTune` fields default to 0 if they are absent. +The optional `resynthesis.harmony.voices` field defaults to 4 if it is +absent. The conversion ignores extra object properties. The generated +declarations contain the parameter documentation from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..6834a36 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -61,12 +61,12 @@ pub enum MultiVoiceMode { /// The controls for pitch-class correction, with target selection in the /// period domain. /// -/// Correction is enabled by default, with all chromatic notes and a retune -/// time of zero. Target selection and the smoothing of the correction ratio -/// occur at each update of the pitch tracking. When a period is tracked, -/// this update usually occurs every five frames. If the active note table is -/// empty or correction is disabled, the ratio moves toward 1.0 at the same -/// rate. +/// Correction is enabled by default, with all chromatic notes, a retune time +/// of zero, zero humanize and zero flex-tune. Target selection and the +/// smoothing of the correction ratio occur at each update of the pitch +/// tracking. When a period is tracked, this update usually occurs every five +/// frames. If the active note table is empty or correction is disabled, the +/// ratio moves toward 1.0 with `retune_ms`. /// /// Correction MIDI replaces the active note table. It does not change this /// configuration. A change to `notes` or to `enabled` loads the configured @@ -106,6 +106,32 @@ pub struct CorrectionConfig { /// tracking update. A value that is not zero is a half-life. It is not a /// fixed time to get exactly to the target. pub retune_ms: f32, + /// The sustained-note relaxation without a unit, 0..=1. The default is 0. + /// + /// While the tracked pitch stays in one target bin, the smoothing + /// half-life increases toward `retune_ms + (400 - retune_ms) * humanize` + /// milliseconds. A target change, a table reload or a tracker restart + /// resets this ramp to `retune_ms`. Zero disables this relaxation. In + /// JavaScript, the field is optional and an absent value gives 0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub humanize: f32, + /// The expressive deadband width without a unit, 0..=1. The default is 0. + /// + /// Pitches inside the `1 - flex_tune` fraction of the half-bin around a + /// target period get the full correction ratio. Outside that inner zone, + /// the pull toward the target decreases to zero at the midpoint boundary. + /// Zero applies the full target ratio across the whole bin. In JavaScript, + /// the field is optional and an absent value gives 0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub flex_tune: f32, } impl Default for CorrectionConfig { @@ -114,6 +140,8 @@ impl Default for CorrectionConfig { enabled: true, notes: NoteMask::default(), retune_ms: 0.0, + humanize: 0.0, + flex_tune: 0.0, } } } @@ -121,21 +149,24 @@ impl Default for CorrectionConfig { impl CorrectionConfig { /// Validates all fields, also if correction is disabled. /// - /// All values of `enabled` and `notes` are valid. `retune_ms` must be - /// finite and in its documented inclusive range. Validation does not - /// clamp values. It does not change the state of the processor. + /// All values of `enabled` and `notes` are valid. `retune_ms`, `humanize` + /// and `flex_tune` must be finite and in their documented inclusive ranges. + /// Validation does not clamp values. It does not change the state of the + /// processor. /// /// # Errors /// /// Returns [`Error::InvalidConfig`], with the dotted path of the field and - /// the problem, if `retune_ms` is not valid. + /// the problem, if a field is not valid. pub fn validate(self) -> Result<(), Error> { check_range( "resynthesis.correction.retune_ms", self.retune_ms, 0.0, 400.0, - ) + )?; + check_range("resynthesis.correction.humanize", self.humanize, 0.0, 1.0)?; + check_range("resynthesis.correction.flex_tune", self.flex_tune, 0.0, 1.0) } } @@ -443,6 +474,15 @@ pub(crate) struct Resynthesis { /// The Q14 half-life coefficient for correction updates. These updates /// usually occur every five frames. correction_decay: Q14, + /// The Q14 sustained half-life coefficient for `humanize`, to a 400 ms + /// limit. + sustained_decay: Q14, + /// The Q14 dwell progress in the current target bin, 0..=1. + dwell: Q14, + /// The Q14 dwell increment for each five-frame tracking update. + dwell_step: Q14, + /// The Q14 flex-tune width, 0..=1. + flex_tune: Q14, /// If `true`, the current correction target and octave are selected. scale_initialized: bool, /// The index of the active target. It is valid only if the correction @@ -451,6 +491,10 @@ pub(crate) struct Resynthesis { /// The signed power-of-two exponent that normalizes the input period /// into the range of the correction table. octave: i32, + /// The target index from the previous tracking update, for dwell resets. + previous_scale_index: usize, + /// The octave exponent from the previous tracking update, for dwell resets. + previous_octave: i32, /// The Q14 global pitch multiplier. shift: Q14, /// The plain integer modulation depth. It is the public control times @@ -534,9 +578,15 @@ impl Resynthesis { post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, correction_decay: Q14::ZERO, + sustained_decay: Q14::ZERO, + dwell: Q14::ZERO, + dwell_step: Q14::ZERO, + flex_tune: Q14::ZERO, scale_initialized: false, scale_index: 0, octave: 0, + previous_scale_index: 0, + previous_octave: 0, shift: Q14::ONE, modulation: 0, modulation_phase: Q14::ZERO, @@ -572,6 +622,23 @@ impl Resynthesis { let t = self.config.correction.retune_ms / 1000.0; Q14::from_f64(0.5_f64.powf(1.0 / ((self.rate.hz() / 5.0) * t) as f64)) }; + if self.config.correction.humanize == 0.0 { + self.sustained_decay = self.correction_decay; + self.dwell_step = Q14::ZERO; + } else { + let sustained_ms = self.config.correction.retune_ms + + (400.0 - self.config.correction.retune_ms) * self.config.correction.humanize; + let t = sustained_ms / 1000.0; + self.sustained_decay = + Q14::from_f64(0.5_f64.powf(1.0 / ((self.rate.hz() / 5.0) * t) as f64)); + self.dwell_step = + Q14::from_f64(1.0 / ((self.rate.hz() / 5.0) * 0.16) as f64).max(Q14::from_bits(1)); + } + self.flex_tune = if self.config.correction.flex_tune == 0.0 { + Q14::ZERO + } else { + Q14::from_f64(self.config.correction.flex_tune as f64).max(Q14::from_bits(1)) + }; let base = (self.rate.hz() / 100.0) as f64 * 0.2; let decay = (-std::f64::consts::LN_2 / base).exp(); self.drift_decay = Q14::from_f64(decay); @@ -649,6 +716,9 @@ impl Resynthesis { { self.scale.set_notes(config.correction.notes); self.scale_initialized = false; + self.dwell = Q14::ZERO; + } else if config.correction.humanize == 0.0 { + self.dwell = Q14::ZERO; } if old.pitch_ratio != config.pitch_ratio { self.configure_shift_filters(); @@ -716,7 +786,10 @@ impl Resynthesis { self.formant_position = 0; self.current_output_period = Q6::ZERO; self.correction = Q14::ONE; + self.dwell = Q14::ZERO; self.scale_initialized = false; + self.previous_scale_index = 0; + self.previous_octave = 0; } /// Applies a MIDI event that the API or the block code checked before. @@ -731,6 +804,7 @@ impl Resynthesis { pub(crate) fn apply_correction_midi(&mut self, event: MidiEvent) { self.scale.apply_validated_midi(event); self.scale_initialized = false; + self.dwell = Q14::ZERO; } /// Returns the finite number of frames for a drain of resynthesis. @@ -858,7 +932,9 @@ impl Resynthesis { /// /// The Q6 input period must be a usable tracking result. The target /// search moves through the midpoints, also across octave limits. The - /// global shift is part of the normalization. + /// global shift is part of the normalization. On a sustained bin, + /// `humanize` relaxes the decay toward `sustained_decay`. Outside the + /// `1 - flex_tune` inner zone, the pull toward `target_ratio` decreases. /// /// 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 @@ -866,7 +942,9 @@ impl Resynthesis { /// multiplication by fixed-point 1.0 still wraps. Do not remove it. fn update_correction(&mut self, period: Q6) { let mut target_ratio = Q14::ONE; + let mut decay = self.correction_decay; if self.config.correction.enabled && self.scale.count != 0 { + let was_initialized = self.scale_initialized; let count = self.scale.count; // The correction table holds periods normalized to one octave. // They use the same units as the shifted target period below. @@ -878,6 +956,9 @@ impl Resynthesis { self.octave = 0; target = self.shift.mul(period); if target <= Q6::ZERO { + self.previous_scale_index = 0; + self.previous_octave = 0; + self.dwell = Q14::ZERO; self.correction = Q14::ONE; return; } @@ -912,12 +993,46 @@ impl Resynthesis { self.scale_index -= 1; } } + if !was_initialized + || self.scale_index != self.previous_scale_index + || self.octave != self.previous_octave + { + self.previous_scale_index = self.scale_index; + self.previous_octave = self.octave; + self.dwell = Q14::ZERO; + } else if self.dwell_step != Q14::ZERO { + self.dwell = (self.dwell + self.dwell_step).min(Q14::ONE); + let weight = self.dwell.mul::<14, 14>(self.dwell); + decay = self.correction_decay + + weight.mul(self.sustained_decay - self.correction_decay); + } let denominator = Q6::from_bits(self.scale.periods[self.scale_index]); if denominator != Q6::ZERO { target_ratio = target.div(denominator); + if self.flex_tune != Q14::ZERO { + let (distance, span) = if target >= denominator { + let upper = Q6::from_bits(self.scale.midpoints[self.scale_index + 1]); + (target - denominator, upper - denominator) + } else { + let lower = Q6::from_bits(self.scale.midpoints[self.scale_index]); + (denominator - target, denominator - lower) + }; + if span > Q6::ZERO { + let distance = distance.min(span); + let inner = span.mul::<14, 6>(Q14::ONE - self.flex_tune); + if distance > inner { + let outer = span - inner; + let remaining = Q14::ONE - (distance - inner).div::<6, 14>(outer); + let pull = remaining.mul::<14, 14>(remaining); + target_ratio = Q14::ONE + pull.mul(target_ratio - Q14::ONE); + } + } + } } + } else { + self.dwell = Q14::ZERO; } - self.correction = self.correction_decay.mul(self.correction - target_ratio) + target_ratio; + self.correction = decay.mul(self.correction - target_ratio) + target_ratio; } /// Selects the period and the correction. @@ -1066,6 +1181,7 @@ impl Resynthesis { if step.restarted { self.correction = Q14::ONE; self.scale_initialized = false; + self.dwell = Q14::ZERO; } if step.acquired { self.formant.detection_mode_off(); diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..b76b6f3 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,6 +19,7 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. +//! - The optional correction `humanize` and `flexTune` fields default to 0. //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use From 20d4310de703bbf675729618493389e789b5745a 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:37:37 +0000 Subject: [PATCH 2/3] fix(resynthesis): smooth the humanize ramp and clarify flex-tune docs - Interpolate the humanize half-life in Q20 with a Hermite ramp. - Convert the half-life to Q14 decay with a Pade (1, 1) quotient. - Factor select_target_ratio and reset dwell on pitch_ratio changes. - Describe flex_tune as an outer soft zone, not a deadband. --- README.md | 18 +++--- src/resynthesis.rs | 158 ++++++++++++++++++++++++++++++--------------- 2 files changed, 116 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 56b3dc1..a2a9f74 100644 --- a/README.md +++ b/README.md @@ -175,10 +175,10 @@ The internal Q14 stages use `i64` products and saturate at the `i32` limits. Decrease `output_gain` to prevent `-32767..=32767` clipping on multi-voice mixes. -`resynthesis.correction.humanize` sets the sustained-note relaxation, in -`0..=1`. The default is 0. `resynthesis.correction.flex_tune` sets the -expressive deadband width around each target note, in `0..=1`. The default -is 0. +`resynthesis.correction.humanize` sets the relaxation on sustained notes, in +`0..=1`. The default is 0. `resynthesis.correction.flex_tune` sets the outer +fraction of each half-bin where pull toward the target decreases, in `0..=1`. +The default is 0, which applies full pull across the whole bin. `resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The dry path starts after Warm and has a delay of 1,593 frames. All six reverb @@ -458,11 +458,11 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.correction.humanize` and -`resynthesis.correction.flexTune` fields default to 0 if they are absent. -The optional `resynthesis.harmony.voices` field defaults to 4 if it is -absent. The conversion ignores extra object properties. The generated -declarations contain the parameter documentation from the Rust types. +JavaScript `Error`. If an optional field is absent, it gets its default: +`resynthesis.correction.humanize` and `resynthesis.correction.flexTune` +default to 0, and `resynthesis.harmony.voices` defaults to 4. The conversion +ignores extra object properties. The generated declarations contain the +parameter documentation from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 80912f7..83096de 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -103,26 +103,30 @@ pub struct CorrectionConfig { /// tracking update. A value that is not zero is a half-life. It is not a /// fixed time to get exactly to the target. pub retune_ms: f32, - /// The sustained-note relaxation without a unit, 0..=1. The default is 0. + /// The relaxation on sustained notes without a unit, 0..=1. The default + /// is 0. /// - /// While the tracked pitch stays in one target bin, the smoothing - /// half-life increases toward `retune_ms + (400 - retune_ms) * humanize` - /// milliseconds. A target change, a table reload or a tracker restart - /// resets this ramp to `retune_ms`. Zero disables this relaxation. In - /// JavaScript, the field is optional and an absent value gives 0. + /// While the tracked pitch stays in one target bin, the half-life + /// increases smoothly toward `retune_ms + (400 - retune_ms) * humanize` + /// milliseconds. If the target bin, the note table or `pitch_ratio` + /// changes, or if the pitch tracker starts again, the half-life returns to + /// `retune_ms`. Zero disables this relaxation. In JavaScript, the field is + /// optional and an absent value gives 0. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), serde(default), tsify(optional) )] pub humanize: f32, - /// The expressive deadband width without a unit, 0..=1. The default is 0. + /// The outer soft-zone width of each target bin without a unit, 0..=1. + /// The default is 0. /// - /// Pitches inside the `1 - flex_tune` fraction of the half-bin around a - /// target period get the full correction ratio. Outside that inner zone, - /// the pull toward the target decreases to zero at the midpoint boundary. - /// Zero applies the full target ratio across the whole bin. In JavaScript, - /// the field is optional and an absent value gives 0. + /// Pitches in the inner `1 - flex_tune` fraction of the half-bin around a + /// target period get the full pull toward the target. In the outer + /// `flex_tune` fraction, the pull decreases to zero at the midpoint + /// boundary. Zero applies full pull across the whole bin, and 1 softens + /// pull from the target outward. In JavaScript, the field is optional and + /// an absent value gives 0. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), serde(default), @@ -473,14 +477,20 @@ pub(crate) struct Resynthesis { /// The Q14 half-life coefficient for correction updates. These updates /// usually occur every five frames. correction_decay: Q14, - /// The Q14 sustained half-life coefficient for `humanize`, to a 400 ms + /// The Q14 terminal half-life coefficient for `humanize`, to a 400 ms /// limit. sustained_decay: Q14, + /// The Q20 retune half-life in milliseconds, for the humanize ramp. + retune_half_life: i64, + /// The Q20 sustained half-life in milliseconds, to a 400 ms limit. + sustained_half_life: i64, + /// Half of the five-frame period step times `ln(2)`, in Q20 milliseconds. + decay_half_step: i64, /// The Q14 dwell progress in the current target bin, 0..=1. dwell: Q14, - /// The Q14 dwell increment for each five-frame tracking update. + /// The Q14 dwell increment for each five-frame period update. dwell_step: Q14, - /// The Q14 flex-tune width, 0..=1. + /// The Q14 outer soft-zone width of each half-bin, 0..=1. flex_tune: Q14, /// If `true`, the current correction target and octave are selected. scale_initialized: bool, @@ -492,9 +502,9 @@ pub(crate) struct Resynthesis { /// The signed power-of-two exponent that normalizes the input period /// into the range of the correction table. octave: i32, - /// The target index from the previous tracking update, for dwell resets. + /// The target index from the previous period update, for dwell resets. previous_scale_index: usize, - /// The octave exponent from the previous tracking update, for dwell resets. + /// The octave exponent from the previous period update, for dwell resets. previous_octave: i32, /// The Q14 global pitch multiplier. shift: Q14, @@ -571,6 +581,9 @@ impl Resynthesis { correction: Q14::ONE, correction_decay: Q14::ZERO, sustained_decay: Q14::ZERO, + retune_half_life: 0, + sustained_half_life: 0, + decay_half_step: 0, dwell: Q14::ZERO, dwell_step: Q14::ZERO, flex_tune: Q14::ZERO, @@ -602,11 +615,12 @@ impl Resynthesis { /// Quantizes the controls and calculates the decay coefficients and the /// voice pan gains again. /// - /// The coefficients are the correction decay, the drift decay and the - /// drift amount. The histories and the controller phase do not change. - /// The stereo pan gains include the harmony gain. The mono harmony path - /// uses a separate Q14 gain. + /// The coefficients cover correction, humanize, flex-tune and choir drift. + /// The histories and the controller phase do not change. The stereo pan + /// gains include the harmony gain. The mono harmony path uses a separate + /// Q14 gain. fn configure_coefficients(&mut self) { + const Q20_SCALE: f64 = (1_u32 << 20) as f64; self.shift = Q14::from_f64(self.config.pitch_ratio as f64); self.modulation = (self.config.harmonic_modulation as f64 / 8.0 * 16.0) as i32; self.dry_mix = Q8::from_f64((self.config.dry_mix * 100.0) as f64 / 100.0); @@ -616,17 +630,23 @@ impl Resynthesis { let t = self.config.correction.retune_ms / 1000.0; Q14::from_f64(0.5_f64.powf(1.0 / ((self.rate.hz() / 5.0) * t) as f64)) }; + let retune_ms = f64::from(self.config.correction.retune_ms); + self.retune_half_life = (retune_ms * Q20_SCALE + 0.5) as i64; + self.decay_half_step = + (2500.0 * std::f64::consts::LN_2 / f64::from(self.rate.hz()) * Q20_SCALE + 0.5) as i64; if self.config.correction.humanize == 0.0 { self.sustained_decay = self.correction_decay; + self.sustained_half_life = self.retune_half_life; self.dwell_step = Q14::ZERO; } else { - let sustained_ms = self.config.correction.retune_ms - + (400.0 - self.config.correction.retune_ms) * self.config.correction.humanize; + let sustained_ms = + retune_ms + (400.0 - retune_ms) * f64::from(self.config.correction.humanize); let t = sustained_ms / 1000.0; self.sustained_decay = - Q14::from_f64(0.5_f64.powf(1.0 / ((self.rate.hz() / 5.0) * t) as f64)); - self.dwell_step = - Q14::from_f64(1.0 / ((self.rate.hz() / 5.0) * 0.16) as f64).max(Q14::from_bits(1)); + Q14::from_f64(0.5_f64.powf(1.0 / ((f64::from(self.rate.hz()) / 5.0) * t))); + self.sustained_half_life = (sustained_ms * Q20_SCALE + 0.5) as i64; + self.dwell_step = Q14::from_f64(1.0 / ((f64::from(self.rate.hz()) / 5.0) * 0.18)) + .max(Q14::from_bits(1)); } self.flex_tune = if self.config.correction.flex_tune == 0.0 { Q14::ZERO @@ -718,6 +738,7 @@ impl Resynthesis { if old.pitch_ratio != config.pitch_ratio { self.configure_shift_filters(); self.scale_initialized = false; + self.dwell = Q14::ZERO; } if old.mode != config.mode || old.choir_delay != config.choir_delay { self.create_delays(); @@ -948,19 +969,47 @@ impl Resynthesis { self.formant .envelope(self.formant_position, max_frequency_hz, input, output) } - /// Selects a target in the period domain and smooths the Q14 correction - /// ratio. + /// Clears the dwell progress and the previous target bin. + fn reset_dwell(&mut self) { + self.dwell = Q14::ZERO; + self.previous_scale_index = 0; + self.previous_octave = 0; + } + + /// Maps the current dwell progress to a Q14 half-life decay coefficient. /// - /// The Q6 input period must be a usable tracking result. The target - /// search moves through the midpoints, also across octave limits. The - /// global shift is part of the normalization. On a sustained bin, - /// `humanize` relaxes the decay toward `sustained_decay`. Outside the - /// `1 - flex_tune` inner zone, the pull toward `target_ratio` decreases. + /// The Hermite ramp `u^3 * (4 - 3 * u)` interpolates the half-life in Q20 + /// milliseconds. A Padé `(1, 1)` quotient converts that half-life to Q14. + fn humanize_decay(&self) -> Q14 { + if self.dwell >= Q14::ONE { + return self.sustained_decay; + } + let u = i64::from(self.dwell.to_bits()); + let s = (u * u * u * (65_536 - 3 * u)) >> 42; + let half_life = self.retune_half_life + + (((self.sustained_half_life - self.retune_half_life) * s) >> 14); + let raw = if half_life <= self.decay_half_step { + 0 + } else { + (((half_life - self.decay_half_step) << 14) / (half_life + self.decay_half_step)) as i32 + }; + Q14::from_bits(raw).clamp(self.correction_decay, self.sustained_decay) + } + + /// Selects a target in the period domain and returns the Q14 target ratio + /// and Q14 decay coefficient. /// - /// If correction is disabled or the active table is empty, the ratio moves - /// 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) { + /// The Q6 input period must be a usable result from the pitch tracker. The + /// search moves through the midpoints, also across octave limits, and + /// includes the global shift. On a sustained bin, `humanize` increases the + /// half-life toward `sustained_half_life`. In the outer `flex_tune` zone, + /// the pull toward the target decreases to zero at the midpoint boundary. + /// + /// If the shifted period is not positive, the function clears + /// `scale_initialized` and dwell, and returns `None`. If correction is + /// disabled or the active table is empty, the function returns unity ratio + /// and `correction_decay`. + fn select_target_ratio(&mut self, period: Q6) -> Option<(Q14, Q14)> { let mut target_ratio = Q14::ONE; let mut decay = self.correction_decay; if self.config.correction.enabled && self.scale.count != 0 { @@ -975,11 +1024,8 @@ impl Resynthesis { self.octave = 0; target = self.shift.mul(period); if target <= Q6::ZERO { - self.previous_scale_index = 0; - self.previous_octave = 0; - self.dwell = Q14::ZERO; - self.correction = Q14::ONE; - return; + self.reset_dwell(); + return None; } while table_period(1) > target { self.octave += 1; @@ -989,8 +1035,8 @@ impl Resynthesis { } } if target <= Q6::ZERO { - self.correction = Q14::ONE; - return; + self.reset_dwell(); + return None; } self.scale_initialized = true; } @@ -1001,8 +1047,8 @@ impl Resynthesis { }); if target <= Q6::ZERO { self.scale_initialized = false; - self.correction = Q14::ONE; - return; + self.reset_dwell(); + return None; } while table_period(self.scale_index + 1) < target { self.scale_index += 1; @@ -1030,9 +1076,7 @@ impl Resynthesis { self.dwell = Q14::ZERO; } else if self.dwell_step != Q14::ZERO { self.dwell = (self.dwell + self.dwell_step).min(Q14::ONE); - let weight = self.dwell.mul::<14, 14>(self.dwell); - decay = self.correction_decay - + weight.mul(self.sustained_decay - self.correction_decay); + decay = self.humanize_decay(); } let denominator = Q6::from_bits(self.scale.periods[self.scale_index]); if denominator != Q6::ZERO { @@ -1050,8 +1094,8 @@ impl Resynthesis { let inner = span.mul::<14, 6>(Q14::ONE - self.flex_tune); if distance > inner { let outer = span - inner; - let remaining = Q14::ONE - (distance - inner).div::<6, 14>(outer); - let pull = remaining.mul::<14, 14>(remaining); + let taper = Q14::ONE - (distance - inner).div::<6, 14>(outer); + let pull = taper.mul::<14, 14>(taper); target_ratio = Q14::ONE + pull.mul(target_ratio - Q14::ONE); } } @@ -1060,6 +1104,18 @@ impl Resynthesis { } else { self.dwell = Q14::ZERO; } + Some((target_ratio, decay)) + } + + /// Updates the Q14 correction ratio from `period`. + /// + /// If `select_target_ratio` finds a non-positive shifted period, the + /// correction ratio becomes 1.0 immediately. + fn update_correction(&mut self, period: Q6) { + let Some((target_ratio, decay)) = self.select_target_ratio(period) else { + self.correction = Q14::ONE; + return; + }; self.correction = decay.mul(self.correction - target_ratio) + target_ratio; } From c117e2398b9d6892dda079aad1a4e904ccc6a1b7 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 16:44:32 +0000 Subject: [PATCH 3/3] fix(wasm): accept undefined humanize and flexTune fields - Decode undefined humanize and flexTune values to 0 in Wasm. - Emit number | undefined for humanize and flexTune in tsify. - Check absent and undefined correction fields in verify-pack.mjs. --- scripts/verify-pack.mjs | 32 ++++++++++++++++++++++++++++++++ src/resynthesis.rs | 21 +++++++++++++++------ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 684a904..ada96fe 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -285,9 +285,13 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.ok(wasmExports);", "", "const initialConfig = rootModule.defaultConfig();", + "initialConfig.resynthesis.correction.humanize = undefined;", + "initialConfig.resynthesis.correction.flexTune = undefined;", "initialConfig.resynthesis.harmony.voices = undefined;", "const processor = new rootModule.Tunelet(48000, 128, initialConfig);", "try {", + " assert.equal(processor.config().resynthesis.correction.humanize, 0);", + " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", "", " const twoVoiceConfig = processor.config();", @@ -305,12 +309,30 @@ function verifyRuntimeImport(consumerDir, packageName) { " processor.setConfig(oneVoiceConfig);", " assert.equal(processor.config().resynthesis.harmony.voices, 1);", "", + " const tunedCorrectionConfig = processor.config();", + " tunedCorrectionConfig.resynthesis.correction.humanize = 0.5;", + " tunedCorrectionConfig.resynthesis.correction.flexTune = 0.25;", + " processor.setConfig(tunedCorrectionConfig);", + " assert.equal(processor.config().resynthesis.correction.humanize, 0.5);", + " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", + "", + " const omittedCorrectionConfig = processor.config();", + " delete omittedCorrectionConfig.resynthesis.correction.humanize;", + " delete omittedCorrectionConfig.resynthesis.correction.flexTune;", + " processor.setConfig(omittedCorrectionConfig);", + " assert.equal(processor.config().resynthesis.correction.humanize, 0);", + " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + "", " const mono = new Int16Array(128);", " const eventResynthesis = processor.config().resynthesis;", + " eventResynthesis.correction.humanize = undefined;", + " eventResynthesis.correction.flexTune = undefined;", " eventResynthesis.harmony.voices = undefined;", " processor.processMono(mono, [", ' { offset: 0, event: { type: "resynthesis", value: eventResynthesis } },', " ]);", + " assert.equal(processor.config().resynthesis.correction.humanize, 0);", + " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", "", " const input = new Int16Array(128);", @@ -533,6 +555,11 @@ function verifyTypeDeclarations(consumerDir, packageName) { " ...baseConfig,", " resynthesis: {", " ...baseConfig.resynthesis,", + " correction: {", + " ...baseConfig.resynthesis.correction,", + " humanize: optionalVoices,", + " flexTune: optionalVoices,", + " },", " harmony: {", " ...baseConfig.resynthesis.harmony,", " voices: optionalVoices,", @@ -551,6 +578,11 @@ function verifyTypeDeclarations(consumerDir, packageName) { " processor.setConfig(configWithUndefined);", " const resynthesisUpdate: ResynthesisConfig = {", " ...configWithUndefined.resynthesis,", + " correction: {", + " enabled: configWithUndefined.resynthesis.correction.enabled,", + " notes: configWithUndefined.resynthesis.correction.notes,", + " retuneMs: configWithUndefined.resynthesis.correction.retuneMs,", + " },", " harmony: {", " ...configWithUndefined.resynthesis.harmony,", " voices: undefined,", diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 3116b5f..108bff6 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -113,11 +113,11 @@ pub struct CorrectionConfig { /// milliseconds. If the target bin, the note table or `pitch_ratio` /// changes, or if the pitch tracker starts again, the half-life returns to /// `retune_ms`. Zero disables this relaxation. In JavaScript, the field is - /// optional and an absent value gives 0. + /// optional and an absent or `undefined` value gives 0. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - serde(default), - tsify(optional) + serde(default, deserialize_with = "deserialize_zero_f32"), + tsify(optional, type = "number | undefined") )] pub humanize: f32, /// The outer soft-zone width of each target bin without a unit, 0..=1. @@ -128,15 +128,24 @@ pub struct CorrectionConfig { /// `flex_tune` fraction, the pull decreases to zero at the midpoint /// boundary. Zero applies full pull across the whole bin, and 1 softens /// pull from the target outward. In JavaScript, the field is optional and - /// an absent value gives 0. + /// an absent or `undefined` value gives 0. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - serde(default), - tsify(optional) + serde(default, deserialize_with = "deserialize_zero_f32"), + tsify(optional, type = "number | undefined") )] pub flex_tune: f32, } +/// Decodes an optional correction control and maps an absent value to 0. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_zero_f32<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or(0.0)) +} + impl Default for CorrectionConfig { fn default() -> Self { Self {