diff --git a/README.md b/README.md index 83a8f47..cc413d4 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,15 @@ multi-voice mixes. `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. +`resynthesis.pitch.vocal_range` selects a frequency preset (`Auto`, `Soprano`, +`AltoTenor`, `BaritoneBass` or `Custom`). `Auto` is the default (`40..=1100` +Hz). `Custom` uses `min_frequency_hz` and `max_frequency_hz`. Both pitch +tracking and `feedback()` enforce the active limits. + +`resynthesis.pitch.sibilant_bypass` is `true` by default. Active sibilants +split at 3.5 kHz, and the high band bypasses pitch shift and harmony voices +at unity pitch with a delay of 1,593 frames. + ### Harmony sources Set `resynthesis.mode` to `Harmony`. Then select the source of the voices @@ -489,8 +498,9 @@ 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 - `resynthesis.pitch.minFrequencyHz` and `resynthesis.pitch.maxFrequencyHz`. +- The estimated frequency is outside the active bounds of + `resynthesis.pitch.vocalRange` (or `resynthesis.pitch.minFrequencyHz` and + `resynthesis.pitch.maxFrequencyHz` for `"custom"`). `formantEnvelope(maxFrequencyHz, input, output)` fills two `Float32Array` buffers of equal length and returns `false` if no envelope is available. diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..45cee99 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -169,6 +169,8 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.ok(wasmExports);", "", "const config = rootModule.defaultConfig();", + 'assert.equal(config.resynthesis.pitch.vocalRange, "auto");', + "assert.equal(config.resynthesis.pitch.sibilantBypass, true);", "const processor = new rootModule.Tunelet(48000, 128, config);", "try {", " const input = new Int16Array(128);", @@ -202,6 +204,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " loadTunelet as namedLoadTunelet,", " Tunelet,", " type ProcessorConfig,", + " type VocalRange,", `} from ${pkgLiteral};`, "import init, {", " initSync as wasmInitSync,", @@ -214,6 +217,9 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", " const exportsFromWasm: InitOutput = await init(source);", " const config: ProcessorConfig = defaultConfig();", + ' const range: VocalRange = "baritoneBass";', + " config.resynthesis.pitch.vocalRange = range;", + " config.resynthesis.pitch.sibilantBypass = true;", " const processor = new Tunelet(48000, 128, config);", " const input = new Int16Array(128);", " const left = new Int16Array(128);", diff --git a/src/lib.rs b/src/lib.rs index f17bc85..0cae3e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,11 +50,10 @@ //! //! [`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::take_feedback`] also clears the peak window. Both pitch +//! detection and feedback reports use the active [`VocalRange`] bounds. +//! [`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 @@ -133,7 +132,7 @@ pub use harmony::{ ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, }; pub use midi::MidiEvent; -pub use pitch::PitchConfig; +pub use pitch::{PitchConfig, VocalRange}; pub use processor::{Feedback, Processor, Telemetry}; pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig}; pub use scale::{CorrectionScale, NoteMask, PitchClass}; diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..749171c 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -2,8 +2,8 @@ //! 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. Both pitch tracking and host feedback enforce the +//! active [`VocalRange`] frequency limits. mod search; pub(crate) mod tracker; @@ -11,7 +11,34 @@ pub(crate) mod tracker; use crate::error::{check_range, ConfigProblem}; use crate::Error; -/// The acquisition sensitivity and the bounds for pitch reports to the host. +/// The frequency preset for pitch acquisition, pitch tracking and host reports. +/// +/// The default is [`Self::Auto`]. Presets restrict pitch detection and +/// feedback to the selected vocal register. Notes outside the active bounds +/// stay unvoiced and bypass pitch shift and harmony voices. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum VocalRange { + /// Custom bounds from `min_frequency_hz` and `max_frequency_hz` in + /// [`PitchConfig`]. + Custom, + /// The soprano register, 200..=1100 Hz. + Soprano, + /// The alto and tenor register, 100..=720 Hz. + AltoTenor, + /// The baritone and bass register, 45..=360 Hz. + BaritoneBass, + /// The full vocal register, 40..=1100 Hz. This is the default. + #[default] + Auto, +} + +/// The acquisition sensitivity, vocal range preset, custom frequency limits +/// and sibilant bypass control. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -26,42 +53,66 @@ 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 active vocal register preset. The default is [`VocalRange::Auto`]. + /// + /// [`VocalRange::Custom`] uses `min_frequency_hz` and `max_frequency_hz`. + /// The other presets use fixed frequency limits. Both the pitch tracker + /// and [`crate::Processor::feedback`] enforce the active limits. + pub vocal_range: VocalRange, + /// The custom lower bound 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. + /// [`VocalRange::Custom`] enforces this bound in pitch detection and in + /// feedback reports. Validation checks this field in all vocal ranges. pub min_frequency_hz: f32, - /// The upper bound of the feedback in hertz (inclusive), 40..=2000. + /// The custom upper bound 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`. [`VocalRange::Custom`] enforces this bound in pitch + /// detection and in feedback reports. Results outside the active bounds + /// are unvoiced, with zero frequency and zero period. pub max_frequency_hz: f32, + /// Enables the 3.5 kHz sibilant crossover split. The default is `true`. + /// + /// If this field is `true`, active sibilants split into a low band and a + /// high band. The high band bypasses pitch shift and harmony voices at + /// unity pitch. + pub sibilant_bypass: bool, } impl Default for PitchConfig { fn default() -> Self { Self { threshold: 0.1, + vocal_range: VocalRange::Auto, min_frequency_hz: 40.0, max_frequency_hz: 1100.0, + sibilant_bypass: true, } } } impl PitchConfig { - /// Applies only the bounds for host reports to a kept estimate. + /// Returns the inclusive lower and upper frequency limits in hertz for the + /// active [`VocalRange`]. + pub(crate) fn bounds(self) -> (f32, f32) { + match self.vocal_range { + VocalRange::Custom => (self.min_frequency_hz, self.max_frequency_hz), + VocalRange::Soprano => (200.0, 1100.0), + VocalRange::AltoTenor => (100.0, 720.0), + VocalRange::BaritoneBass => (45.0, 360.0), + VocalRange::Auto => (40.0, 1100.0), + } + } + + /// Applies the active frequency bounds to a kept estimate for host reports. /// /// 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 /// tracker state or the correction state. pub(crate) fn report(self, estimate: PitchEstimate) -> PitchEstimate { - if estimate.voiced - && estimate.frequency_hz >= self.min_frequency_hz - && estimate.frequency_hz <= self.max_frequency_hz - { + let (min_hz, max_hz) = self.bounds(); + if estimate.voiced && estimate.frequency_hz >= min_hz && estimate.frequency_hz <= max_hz { estimate } else { PitchEstimate::default() diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index c46ed9b..7c069fb 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -8,10 +8,9 @@ //! resolution of the period. //! //! 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. +//! minimum is at a boundary, out of range or not periodic, acquisition +//! starts again. The last usable period fills short unvoiced gaps and clears +//! on reset or unvoiced expiry. Both stages enforce the active vocal range. use super::search::{tracking_minimum, TRACKING_LAGS}; use crate::filter::{Biquad, Design}; @@ -44,13 +43,25 @@ pub(crate) struct PitchStep { } /// The number of lags that acquisition compares. -const ACQUISITION_LAGS: usize = 137; +const ACQUISITION_LAGS: usize = 305; +/// The decimated unvoiced steps before the fallback period expires. +const UNVOICED_EXPIRY_STEPS: u16 = 64; +/// The Q6 tolerance for coarse decimated candidates before full-rate tracking. +const COARSE_MARGIN: Q6 = Q6::from_bits(20 << 6); +/// The Q6 boundary tolerance that prevents restarts from window ripple. +const BOUND_SNAP: Q6 = Q6::from_bits(24); +/// The maximum Q14 normalized cycle difference for full-rate tracking. +const TRACKING_MAX_DIFF: i64 = 6226; /// The two-stage pitch tracker. /// /// The audio history and the filtered samples are Q14 words. The acquisition /// energies and cross terms are plain wrapping words. pub(crate) struct PitchTracker { + /// The fixed sample rate for period bounds and prefilter cutoffs. + rate: SampleRate, + /// The active frequency bounds in hertz, cached for configuration updates. + bounds_hz: (f32, f32), /// Two low-pass sections before the 8:1 decimation for acquisition. /// /// Full-rate tracking uses the raw audio. @@ -92,9 +103,16 @@ pub(crate) struct PitchTracker { tracking_counter: i32, /// The latest refined Q6 period. A restart of acquisition sets it to zero. period: Q6, - /// The last refined Q6 period. A restart or an audio reset does not clear - /// it. + /// The last refined Q6 period. A reset or unvoiced expiry sets it to zero. previous_period: Q6, + /// The shortest permitted Q6 period from the upper frequency limit. + min_period: Q6, + /// The longest permitted Q6 period from the lower frequency limit. + max_period: Q6, + /// The largest decimated lag index for the active lower frequency limit. + max_detection_lag: usize, + /// The count of consecutive unvoiced decimated steps. + unvoiced_count: u16, /// The Q14 threshold of the normalized difference. It applies only to the /// acceptance of acquisition minima. threshold: Q14, @@ -106,15 +124,13 @@ pub(crate) struct PitchTracker { impl PitchTracker { /// Prepares the acquisition filters and allocates the silent full-rate /// history. - /// The two supported rates use low-pass cutoffs at rate/32 and at 1.5 - /// times that cutoff. The validated sensitivity is quantized to Q14. + /// The prefilters and period bounds match the active vocal range. The + /// validated sensitivity is quantized to Q14. pub(crate) fn new(rate: SampleRate, config: PitchConfig) -> Self { - let mut pre = [Biquad::new(), Biquad::new()]; - let cutoff = rate.hz() / 16.0 / 2.0; - pre[0].set_design(Design::low_pass(rate.hz(), cutoff, 0.707)); - pre[1].set_design(Design::low_pass(rate.hz(), cutoff * 1.5, 0.707)); - Self { - pre, + let mut tracker = Self { + rate, + bounds_hz: (0.0, 0.0), + pre: [Biquad::new(), Biquad::new()], raw: vec![0; HISTORY] .into_boxed_slice() .try_into() @@ -134,22 +150,58 @@ impl PitchTracker { tracking_counter: 0, period: Q6::default(), previous_period: Q6::default(), + min_period: Q6::default(), + max_period: Q6::default(), + max_detection_lag: ACQUISITION_LAGS - 1, + unvoiced_count: 0, threshold: Q14::from_f64(config.threshold as f64), best: 0, + }; + tracker.configure_bounds(config.bounds()); + tracker + } + + /// Updates the prefilters and the Q6 period bounds for `bounds`. + fn configure_bounds(&mut self, bounds: (f32, f32)) { + if self.bounds_hz == bounds { + return; } + self.bounds_hz = bounds; + let (min_hz, max_hz) = bounds; + let rate_hz = self.rate.hz(); + let cutoff = (max_hz * 1.1).clamp(320.0, rate_hz / 32.0); + let second_cutoff = (cutoff * 1.5).min(rate_hz / 16.0 * 0.85); + self.pre[0].set_design(Design::low_pass(rate_hz, cutoff, 0.707)); + self.pre[1].set_design(Design::low_pass(rate_hz, second_cutoff, 0.707)); + let min_bits = ((rate_hz as f64 / max_hz as f64) * 64.0).ceil() as i32; + let max_bits = ((rate_hz as f64 / min_hz as f64) * 64.0).floor() as i32; + self.min_period = Q6::from_bits(min_bits.max(1)); + self.max_period = Q6::from_bits(max_bits.max(min_bits)); + let max_samples = ((self.max_period.to_bits() + 63) >> 6) as usize; + let max_dec = max_samples.div_ceil(8); + self.max_detection_lag = (2 * max_dec + 6).clamp(16, ACQUISITION_LAGS - 1); } - /// Updates only the acquisition sensitivity. - /// The reporting bounds apply outside the tracker. A change of the - /// sensitivity does not reset a tracked period. + /// Updates the acquisition sensitivity and the active vocal range bounds. + /// If the tracked period or fallback period is outside the new bounds, + /// the tracker restarts acquisition and clears the fallback period. pub(crate) fn set_config(&mut self, config: PitchConfig) { self.threshold = Q14::from_f64(config.threshold as f64); + self.configure_bounds(config.bounds()); + if !self.detecting && (self.period < self.min_period || self.period > self.max_period) { + self.restart(); + self.previous_period = Q6::ZERO; + } + if self.previous_period != Q6::ZERO + && (self.previous_period < self.min_period || self.previous_period > self.max_period) + { + self.previous_period = Q6::ZERO; + } } - /// Clears the full-rate audio, the current period and the prefilter - /// memories, and requests acquisition. - /// The acquisition tables clear at the next decimated call. The previous - /// usable period stays until another tracking update replaces it. + /// Clears the full-rate audio, both periods and the prefilter memories, + /// and requests acquisition. + /// The acquisition tables clear at the next decimated call. pub(crate) fn reset(&mut self) { let written = usize::from(self.written); if written == HISTORY { @@ -159,6 +211,8 @@ impl PitchTracker { } self.written = 0; self.write = 0; + self.previous_period = Q6::ZERO; + self.unvoiced_count = 0; self.restart(); for pre in &mut self.pre { pre.reset(); @@ -321,7 +375,7 @@ impl PitchTracker { &mut self.cross[lag..end], ); index1 = if count == index1 + 1 { - 273 + 2 * ACQUISITION_LAGS - 1 } else { index1 - count }; @@ -334,9 +388,13 @@ impl PitchTracker { } self.detection_count = self.detection_count.wrapping_add(1); if self.detection_count <= 10 { + self.unvoiced_count = self.unvoiced_count.saturating_add(1); + if self.unvoiced_count >= UNVOICED_EXPIRY_STEPS { + self.previous_period = Q6::ZERO; + } return 0; } - let maximum = ((self.detection_count - 6) / 2).min(ACQUISITION_LAGS as i32 - 1) as usize; + let maximum = ((self.detection_count - 6) / 2).min(self.max_detection_lag as i32) as usize; let mut normalized = [0_i32; ACQUISITION_LAGS]; #[allow( clippy::needless_range_loop, @@ -421,10 +479,23 @@ impl PitchTracker { best = a.wrapping_add(b) >> 1; } } + if best != 0 { + let coarse = Q6::from_bits(best.wrapping_add(2) >> 2); + if coarse + COARSE_MARGIN < self.min_period || coarse - COARSE_MARGIN > self.max_period + { + self.previous_period = Q6::ZERO; + best = 0; + } + } if best == 0 { + self.unvoiced_count = self.unvoiced_count.saturating_add(1); + if self.unvoiced_count >= UNVOICED_EXPIRY_STEPS { + self.previous_period = Q6::ZERO; + } 0 } else { - ((128_i32.wrapping_add(best)) >> 8).wrapping_sub(20) + self.unvoiced_count = 0; + ((128_i32.wrapping_add(best)) >> 8).wrapping_sub(20).max(1) } } @@ -630,7 +701,14 @@ impl PitchTracker { let mut best = tracking_minimum(|lag| { (self.tracking_energy[lag] >> 1).wrapping_sub(self.tracking_cross[lag]) }); - if best == TRACKING_LAGS - 1 || best == 0 || self.base + best as i32 <= 19 { + let best_energy = self.tracking_energy[best]; + let best_diff = (best_energy >> 1).wrapping_sub(self.tracking_cross[best]); + if best == TRACKING_LAGS - 1 + || best == 0 + || self.base + best as i32 <= 19 + || best_energy <= 0 + || i64::from(best_diff) * 16_384 > i64::from(best_energy) * TRACKING_MAX_DIFF + { self.restart(); step.restarted = true; } else { @@ -688,11 +766,27 @@ impl PitchTracker { // The lag in Q8 plus the parabolic fraction // (Q14 >> 6), rounded to Q6. let lag = self.base.wrapping_add(best as i32).wrapping_shl(8); - self.period = + let mut refined = Q6::from_bits(lag.wrapping_add(fraction >> 6).wrapping_add(2) >> 2); - self.previous_period = self.period; - self.best = best; - step.tracking_update = true; + if refined < self.min_period && self.min_period - refined <= BOUND_SNAP + { + refined = self.min_period; + } else if refined > self.max_period + && refined - self.max_period <= BOUND_SNAP + { + refined = self.max_period; + } + if refined < self.min_period || refined > self.max_period { + self.restart(); + self.previous_period = Q6::ZERO; + step.restarted = true; + } else { + self.period = refined; + self.previous_period = refined; + self.unvoiced_count = 0; + self.best = best; + step.tracking_update = true; + } } } } diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..15ea8e1 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -517,8 +517,6 @@ impl Processor { /// - the random stream and the arctangent lookup position of Punch /// - the reverb low-pass memories and the reverb write position /// - correction key 127 and the active correction note table - /// - the last usable period of the pitch tracker, which fills unvoiced - /// gaps /// - the harmony gain envelopes and the last voice ratios of the harmony /// controller /// - the prepared chord targets of the named and degree chord sources @@ -725,7 +723,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 active bounds of /// [`crate::PitchConfig`]. pub period_samples: f32, /// The reported input pitch frequency in hertz. @@ -749,11 +747,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 - /// selected target does not give `None`. + /// outside the active bounds of [`crate::PitchConfig`]. 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 active bounds of [`crate::PitchConfig`]. /// /// This is not an amplitude gate or a confidence score. A tracking result /// can stay between detector updates. diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..da4794a 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -166,8 +166,8 @@ impl CorrectionConfig { tsify(large_number_types_as_bigints) )] pub struct ResynthesisConfig { - /// The acquisition sensitivity and the reporting bounds. The - /// default is [`PitchConfig::default`]. + /// The acquisition sensitivity, vocal range, custom bounds and sibilant + /// bypass. The default is [`PitchConfig::default`]. pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled /// chromatic correction with a retune time of zero. @@ -345,6 +345,22 @@ const CONTROL_DUE: i32 = 100; const DRIFT_LIMIT: Q14 = Q14::from_bits(3276); /// The step for each frame of the crossfade after a reader jump. const FADE_STEP: Q14 = Q14::from_bits(0x333); +/// The crossover frequency in hertz between the voiced low band and the +/// unshifted sibilant high band. +const SIBILANT_CROSSOVER_HZ: f32 = 3500.0; +/// The quality factor of each Butterworth section in the fourth-order +/// Linkwitz-Riley crossover. +const SIBILANT_CROSSOVER_Q: f32 = std::f32::consts::FRAC_1_SQRT_2; +/// The per-frame Q14 attack step for the sibilant crossover blend. +const SIBILANT_ATTACK: Q14 = Q14::from_bits(256); +/// The per-frame Q14 release step for the sibilant crossover blend. +const SIBILANT_RELEASE: Q14 = Q14::from_bits(128); +/// The minimum Q14 high-band envelope share that activates sibilant split. +const SIBILANT_RATIO_MIN: Q14 = Q14::from_bits(1638); +/// The minimum high-band zero-cross count in a 64-frame window. +const SIBILANT_ZCR_MIN: u32 = 9; +/// The minimum Q20 high-band rectified level that activates sibilant split. +const SIBILANT_HIGH_FLOOR: i32 = 8 << 6; /// Returns the reader position at the start of the history frame `frame`. #[inline] @@ -486,6 +502,34 @@ pub(crate) struct Resynthesis { /// The previous Q14 synthesized output for each channel. The glottal /// envelope uses it. previous_output: [Q14; 2], + /// Two 3.5 kHz low-pass sections for the voiced crossover branch. + sibilant_low: [Biquad; 2], + /// Two 3.5 kHz high-pass sections for the unshifted sibilant branch. + sibilant_high: [Biquad; 2], + /// The Q20 rectified amplitude follower of the low crossover band. + sibilant_low_env: i32, + /// The Q20 rectified amplitude follower of the high crossover band. + sibilant_high_env: i32, + /// The last 64 high-band zero-cross flags. + sibilant_zcr_high: u64, + /// The last 64 full-band zero-cross flags. + sibilant_zcr_full: u64, + /// The previous full-band Q14 input sample for zero-cross detection. + sibilant_prev_sample: Q14, + /// The previous high-band Q14 sample for zero-cross detection. + sibilant_prev_high: Q14, + /// The smoothed Q14 crossover weight, from 0 (full band) to 1 (split). + sibilant_mix: Q14, + /// The 441-frame delay for the voiced branch when formants are disabled. + voiced_delay: [Q14; ANALYSIS_FRAMES], + /// The next slot in `voiced_delay`. + voiced_index: usize, + /// The previous Q14 sample of the voiced branch for formant pre-emphasis. + prev_voiced: Q14, + /// The 1,593-frame delay that aligns the high band to `LATENCY_FRAMES`. + sibilant_delay: [Q14; LATENCY_FRAMES], + /// The next slot in `sibilant_delay`. + sibilant_index: usize, } impl Resynthesis { @@ -554,6 +598,34 @@ impl Resynthesis { drift_decay: Q14::ZERO, drift_amount: Q14::ZERO, previous_output: [Q14::ZERO; 2], + sibilant_low: { + let mut filters = [Biquad::new(), Biquad::new()]; + let design = + Design::low_pass(rate.hz(), SIBILANT_CROSSOVER_HZ, SIBILANT_CROSSOVER_Q); + filters[0].set_design(design); + filters[1].set_design(design); + filters + }, + sibilant_high: { + let mut filters = [Biquad::new(), Biquad::new()]; + let design = + Design::high_pass(rate.hz(), SIBILANT_CROSSOVER_HZ, SIBILANT_CROSSOVER_Q); + filters[0].set_design(design); + filters[1].set_design(design); + filters + }, + sibilant_low_env: 0, + sibilant_high_env: 0, + sibilant_zcr_high: 0, + sibilant_zcr_full: 0, + sibilant_prev_sample: Q14::ZERO, + sibilant_prev_high: Q14::ZERO, + sibilant_mix: Q14::ZERO, + voiced_delay: [Q14::ZERO; ANALYSIS_FRAMES], + voiced_index: 0, + prev_voiced: Q14::ZERO, + sibilant_delay: [Q14::ZERO; LATENCY_FRAMES], + sibilant_index: 0, }; result.configure_coefficients(); result.configure_shift_filters(); @@ -740,6 +812,32 @@ impl Resynthesis { for filter in &mut self.post { filter.reset(); } + for filter in &mut self.sibilant_low { + filter.reset(); + } + for filter in &mut self.sibilant_high { + filter.reset(); + } + if written >= ANALYSIS_FRAMES { + self.voiced_delay.fill(Q14::ZERO); + } else if written > 0 { + self.voiced_delay[..written].fill(Q14::ZERO); + } + self.voiced_index = 0; + self.prev_voiced = Q14::ZERO; + if written >= LATENCY_FRAMES { + self.sibilant_delay.fill(Q14::ZERO); + } else if written > 0 { + self.sibilant_delay[..written].fill(Q14::ZERO); + } + self.sibilant_index = 0; + self.sibilant_low_env = 0; + self.sibilant_high_env = 0; + self.sibilant_zcr_high = 0; + self.sibilant_zcr_full = 0; + self.sibilant_prev_sample = Q14::ZERO; + self.sibilant_prev_high = Q14::ZERO; + self.sibilant_mix = Q14::ZERO; self.create_delays(); self.drift_ratio.fill(Q14::ONE); self.old_position = self.positions[0]; @@ -1107,8 +1205,56 @@ impl Resynthesis { self.written += 1; } self.raw[self.write] = sample; + let mut low = sample; + for filter in &mut self.sibilant_low { + low = filter.process_sample(low); + } + let mut high = sample; + for filter in &mut self.sibilant_high { + high = filter.process_sample(high); + } + let crossed_full = (sample.to_bits() ^ self.sibilant_prev_sample.to_bits()) < 0 + && (sample.abs() > Q14::from_bits(8) + || self.sibilant_prev_sample.abs() > Q14::from_bits(8)); + self.sibilant_prev_sample = sample; + self.sibilant_zcr_full = (self.sibilant_zcr_full << 1) | u64::from(crossed_full); + let crossed_high = (high.to_bits() ^ self.sibilant_prev_high.to_bits()) < 0 + && (high.abs() > Q14::from_bits(4) + || self.sibilant_prev_high.abs() > Q14::from_bits(4)); + self.sibilant_prev_high = high; + self.sibilant_zcr_high = (self.sibilant_zcr_high << 1) | u64::from(crossed_high); + self.sibilant_low_env = clamp_i32( + (i64::from(self.sibilant_low_env) * 63 + (i64::from(low.abs().to_bits()) << 6)) >> 6, + ); + self.sibilant_high_env = clamp_i32( + (i64::from(self.sibilant_high_env) * 63 + (i64::from(high.abs().to_bits()) << 6)) >> 6, + ); + let sibilant_active = if self.config.pitch.sibilant_bypass + && self.sibilant_high_env > SIBILANT_HIGH_FLOOR + { + let total_env = i64::from(self.sibilant_low_env) + i64::from(self.sibilant_high_env); + let high_ratio = if total_env > 0 { + Q14::from_bits(clamp_i32( + (i64::from(self.sibilant_high_env) << 14) / total_env, + )) + } else { + Q14::ZERO + }; + let zcr_high = self.sibilant_zcr_high.count_ones(); + let zcr_full = self.sibilant_zcr_full.count_ones(); + high_ratio >= SIBILANT_RATIO_MIN + && (zcr_high >= SIBILANT_ZCR_MIN || zcr_full >= SIBILANT_ZCR_MIN) + } else { + false + }; + if sibilant_active { + self.sibilant_mix = (self.sibilant_mix + SIBILANT_ATTACK).min(Q14::ONE); + } else { + self.sibilant_mix = (self.sibilant_mix - SIBILANT_RELEASE).max(Q14::ZERO); + } + let voiced_sample = sample.mul(Q14::ONE - self.sibilant_mix) + low.mul(self.sibilant_mix); let was_tracking = !self.pitch.is_detecting(); - let step = self.pitch.process_sample(sample.to_bits()); + let step = self.pitch.process_sample(voiced_sample.to_bits()); 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 @@ -1157,21 +1303,34 @@ impl Resynthesis { self.periods[write] = step.period; self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; + let delayed_voiced = self.voiced_delay[self.voiced_index]; + self.voiced_delay[self.voiced_index] = voiced_sample; + self.voiced_index += 1; + if self.voiced_index == ANALYSIS_FRAMES { + self.voiced_index = 0; + } + let previous_voiced = self.prev_voiced; + self.prev_voiced = voiced_sample; + let aligned_high = self.sibilant_delay[self.sibilant_index]; + self.sibilant_delay[self.sibilant_index] = high.mul(self.sibilant_mix); + self.sibilant_index += 1; + if self.sibilant_index == LATENCY_FRAMES { + self.sibilant_index = 0; + } self.overlap_index += 1; if self.overlap_index == OVERLAP_FRAMES { self.overlap_index = 0; } self.overlap[self.overlap_index] = if self.config.formant.enabled { - let previous = self.raw[ring(write as i32 - 1)]; Q14::from_bits(self.formant.process_analysis( - sample.to_bits(), - previous.to_bits(), + voiced_sample.to_bits(), + previous_voiced.to_bits(), self.periods.as_slice(), write, step.previous_period.to_bits(), )) } else { - self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] + delayed_voiced }; // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by // the same number of frames in the overlap ring. Then the total delay @@ -1365,6 +1524,9 @@ impl Resynthesis { *sum = sum.mul(cosine); } } + for sum in &mut mix { + *sum = *sum + aligned_high; + } // The dry branch is the delayed raw input. It bypasses the shift // filters, the voice readers, the formant stages and the harmonic // modulation. Calculate the Q22 blend in `i64`, then shift and clamp diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..40607d4 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -366,8 +366,9 @@ 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 - /// `minFrequencyHz` and `maxFrequencyHz` of the pitch configuration. + /// - The estimated frequency is outside the active bounds of the pitch + /// configuration (`vocalRange`, or `minFrequencyHz` and `maxFrequencyHz` + /// for `"custom"`). /// /// # Errors ///