diff --git a/README.md b/README.md index a06715f..5c626e9 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,11 @@ multi-voice mixes. 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.correction.vibrato_preserve` sets the fraction of 4..=8 Hz +vibrato that bypasses correction, in `0..=1`. The default is 0. At 1, +correction moves the mean pitch to the target note and keeps natural +vibrato, also at zero retune time. + `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. @@ -579,8 +584,9 @@ and show enums as string literals. To change the configuration, do these steps: If a required field is absent or a value is not valid, the call throws a 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 +default. `resynthesis.correction.humanize`, +`resynthesis.correction.flexTune` and +`resynthesis.correction.vibratoPreserve` 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 66d5b7a..3b19bd8 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -315,11 +315,13 @@ function verifyRuntimeImport(consumerDir, packageName) { "const initialConfig = rootModule.defaultConfig();", "initialConfig.resynthesis.correction.humanize = undefined;", "initialConfig.resynthesis.correction.flexTune = undefined;", + "initialConfig.resynthesis.correction.vibratoPreserve = 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.correction.vibratoPreserve, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", " const initialTelemetry = processor.telemetry();", @@ -330,18 +332,24 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(initialTelemetry.targetMidiNote, undefined);", "", " const twoVoiceConfig = processor.config();", + " twoVoiceConfig.resynthesis.correction.vibratoPreserve = 0.5;", " twoVoiceConfig.resynthesis.harmony.voices = 2;", " processor.setConfig(twoVoiceConfig);", + " assert.equal(processor.config().resynthesis.correction.vibratoPreserve, 0.5);", " assert.equal(processor.config().resynthesis.harmony.voices, 2);", "", " const undefinedVoiceConfig = processor.config();", + " undefinedVoiceConfig.resynthesis.correction.vibratoPreserve = undefined;", " undefinedVoiceConfig.resynthesis.harmony.voices = undefined;", " processor.setConfig(undefinedVoiceConfig);", + " assert.equal(processor.config().resynthesis.correction.vibratoPreserve, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", "", " const oneVoiceConfig = processor.config();", + " oneVoiceConfig.resynthesis.correction.vibratoPreserve = 1;", " oneVoiceConfig.resynthesis.harmony.voices = 1;", " processor.setConfig(oneVoiceConfig);", + " assert.equal(processor.config().resynthesis.correction.vibratoPreserve, 1);", " assert.equal(processor.config().resynthesis.harmony.voices, 1);", "", " const tunedCorrectionConfig = processor.config();", @@ -354,20 +362,24 @@ function verifyRuntimeImport(consumerDir, packageName) { " const omittedCorrectionConfig = processor.config();", " delete omittedCorrectionConfig.resynthesis.correction.humanize;", " delete omittedCorrectionConfig.resynthesis.correction.flexTune;", + " delete omittedCorrectionConfig.resynthesis.correction.vibratoPreserve;", " processor.setConfig(omittedCorrectionConfig);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + " assert.equal(processor.config().resynthesis.correction.vibratoPreserve, 0);", "", " const mono = new Int16Array(128);", " const eventResynthesis = processor.config().resynthesis;", " eventResynthesis.correction.humanize = undefined;", " eventResynthesis.correction.flexTune = undefined;", + " eventResynthesis.correction.vibratoPreserve = 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.correction.vibratoPreserve, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", "", " const input = new Int16Array(128);", @@ -778,6 +790,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " ...baseConfig.resynthesis.correction,", " humanize: optionalVoices,", " flexTune: optionalVoices,", + " vibratoPreserve: optionalVoices,", " },", " harmony: {", " ...baseConfig.resynthesis.harmony,", diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..732fd09 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -28,6 +28,7 @@ //! - The order of the fixed-point arithmetic. pub(crate) mod history; +mod vibrato; use crate::error::{check_count, check_range}; use crate::filter::{Biquad, Design}; @@ -41,6 +42,7 @@ use crate::pitch::{PitchConfig, PitchEstimate}; use crate::scale::{CorrectionTable, NoteMask}; use crate::{Error, SampleRate}; use history::{clear_dirty_ring, prepare_history, record_history}; +use vibrato::PeriodFilter; /// The method that resynthesis uses to render its voices. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -62,11 +64,11 @@ pub enum MultiVoiceMode { /// period domain. /// /// 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`. +/// of zero, zero humanize, zero flex-tune and zero vibrato preservation. +/// 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 @@ -135,6 +137,19 @@ pub struct CorrectionConfig { tsify(optional, type = "number | undefined") )] pub flex_tune: f32, + /// The fraction of 4 Hz to 8 Hz vibrato that bypasses correction, without + /// a unit, 0..=1. The default is 0. + /// + /// Zero applies full correction to the vibrato. A value of 1 keeps the + /// 4 Hz to 8 Hz vibrato while the mean pitch moves to the active target + /// note. 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 vibrato_preserve: f32, } /// Decodes an optional correction control and maps an absent value to 0. @@ -154,6 +169,7 @@ impl Default for CorrectionConfig { retune_ms: 0.0, humanize: 0.0, flex_tune: 0.0, + vibrato_preserve: 0.0, } } } @@ -161,10 +177,10 @@ impl Default for CorrectionConfig { impl CorrectionConfig { /// Validates all fields, also if correction is disabled. /// - /// 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. + /// All values of `enabled` and `notes` are valid. `retune_ms`, `humanize`, + /// `flex_tune` and `vibrato_preserve` must be finite and in their + /// documented inclusive ranges. Validation does not clamp values. It does + /// not change the state of the processor. /// /// # Errors /// @@ -173,7 +189,8 @@ impl CorrectionConfig { pub fn validate(self) -> Result<(), Error> { validate_retune_ms(self.retune_ms)?; validate_humanize(self.humanize)?; - validate_flex_tune(self.flex_tune) + validate_flex_tune(self.flex_tune)?; + validate_vibrato_preserve(self.vibrato_preserve) } } @@ -192,6 +209,16 @@ pub(crate) fn validate_flex_tune(flex_tune: f32) -> Result<(), Error> { check_range("resynthesis.correction.flex_tune", flex_tune, 0.0, 1.0) } +/// Checks the range of the vibrato preservation fraction. +fn validate_vibrato_preserve(vibrato_preserve: f32) -> Result<(), Error> { + check_range( + "resynthesis.correction.vibrato_preserve", + vibrato_preserve, + 0.0, + 1.0, + ) +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -538,6 +565,17 @@ pub(crate) struct Resynthesis { /// The current smoothed Q14 correction ratio. It does not include the /// global shift or the voice ratios. correction: Q14, + /// The smoothed Q24 ratio of the secular pitch contour when vibrato + /// preservation is active. + secular_correction: i64, + /// The smoothed Q24 modulation ratio when vibrato preservation is active. + vibrato_ratio: i64, + /// If `true`, `vibrato_preserve` is nonzero and the contour filter runs. + vibrato_enabled: bool, + /// The Q24 vibrato preservation weight. + vibrato_preserve: i64, + /// The Q24 contour filter that separates secular periods from vibrato. + period_filter: PeriodFilter, /// The Q14 half-life coefficient for correction updates. These updates /// usually occur every five frames. correction_decay: Q14, @@ -643,6 +681,11 @@ impl Resynthesis { formant_position: 0, post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, + secular_correction: 1 << 24, + vibrato_ratio: 1 << 24, + vibrato_enabled: false, + vibrato_preserve: 0, + period_filter: PeriodFilter::new(rate), correction_decay: Q14::ZERO, sustained_decay: Q14::ZERO, retune_half_life: 0, @@ -730,6 +773,28 @@ impl Resynthesis { }; } + /// Quantizes the vibrato preservation weight and updates the contour filter + /// state unconditionally. + fn configure_vibrato_preserve(&mut self) { + let was_vibrato_enabled = self.vibrato_enabled; + if self.config.correction.vibrato_preserve == 0.0 { + self.vibrato_enabled = false; + self.vibrato_preserve = 0; + if was_vibrato_enabled { + self.period_filter.reset(); + self.vibrato_ratio = 1 << 24; + } + } else { + self.vibrato_enabled = true; + self.vibrato_preserve = + vibrato::quantize_preserve(self.config.correction.vibrato_preserve); + if !was_vibrato_enabled { + self.secular_correction = i64::from(self.correction.to_bits()) << 10; + self.vibrato_ratio = 1 << 24; + } + } + } + /// Calculates the choir drift decay and drift amount unconditionally. fn configure_choir_drift(&mut self) { let base = (self.rate.hz() / 100.0) as f64 * 0.2; @@ -785,6 +850,7 @@ impl Resynthesis { self.configure_dry_mix(); self.configure_correction_decay(); self.configure_flex_tune(); + self.configure_vibrato_preserve(); self.configure_choir_drift(); self.configure_choir_pan(); self.configure_harmony_gain(); @@ -856,6 +922,9 @@ impl Resynthesis { if old.correction.flex_tune != config.correction.flex_tune { self.configure_flex_tune(); } + if old.correction.vibrato_preserve != config.correction.vibrato_preserve { + self.configure_vibrato_preserve(); + } if old.pitch_ratio != config.pitch_ratio { self.configure_pitch_ratio(); self.configure_shift_filters(); @@ -1139,7 +1208,10 @@ impl Resynthesis { self.voice_ratios.fill(Q14::ONE); self.formant_position = 0; self.current_output_period = Q6::ZERO; + self.period_filter.reset(); self.correction = Q14::ONE; + self.secular_correction = 1 << 24; + self.vibrato_ratio = 1 << 24; self.dwell = Q14::ZERO; self.scale_initialized = false; self.previous_scale_index = 0; @@ -1322,8 +1394,8 @@ impl Resynthesis { 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. + /// Selects a target in the period domain and returns the Q14 target ratio, + /// Q14 decay coefficient and Q14 correction pull. /// /// The Q6 input period must be a usable result from the pitch tracker. The /// search moves through the midpoints, also across octave limits, and @@ -1333,11 +1405,12 @@ impl Resynthesis { /// /// 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)> { + /// disabled or the active table is empty, the function returns unity ratio, + /// `correction_decay` and zero pull. + fn select_target_ratio(&mut self, period: Q6) -> Option<(Q14, Q14, Q14)> { let mut target_ratio = Q14::ONE; let mut decay = self.correction_decay; + let mut pull = Q14::ZERO; if self.config.correction.enabled && self.scale.count != 0 { let was_initialized = self.scale_initialized; let count = self.scale.count; @@ -1406,6 +1479,7 @@ impl Resynthesis { } let denominator = Q6::from_bits(self.scale.periods[self.scale_index]); if denominator != Q6::ZERO { + pull = Q14::ONE; target_ratio = target.div(denominator); if self.flex_tune != Q14::ZERO { let (distance, span) = if target >= denominator { @@ -1421,7 +1495,7 @@ impl Resynthesis { if distance > inner { let outer = span - inner; let taper = Q14::ONE - (distance - inner).div::<6, 14>(outer); - let pull = taper.mul::<14, 14>(taper); + pull = taper.mul::<14, 14>(taper); target_ratio = Q14::ONE + pull.mul(target_ratio - Q14::ONE); } } @@ -1430,19 +1504,43 @@ impl Resynthesis { } else { self.dwell = Q14::ZERO; } - Some((target_ratio, decay)) + Some((target_ratio, decay, pull)) } /// Updates the Q14 correction ratio from `period`. /// - /// If `select_target_ratio` finds a non-positive shifted period, the - /// correction ratio becomes 1.0 immediately. + /// If `vibrato_preserve` is zero, this method skips the contour filter and + /// the modulation product to keep the Q14 quantization unchanged. If + /// `vibrato_preserve` is nonzero, the contour filter supplies a secular + /// period for target selection and a modulation ratio that `flex_tune` pull + /// tapers. 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 { + if !self.vibrato_enabled { + 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; + return; + } + let (secular_period, mod_ratio) = self.period_filter.split(period, self.vibrato_preserve); + let Some((target_ratio, decay, pull)) = self.select_target_ratio(secular_period) else { + self.secular_correction = 1 << 24; + self.vibrato_ratio = 1 << 24; self.correction = Q14::ONE; return; }; - self.correction = decay.mul(self.correction - target_ratio) + target_ratio; + let target_mod = Q14::ONE + pull.mul(mod_ratio - Q14::ONE); + let decay = i64::from(decay.to_bits()); + let target_q24 = i64::from(target_ratio.to_bits()) << 10; + self.secular_correction = + target_q24 + ((self.secular_correction - target_q24) * decay) / 16_384; + let mod_q24 = i64::from(target_mod.to_bits()) << 10; + self.vibrato_ratio = mod_q24 + ((self.vibrato_ratio - mod_q24) * decay) / 16_384; + let secular_q14 = Q14::from_bits(((self.secular_correction + 512) >> 10) as i32); + let mod_q14 = Q14::from_bits(((self.vibrato_ratio + 512) >> 10) as i32); + self.correction = secular_q14.mul(mod_q14); } /// Selects the period and the correction. @@ -1637,11 +1735,23 @@ impl Resynthesis { self.old_position = self.old_position - position_of(HISTORY as i32); } if step.restarted { + if self.vibrato_enabled { + self.period_filter.reset(); + self.secular_correction = 1 << 24; + self.vibrato_ratio = 1 << 24; + } self.correction = Q14::ONE; self.scale_initialized = false; self.dwell = Q14::ZERO; } if step.acquired { + if self.vibrato_enabled { + if step.period > Q6::ZERO { + self.period_filter.seed(step.period); + } else { + self.period_filter.reset(); + } + } self.formant.detection_mode_off(); } if step.tracking_update { diff --git a/src/resynthesis/vibrato.rs b/src/resynthesis/vibrato.rs new file mode 100644 index 0000000..d23283c --- /dev/null +++ b/src/resynthesis/vibrato.rs @@ -0,0 +1,189 @@ +//! The Q24 period filter that separates the mean pitch contour from vibrato. +//! +//! The pitch tracker updates the period once every five audio frames. At 44.1 +//! kHz and 48 kHz, a Q14 biquad with a 3 Hz cutoff loses its numerator bits. +//! Thus, this filter uses Q24 coefficients and Q24 state words. + +use crate::numeric::fixed::{Q14, Q6}; +use crate::SampleRate; + +/// The number of fractional bits in Q24. +const Q24_SHIFT: u32 = 24; +/// The left shift from a Q6 period word to a Q24 period word. +const Q6_TO_Q24_SHIFT: u32 = 18; +/// The geometric center of the 4..=8 Hz vibrato band, in hertz. +const BAND_CENTER_HZ: f64 = 5.656_854_249_492_381; +/// The -3 dB width of the vibrato band-pass section, in hertz. +const BAND_WIDTH_HZ: f64 = 8.2; +/// The one-pole cutoff after the vibrato notch, in hertz. +/// +/// The combined secular -3 dB cutoff is below 3 Hz, and the group delay is +/// below 80 ms at both sample rates. +const SECULAR_LP_HZ: f64 = 4.4; +/// The lowest Q14 modulation ratio (0.25). +const MIN_MOD_RATIO_BITS: i128 = 4_096; +/// The highest Q14 modulation ratio (4.0). +const MAX_MOD_RATIO_BITS: i128 = 65_536; + +/// Scales a finite control in 0..=1 to a Q24 word. +pub(super) fn quantize_preserve(value: f32) -> i64 { + PeriodFilter::quantize_q24(f64::from(value)) +} + +/// A Q24 contour filter that runs at the five-frame period cadence. +/// +/// A second-order band-pass section extracts the 4..=8 Hz vibrato residual. A +/// first-order low-pass section filters the difference to get the secular +/// period below 3 Hz. Error feedback keeps the sub-unit remainders, so a step +/// converges to the exact input period. +pub(super) struct PeriodFilter { + /// The Q24 feed-forward gain of the band-pass section. + bp_b0: i64, + /// The first Q24 feedback coefficient of the band-pass section. + bp_a1: i64, + /// The second Q24 feedback coefficient of the band-pass section. + bp_a2: i64, + /// The Q24 step coefficient of the secular one-pole low-pass section. + lp_alpha: i64, + /// If `true`, the state holds a valid initial period. + seeded: bool, + /// The two previous Q24 input periods for the band-pass section. + bp_x: [i64; 2], + /// The two previous Q24 outputs of the band-pass section. + bp_y: [i64; 2], + /// The sub-unit remainder of the band-pass sum. + bp_rem: i64, + /// The current Q24 secular period estimate. + lp_y: i64, + /// The sub-unit remainder of the low-pass product. + lp_rem: i64, +} + +impl PeriodFilter { + /// Scales a finite value to Q24 with a half-unit adjustment. + fn quantize_q24(value: f64) -> i64 { + let scaled = value * f64::from(1_u32 << Q24_SHIFT); + if scaled >= 0.0 { + (scaled + 0.5) as i64 + } else { + (scaled - 0.5) as i64 + } + } + + /// Creates a cleared filter with coefficients for `rate`. + pub(super) fn new(rate: SampleRate) -> Self { + let mut filter = Self { + bp_b0: 0, + bp_a1: 0, + bp_a2: 0, + lp_alpha: 0, + seeded: false, + bp_x: [0; 2], + bp_y: [0; 2], + bp_rem: 0, + lp_y: 0, + lp_rem: 0, + }; + filter.configure(rate); + filter + } + + /// Calculates the Q24 coefficients for the five-frame update rate. + /// + /// The filter state does not change. + fn configure(&mut self, rate: SampleRate) { + let update_hz = f64::from(rate.as_u32()) / 5.0; + let q = BAND_CENTER_HZ / BAND_WIDTH_HZ; + let w0 = 2.0 * std::f64::consts::PI * BAND_CENTER_HZ / update_hz; + let sin = w0.sin(); + let cos = w0.cos(); + let alpha = sin / (2.0 * q); + let a0 = 1.0 + alpha; + self.bp_b0 = Self::quantize_q24(alpha / a0); + self.bp_a1 = Self::quantize_q24((-2.0 * cos) / a0); + self.bp_a2 = Self::quantize_q24((1.0 - alpha) / a0); + let w_lp = 2.0 * std::f64::consts::PI * SECULAR_LP_HZ / update_hz; + self.lp_alpha = Self::quantize_q24(1.0 - (-w_lp).exp()); + } + + /// Clears the filter histories and marks the filter as not seeded. + /// + /// The coefficients do not change. + pub(super) fn reset(&mut self) { + self.seeded = false; + self.bp_x = [0; 2]; + self.bp_y = [0; 2]; + self.bp_rem = 0; + self.lp_y = 0; + self.lp_rem = 0; + } + + /// Sets the secular state to `period` and clears the vibrato residual. + pub(super) fn seed(&mut self, period: Q6) { + let p_q24 = i64::from(period.to_bits()) << Q6_TO_Q24_SHIFT; + self.bp_x = [p_q24; 2]; + self.bp_y = [0; 2]; + self.bp_rem = 0; + self.lp_y = p_q24; + self.lp_rem = 0; + self.seeded = true; + } + + /// Splits `period` into a secular Q6 period and a Q14 modulation ratio. + /// + /// If the filter is not seeded yet, this call seeds the state to `period` + /// and returns unity modulation. All calculations use integer arithmetic. + pub(super) fn split(&mut self, period: Q6, preserve_q24: i64) -> (Q6, Q14) { + if period <= Q6::ZERO { + return (period, Q14::ONE); + } + if !self.seeded { + self.seed(period); + return (period, Q14::ONE); + } + let x = i64::from(period.to_bits()) << Q6_TO_Q24_SHIFT; + let acc = i128::from(self.bp_b0) * i128::from(x.wrapping_sub(self.bp_x[1])) + - i128::from(self.bp_a1) * i128::from(self.bp_y[0]) + - i128::from(self.bp_a2) * i128::from(self.bp_y[1]) + + i128::from(self.bp_rem); + let vib = (acc >> Q24_SHIFT) as i64; + self.bp_rem = (acc - (i128::from(vib) << Q24_SHIFT)) as i64; + self.bp_x[1] = self.bp_x[0]; + self.bp_x[0] = x; + self.bp_y[1] = self.bp_y[0]; + self.bp_y[0] = vib; + + let notched = x.wrapping_sub(vib); + let lp_acc = i128::from(self.lp_alpha) * i128::from(notched.wrapping_sub(self.lp_y)) + + i128::from(self.lp_rem); + let lp_step = (lp_acc >> Q24_SHIFT) as i64; + self.lp_rem = (lp_acc - (i128::from(lp_step) << Q24_SHIFT)) as i64; + self.lp_y = self.lp_y.wrapping_add(lp_step); + + let half_q6 = 1_i64 << (Q6_TO_Q24_SHIFT - 1); + let secular_bits = if self.lp_y >= 0 { + self.lp_y.saturating_add(half_q6) >> Q6_TO_Q24_SHIFT + } else { + self.lp_y.saturating_sub(half_q6) >> Q6_TO_Q24_SHIFT + }; + let secular_q6 = Q6::from_bits(secular_bits.clamp(1, i64::from(i32::MAX)) as i32); + + let half_q24 = 1_i128 << (Q24_SHIFT - 1); + let vib_prod = i128::from(vib) * i128::from(preserve_q24); + let preserved = if vib_prod >= 0 { + ((vib_prod + half_q24) >> Q24_SHIFT) as i64 + } else { + ((vib_prod - half_q24) >> Q24_SHIFT) as i64 + }; + let min_denom = (x >> 2).max(1); + let max_denom = x.saturating_mul(4); + let denom = i128::from( + self.lp_y + .saturating_add(preserved) + .clamp(min_denom, max_denom), + ); + let ratio_bits = (((i128::from(x) << 14) + (denom >> 1)) / denom) + .clamp(MIN_MOD_RATIO_BITS, MAX_MOD_RATIO_BITS) as i32; + (secular_q6, Q14::from_bits(ratio_bits)) + } +} diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..5a0a8d8 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -21,7 +21,8 @@ //! - 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 correction `humanize`, `flexTune` and `vibratoPreserve` +//! fields default to 0. //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use