diff --git a/README.md b/README.md index 1b821bc..55331db 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,11 @@ 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 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 modes keep the stereo dry signal. @@ -465,8 +470,10 @@ 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 or `undefined`. The conversion ignores extra object +JavaScript `Error`. If an optional field is absent or `undefined`, 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. 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 57f1fd0..108bff6 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`. /// /// While at least one key in 0..=127 is held, correction MIDI replaces the /// active note table. It does not change this configuration. When all keys @@ -105,6 +105,45 @@ 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 relaxation on sustained notes without a unit, 0..=1. The default + /// is 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 or `undefined` value gives 0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + 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. + /// The default is 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 or `undefined` value gives 0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + 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 { @@ -113,6 +152,8 @@ impl Default for CorrectionConfig { enabled: true, notes: NoteMask::default(), retune_ms: 0.0, + humanize: 0.0, + flex_tune: 0.0, } } } @@ -120,21 +161,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) } } @@ -444,6 +488,21 @@ pub(crate) struct Resynthesis { /// The Q14 half-life coefficient for correction updates. These updates /// usually occur every five frames. correction_decay: Q14, + /// 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 period update. + dwell_step: Q14, + /// 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, /// The number of frames that the histories hold since the last reset. @@ -454,6 +513,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 period update, for dwell resets. + previous_scale_index: usize, + /// The octave exponent from the previous period 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 @@ -528,10 +591,19 @@ impl Resynthesis { post: [Biquad::new(), Biquad::new()], 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, scale_initialized: false, written: 0, scale_index: 0, octave: 0, + previous_scale_index: 0, + previous_octave: 0, shift: Q14::ONE, modulation: 0, modulation_phase: Q14::ZERO, @@ -554,11 +626,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); @@ -568,6 +641,29 @@ 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 = + 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 / ((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 + } 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); @@ -646,10 +742,14 @@ 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(); self.scale_initialized = false; + self.dwell = Q14::ZERO; } if old.mode != config.mode || old.choir_delay != config.choir_delay { self.create_delays(); @@ -728,7 +828,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. @@ -744,6 +847,7 @@ impl Resynthesis { self.scale .apply_validated_midi(event, self.config.correction.notes); self.scale_initialized = false; + self.dwell = Q14::ZERO; } /// Returns the finite number of frames for a drain of resynthesis. @@ -879,19 +983,51 @@ 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. + /// 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 { + 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. @@ -902,8 +1038,8 @@ impl Resynthesis { self.octave = 0; target = self.shift.mul(period); if target <= Q6::ZERO { - self.correction = Q14::ONE; - return; + self.reset_dwell(); + return None; } while table_period(1) > target { self.octave += 1; @@ -913,8 +1049,8 @@ impl Resynthesis { } } if target <= Q6::ZERO { - self.correction = Q14::ONE; - return; + self.reset_dwell(); + return None; } self.scale_initialized = true; } @@ -925,8 +1061,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; @@ -945,12 +1081,56 @@ 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); + decay = self.humanize_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 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); + } + } + } } + } else { + self.dwell = Q14::ZERO; } - self.correction = self.correction_decay.mul(self.correction - target_ratio) + target_ratio; + 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; } /// Selects the period and the correction. @@ -1122,6 +1302,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 4b7abee..d509e5e 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