diff --git a/README.md b/README.md index 83a8f47..b9066c9 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ browsers and Node.js. - **No dependencies**: The default Rust build has no dependencies and uses only safe Rust. -The input is mono signed 16-bit PCM at 44.1 kHz or 48 kHz. The output is -stereo or mono 16-bit PCM. +The input is mono signed 16-bit PCM at 8, 16, 22.05, 24, 32, 44.1, 48, +88.2, 96 or 192 kHz. The output is stereo or mono 16-bit PCM. ## Installation @@ -176,7 +176,8 @@ limits. Decrease `output_gain` to prevent `-32767..=32767` clipping on 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. +dry path starts after Warm and adds the overlap delay (approximately 35 ms; +1,543 frames at 44.1 kHz). ### Harmony sources @@ -299,7 +300,7 @@ These calls read the state of the processor. They do not change the audio. | `take_feedback()` | The same data as `feedback()`, and clears the peak window | | `telemetry()` | Data for meters and displays (refer to the list below) | | `take_telemetry()` | The same data as `telemetry()`, and clears its three peak windows | -| `latency_frames()` | 1,593 frames of nominal resynthesis latency at both sample rates | +| `latency_frames()` | Nominal resynthesis latency in frames for the prepared sample rate | | `formant_envelope()` | The LPC envelopes before and after the formant controls | The telemetry includes these items: diff --git a/src/config.rs b/src/config.rs index 75bcd82..dd50bf3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -11,26 +11,51 @@ use std::num::NonZeroUsize; /// The sample rate of the input and the output. /// -/// The default is 44.1 kHz. The prepared delay and filter layouts support only -/// the listed rates. To convert an integer device rate, use -/// [`SampleRate::try_from`]. The rate of a processor is fixed at construction. -/// To change the rate, you must make a new processor. +/// The default is 44.1 kHz. The prepared delay and filter layouts support ten +/// standard voice, WebRTC and studio rates from 8 kHz to 192 kHz. To convert +/// an integer device rate, use [`SampleRate::try_from`]. The rate of a +/// processor is fixed at construction. To change the rate, you must make a new +/// processor. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[non_exhaustive] pub enum SampleRate { + /// 8 kHz. + Hz8000, + /// 16 kHz. + Hz16000, + /// 22.05 kHz. + Hz22050, + /// 24 kHz. + Hz24000, + /// 32 kHz. + Hz32000, /// 44.1 kHz. #[default] Hz44100, /// 48 kHz. Hz48000, + /// 88.2 kHz. + Hz88200, + /// 96 kHz. + Hz96000, + /// 192 kHz. + Hz192000, } impl SampleRate { /// Returns the rate in hertz. pub const fn as_u32(self) -> u32 { match self { + Self::Hz8000 => 8_000, + Self::Hz16000 => 16_000, + Self::Hz22050 => 22_050, + Self::Hz24000 => 24_000, + Self::Hz32000 => 32_000, Self::Hz44100 => 44_100, Self::Hz48000 => 48_000, + Self::Hz88200 => 88_200, + Self::Hz96000 => 96_000, + Self::Hz192000 => 192_000, } } @@ -48,12 +73,21 @@ impl TryFrom for SampleRate { /// # Errors /// /// Returns [`Error::UnsupportedSampleRate`] with `hz`, unless the value is - /// exactly 44,100 or 48,000. The function does not resample and does not - /// select the nearest rate. + /// 8,000, 16,000, 22,050, 24,000, 32,000, 44,100, 48,000, 88,200, 96,000 + /// or 192,000. The function does not resample and does not select the + /// nearest rate. fn try_from(hz: u32) -> Result { match hz { + 8_000 => Ok(Self::Hz8000), + 16_000 => Ok(Self::Hz16000), + 22_050 => Ok(Self::Hz22050), + 24_000 => Ok(Self::Hz24000), + 32_000 => Ok(Self::Hz32000), 44_100 => Ok(Self::Hz44100), 48_000 => Ok(Self::Hz48000), + 88_200 => Ok(Self::Hz88200), + 96_000 => Ok(Self::Hz96000), + 192_000 => Ok(Self::Hz192000), _ => Err(Error::UnsupportedSampleRate { hz }), } } diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 5e1f509..8fb402e 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -2,12 +2,32 @@ use crate::error::check_count; use crate::numeric::fixed::{Fixed, Q14}; -use crate::Error; +use crate::{Error, SampleRate}; -/// The number of history frames that the loop reads from. -const HISTORY_FRAMES: usize = 192_000; -/// The number of frames for the boundary fade at each loop boundary. -const FADE_FRAMES: usize = 200; +/// Returns the stereo history capacity in frames for `rate` (approximately +/// four seconds; 192,000 frames at 44.1 and 48 kHz). +const fn history_frames(rate: SampleRate) -> usize { + match rate { + SampleRate::Hz8000 => 32_000, + SampleRate::Hz16000 => 64_000, + SampleRate::Hz22050 | SampleRate::Hz24000 => 96_000, + SampleRate::Hz32000 => 128_000, + SampleRate::Hz44100 | SampleRate::Hz48000 => 192_000, + SampleRate::Hz88200 | SampleRate::Hz96000 => 384_000, + SampleRate::Hz192000 => 768_000, + } +} + +/// Returns the boundary fade length in frames (~4.54 ms; 200 frames at +/// 44.1 kHz). +const fn fade_frames(rate: SampleRate) -> usize { + let frames = (200 * rate.as_u32() as usize + 22_050) / 44_100; + if frames < 1 { + 1 + } else { + frames + } +} /// Reverse playback of recent stereo audio in repeated loops with fades. /// @@ -15,7 +35,8 @@ const FADE_FRAMES: usize = 200; /// also when Alien is disabled. Thus, when you enable Alien, it can play /// audio that it recorded during bypass. A change of the loop length keeps /// the history and clamps the current phase into the new loop. The boundary -/// fades are 200 frames long at all sample rates. +/// fades scale with the sample rate (approximately 4.54 ms; 200 frames at +/// 44.1 kHz). #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -28,10 +49,12 @@ pub struct AlienConfig { /// `false`. The recording and the phase continue to advance in both /// states. pub enabled: bool, - /// The loop length in frames, 1..=96000. The default is 95,999. - /// This value is a frame count at the two rates. Thus, its duration in - /// seconds changes with the sample rate. A short loop can be fully inside - /// the fades. + /// The loop length in frames, 1..=384000. The default is 95,999. + /// + /// This value is a frame count, so its duration in seconds changes with + /// the sample rate. The active loop clamps to half of the prepared + /// history capacity (approximately two seconds; 96,000 frames at 44.1 and + /// 48 kHz). A short loop can be fully inside the fades. pub loop_frames: u32, } impl Default for AlienConfig { @@ -53,7 +76,7 @@ impl AlienConfig { /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 96_000) + check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 384_000) } } @@ -63,34 +86,38 @@ impl AlienConfig { pub(crate) struct Alien { /// The validated controls, which include the selection of the wet output. config: AlienConfig, - /// 192,000 stereo Q14 frames, which are allocated one time at - /// construction. + /// The boundary fade length in frames for the prepared rate. + fade_frames: usize, + /// The stereo Q14 history frames, allocated one time at construction. buffer: Vec<[Q14; 2]>, /// The current recording position. The position of the reverse reader /// comes from this cursor. read: usize, /// The current frame in the loop. It is always less than `loop_len`. phase: usize, - /// The validated loop length. It is not more than half of the history + /// The active loop length. It is not more than half of the history /// capacity. loop_len: usize, } impl Alien { /// Allocates a silent stereo ring from validated loop settings. - pub(crate) fn new(config: AlienConfig) -> Self { + pub(crate) fn new(rate: SampleRate, config: AlienConfig) -> Self { + let history = history_frames(rate); + let loop_len = (config.loop_frames as usize).min(history / 2); Self { config, - buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], + fade_frames: fade_frames(rate), + buffer: vec![[Q14::default(); 2]; history], read: 0, phase: 0, - loop_len: config.loop_frames as usize, + loop_len, } } /// Applies a validated configuration, keeps the recorded audio and clamps /// the phase into the new loop, which is not empty. pub(crate) fn set_config(&mut self, config: AlienConfig) { self.config = config; - self.loop_len = config.loop_frames as usize; + self.loop_len = (config.loop_frames as usize).min(self.buffer.len() / 2); self.phase = self.phase.min(self.loop_len - 1); } /// Returns the loop length and the current frame in the loop. @@ -111,21 +138,22 @@ impl Alien { /// both cursors. /// The recording cursor moves forward by one and the reverse offset /// increases by two. Thus, the playback moves backward by one frame. The - /// validated loop limit keeps that subtraction in a single ring wrap. + /// active loop limit keeps that subtraction in a single ring wrap. pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] { + let history = self.buffer.len(); self.buffer[self.read] = input; let result = if self.config.enabled { - let read = self.read + HISTORY_FRAMES - self.phase * 2; - let read = if read >= HISTORY_FRAMES { - read - HISTORY_FRAMES + let read = self.read + history - self.phase * 2; + let read = if read >= history { + read - history } else { read }; let distance = self.phase.min(self.loop_len - self.phase); let mut result = self.buffer[read]; - if distance < FADE_FRAMES { + if distance < self.fade_frames { let gain: Q14 = Fixed::<0>::from_bits(distance as i32) - .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); + .div(Fixed::<0>::from_bits(self.fade_frames as i32)); result = result.map(|sample| sample.mul::<14, 14>(gain)); } result @@ -133,7 +161,7 @@ impl Alien { input }; self.read += 1; - if self.read == HISTORY_FRAMES { + if self.read == history { self.read = 0; } self.phase += 1; @@ -144,14 +172,15 @@ impl Alien { } } -/// Returns the finite tail budget: two loop lengths plus the boundary +/// Returns the finite tail budget: two active loop lengths plus the boundary /// fade. /// /// The value is zero when Alien is disabled. It is a configured budget, /// not a measured tail. -pub(crate) fn tail_frames(config: AlienConfig) -> usize { +pub(crate) fn tail_frames(rate: SampleRate, config: AlienConfig) -> usize { if config.enabled { - 2 * config.loop_frames as usize + FADE_FRAMES + let loop_len = (config.loop_frames as usize).min(history_frames(rate) / 2); + 2 * loop_len + fade_frames(rate) } else { 0 } diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..c0ec1c8 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -6,8 +6,17 @@ use crate::numeric::fixed::{Q14, Q8}; use crate::numeric::{coefficient_to_exp_value, db_to_gain, envelope_decay, NumericContext}; use crate::{Error, SampleRate}; -/// The update interval of the peak follower, in frames. -const WINDOW_FRAMES: usize = 100; +/// Returns the peak-follower update interval in frames (~2.27 ms; 100 frames +/// at 44.1 kHz). +const fn window_frames(rate: SampleRate) -> usize { + let frames = (100 * rate.as_u32() as usize + 22_050) / 44_100; + if frames < 1 { + 1 + } else { + frames + } +} + /// The base arctangent drive, approximately π/2 in Q8. const BASE_DRIVE: Q8 = Q8::from_bits(401); /// The 2/π factor in Q14 that normalizes the arctangent output. @@ -16,9 +25,10 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430); /// The input gain and the transient enhancement with arctangent saturation. /// /// Punch comes before Warm and before pitch detection. It finds the peak of -/// each window of 100 processed frames. Two envelope followers set the drive -/// from these peaks. When Punch is disabled, it does not process audio, and -/// its envelope and window state do not change. +/// each window of processed frames (approximately 2.27 ms; 100 frames at +/// 44.1 kHz). Two envelope followers set the drive from these peaks. When +/// Punch is disabled, it does not process audio, and its envelope and window +/// state do not change. /// /// A gain change updates the cached drive at the next boundary of the peak /// window. A reset calculates that drive again immediately from the @@ -36,7 +46,7 @@ pub struct PunchConfig { /// The input gain in decibels, -96..=12. /// /// The default is 0 dB. The saturation drive from this gain changes at the - /// next 100-frame peak boundary. + /// next boundary of the peak window. pub gain_db: f32, /// The transient emphasis without a unit, 0..=1. /// @@ -52,7 +62,7 @@ pub struct PunchConfig { /// The attack half-life of the peak follower in milliseconds, 0.01..=5000. /// /// The default is 10 ms. The coefficients include the effect of the - /// 100-frame update interval. + /// peak-window update interval. pub attack_ms: f32, } impl Default for PunchConfig { @@ -91,12 +101,14 @@ impl PunchConfig { pub(crate) struct Punch { /// The prepared rate, which converts the envelope times to sample windows. rate: SampleRate, + /// The peak-window length in frames for `rate`. + window_frames: usize, /// The adaptive Q14 peak envelope. The impact control sets its release. slow: Q14, /// The second Q14 peak envelope, with a fixed release half-life of 5 /// seconds. fast: Q14, - /// The number of samples in the current 100-frame peak window. + /// The number of samples in the current peak window. counter: usize, /// The largest absolute Q14 input in the current window. peak: Q14, @@ -119,6 +131,7 @@ impl Punch { pub(crate) fn new(rate: SampleRate, config: PunchConfig) -> Self { let mut result = Self { rate, + window_frames: window_frames(rate), slow: Q14::default(), fast: Q14::default(), counter: 0, @@ -151,7 +164,7 @@ impl Punch { Q14::from_f64(envelope_decay( milliseconds, self.rate.hz() as f64, - WINDOW_FRAMES, + self.window_frames, )) }; self.slow_decay = decay(impact as f64); @@ -179,7 +192,7 @@ impl Punch { target + decay.mul(current - target) } - /// Tracks the current peak, updates the drive every 100 calls and + /// Tracks the current peak, updates the drive at each window boundary and /// saturates one PCM sample. /// The envelope ratio is approximately limited to 16 before it is /// multiplied by the input gain. While the adaptive envelope is zero, the @@ -189,7 +202,7 @@ impl Punch { let sample = Q14::from_bits(i32::from(input) >> 1); self.peak = self.peak.max(sample.abs()); self.counter += 1; - if self.counter == WINDOW_FRAMES { + if self.counter == self.window_frames { self.counter = 0; self.slow = Self::follow(self.slow, self.peak, self.attack_decay, self.slow_decay); self.fast = Self::follow(self.fast, self.peak, self.attack_decay, self.fast_decay); diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index 05155ea..ac521f1 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -525,13 +525,12 @@ struct ReverbLayout { /// 0.8 ms at the prepared rate. Both channels use it. binaural_offset: usize, } -/// Prepares the taps for 44.1 or 48 kHz from the 44.1 kHz reference -/// distances. +/// Prepares the taps and the buffer capacity for `rate` from the 44.1 kHz +/// reference distances. /// -/// The distances are truncated after the scaling. Adjacent taps stay one -/// frame apart. The base of the second network stays at frame 9,000, and the -/// total capacity stays at 17,000. These limits are correct only for the two -/// supported sample rates. +/// The function truncates each distance after it scales the distance. +/// Adjacent taps stay one frame apart. Both the base of the second network +/// and the total capacity scale with the sample rate. fn reverb_layout(rate: f32) -> ReverbLayout { let scale = |samples: f64| (rate as f64 / 44100.0 * samples) as usize; let mut taps = [0; 67]; @@ -572,7 +571,7 @@ fn reverb_layout(rate: f32) -> ReverbLayout { for (index, prior) in [(6, 5), (8, 7), (13, 12), (20, 19), (23, 22), (29, 28)] { taps[index] = taps[prior] + 1; } - let base = 9000; + let base = scale(9000.0); taps[40] = base; taps[41] = base + 1; taps[42] = base + 2; @@ -606,7 +605,7 @@ fn reverb_layout(rate: f32) -> ReverbLayout { taps[59] = taps[58] + 1; ReverbLayout { taps, - capacity: 17000, + capacity: scale(17000.0), binaural_offset: (rate as f64 * 0.8 * 0.001) as usize, } } diff --git a/src/effects/warm.rs b/src/effects/warm.rs index 9721ced..73831ba 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -6,16 +6,24 @@ use crate::numeric::db_to_gain; use crate::numeric::fixed::{Fixed, Q12, Q14, Q8}; use crate::{Error, SampleRate}; -/// The update interval of the peak follower, in frames. -const WINDOW_FRAMES: usize = 100; +/// Returns the peak-follower update interval in frames (~2.27 ms; 100 frames +/// at 44.1 kHz). +const fn window_frames(rate: SampleRate) -> usize { + let frames = (100 * rate.as_u32() as usize + 22_050) / 44_100; + if frames < 1 { + 1 + } else { + frames + } +} /// Asymmetric input saturation, followed by a 50 Hz high-pass filter. /// /// Warm operates after Punch and before pitch detection. Its adaptive -/// normalization updates every 100 enabled frames. When Warm is disabled, -/// the envelope and filter histories do not change. When Warm is enabled -/// again, they continue from their last state, unless the processor was -/// reset. +/// normalization updates after each window of enabled frames (approximately +/// 2.27 ms; 100 frames at 44.1 kHz). When Warm is disabled, the envelope and +/// filter histories do not change. When Warm is enabled again, they continue +/// from their last state, unless the processor was reset. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -59,11 +67,13 @@ impl WarmConfig { /// filter. #[derive(Debug)] pub(crate) struct Warm { + /// The peak-window length in frames for the prepared rate. + window_frames: usize, /// The 50 Hz one-pole high-pass output filter. filter: Biquad, /// The kept Q14 peak envelope from completed windows. peak: Q14, - /// The largest absolute Q14 sample in the current 100-frame window. + /// The largest absolute Q14 sample in the current peak window. window_peak: Q14, /// The number of enabled samples in this window. counter: usize, @@ -87,15 +97,19 @@ impl Warm { /// Prepares the fixed high-pass filter and the initial normalization /// state. pub(crate) fn new(rate: SampleRate, config: WarmConfig) -> Self { + let window_frames = window_frames(rate); let mut filter = Biquad::new(); filter.set_design(Design::high_pass_one_pole(rate.hz(), 50.0)); let mut result = Self { + window_frames, filter, peak: Q14::default(), window_peak: Q14::default(), counter: 0, compression: Q8::ONE, - smooth: Q14::from_f64(0.5_f64.powf(1.0 / (rate.hz() as f64 * 0.2 / 100.0))), + smooth: Q14::from_f64( + 0.5_f64.powf(1.0 / (rate.hz() as f64 * 0.2 / window_frames as f64)), + ), drive: Q12::default(), output_gain: Q14::default(), input_threshold: Q14::from_f64(db_to_gain(-30.0)), @@ -141,7 +155,7 @@ impl Warm { let mut sample = Q14::from_bits(i32::from(input) >> 1); self.window_peak = self.window_peak.max(sample.abs()); self.counter += 1; - if self.counter == WINDOW_FRAMES { + if self.counter == self.window_frames { self.counter = 0; self.peak = if sample.abs() > self.peak { sample.abs() diff --git a/src/formant.rs b/src/formant.rs index 8bb37f3..114dc14 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -1,28 +1,30 @@ //! LPC analysis that uses the pitch, changes to the vocal-tract shape, and //! spectral synthesis. //! -//! Pre-emphasis removes a simple glottal envelope from the input. Every 441 -//! frames, the analysis makes a 50th-order predictor from a segment that is -//! aligned to the pitch. If no pitch is available, the segment is -//! approximately 10 ms. The correlations are normalized, weighted and -//! smoothed. Then they become reflection coefficients. If width or stretch +//! Pre-emphasis removes a simple glottal envelope from the input. Every +//! `analysis_frames` (~10 ms), the analysis makes a rate-scaled predictor from +//! a segment that is aligned to the pitch. If no pitch is available, the +//! segment is approximately 10 ms. The correlations are normalized, weighted +//! and smoothed. Then they become reflection coefficients. If width or stretch //! is not 1, the code changes the reflection coefficients into tract areas. //! Then it changes these areas into a synthesis model. //! //! Thirty model banks keep the history of the coefficients. Each audio frame //! stores a pair of banks and a blend. Thus, a fractional voice reader can //! find the model that applies to the audio that it reads again. The inverse -//! filter has a delay of 441 frames. Resynthesis uses this delay to align -//! each source sample with the stamp of the frame that filtered it. Audio -//! and coefficients use Q14 words. All areas use one common scale that the -//! code sets at runtime. The order of the arithmetic and of the rescale +//! filter has a delay of `analysis_frames`. Resynthesis uses this delay to +//! align each source sample with the stamp of the frame that filtered it. +//! Audio and coefficients use Q14 words. All areas use one common scale that +//! the code sets at runtime. The order of the arithmetic and of the rescale //! operations changes the output samples. use crate::error::check_range; use crate::filter::{Biquad, Design}; use crate::lpc; use crate::numeric::fixed::{Q14, Q6}; -use crate::numeric::{clamp_i32, db_to_gain, fast_sinc, mul14, round_q14, NumericContext}; +use crate::numeric::{ + clamp_i32, db_to_gain, fast_sinc, history_frames, mul14, round_q14, NumericContext, +}; use crate::{Error, SampleRate}; /// The controls for vocal-tract changes and synthesized aspiration during @@ -104,18 +106,30 @@ impl FormantConfig { } } -/// The number of frames of input history for analysis and synthesis. The -/// value is equal to the resynthesis history length. -pub(crate) const HISTORY_FRAMES: usize = 11568; -/// The number of frames in each analysis step. The analysis output has a -/// delay of this number of frames. -pub(crate) const ANALYSIS_FRAMES: usize = 441; -/// The order of the input LPC predictor and of the synthesis model without -/// changes. -const ORDER: usize = 50; -/// The capacity for stretched models and synthesis feedback. A valid -/// stretch uses a maximum of 99. -const MAX_ORDER: usize = 110; +/// Returns the number of frames in each 10 ms formant analysis step at `rate`. +/// +/// The analysis output has a delay equal to this count (441 frames at +/// 44.1 kHz). +pub(crate) const fn analysis_frames(rate: SampleRate) -> usize { + (rate.as_u32() as usize + 50) / 100 +} + +/// Returns the LPC predictor order for `rate`, scaled from 50 at 44.1 kHz. +/// +/// This order preserves the vocal-tract pole interval across sample rates. +const fn predictor_order(rate: SampleRate) -> usize { + (50 * rate.as_u32() as usize + 22_050) / 44_100 +} + +/// Returns the synthesis filter capacity for a stretched model of `order`. +/// +/// The capacity is 110 at 44.1 kHz and 480 at 192 kHz. +const fn max_synthesis_order(order: usize) -> usize { + (order * 22).div_ceil(10) +} + +/// The stack buffer ceiling for synthesis orders up to 192 kHz (`480`). +const MAX_SYNTHESIS_ORDER: usize = 480; /// The number of coefficient banks in the ring. The stamps of the audio /// history refer to these banks. const BANKS: usize = 30; @@ -154,23 +168,32 @@ pub(crate) struct Formant { /// The sample rate for analysis windows, glottal decay and the aspiration /// filter. rate: SampleRate, + /// The number of frames of input history, aligned with resynthesis. + history_frames: usize, + /// The number of frames in each analysis step. + analysis_frames: usize, + /// The order of the input LPC predictor for the prepared sample rate. + order: usize, + /// The capacity for stretched models at the prepared sample rate. + max_order: usize, + /// The Q14 increment of `blend` per input frame. + blend_step: i32, /// The ring of pre-emphasized Q14 audio words. It is aligned with the /// resynthesis history. - input: Vec, - /// The preallocated segment memory for period folding and - /// autocorrelation. - temporary: Vec, - /// The Q14 coefficient banks for the inverse filter. Only the first ORDER - /// coefficients are used. - inverse: Vec<[i32; MAX_ORDER]>, - /// The Q14 coefficient banks for the forward filter. `orders` holds the - /// active lengths. - models: Vec<[i32; MAX_ORDER]>, + input: Box<[i32]>, + /// The preallocated segment memory for period sums and autocorrelation. + temporary: Box<[i32]>, + /// The flat Q14 coefficient banks (`BANKS * max_order`) for the inverse + /// filter. Only the first `order` entries of each bank are used. + inverse: Box<[i32]>, + /// The flat Q14 coefficient banks (`BANKS * max_order`) for the forward + /// filter. `orders` holds the active lengths. + models: Box<[i32]>, /// The valid synthesis order for each bank. Zero means that there is no /// feedback model. orders: [usize; BANKS], /// One record of a bank pair and a blend for each frame of input history. - stamps: Vec, + stamps: Box<[Stamp]>, /// The index of the current coefficient bank. current: usize, /// The bank before `current`. The stage keeps it while the coefficients @@ -184,15 +207,20 @@ pub(crate) struct Formant { design_counter: i32, /// The separate Q14 feedback histories of the synthesis, for the left and /// right channels. Mono synthesis uses channel zero. - history: [[i32; MAX_ORDER]; 2], + history: [Box<[i32]>; 2], /// The next slot in the synthesis history. The two channels use the same /// slot. history_index: usize, - /// The two previous normalized autocorrelation vectors for the moving - /// average. - correlation_history: [[i32; 111]; 2], + /// The two previous normalized autocorrelation vectors for the average. + correlation_history: [Box<[i32]>; 2], /// The wrapped sum of the stored correlation vectors, each divided by two. - correlation_sum: [i32; 111], + correlation_sum: Box<[i32]>, + /// Preallocated autocorrelation vector for the current design step. + correlations: Box<[i32]>, + /// Preallocated reflection coefficient buffer for Durbin and area steps. + parcor: Box<[i32]>, + /// Preallocated recursion scratch buffer for Durbin and filter conversion. + scratch: Box<[i32]>, /// The slot in the correlation history that the next vector replaces. smooth_index: usize, /// The number of valid correlation vectors, from zero to two. @@ -211,17 +239,16 @@ pub(crate) struct Formant { /// the areas is necessary. stretch: i32, /// The number of active coefficients in the stretched model, not more - /// than MAX_ORDER. + /// than `max_order`. stretch_count: usize, - /// The Q7 positions that map the stretched sections into the area model - /// with 50 sections. - stretch_map: [i32; MAX_ORDER], + /// The Q7 positions that map the stretched sections into the area model. + stretch_map: Box<[i32]>, /// The original tract areas, with the runtime scale that the LPC /// conversion returns. - areas: [i32; MAX_ORDER], + areas: Box<[i32]>, /// The interpolated areas, scaled by the width. They use the same binary /// scale as the original areas. - stretched_areas: [i32; MAX_ORDER], + stretched_areas: Box<[i32]>, /// The high-pass filter for the random aspiration that the signal /// modulates. noise_filter: Biquad, @@ -243,25 +270,44 @@ impl Formant { /// the longest analysis segment and the predictor padding. Later calls /// use this memory again. pub(crate) fn new(rate: SampleRate, config: FormantConfig) -> Self { + let hist_frames = history_frames(rate); + let ana_frames = analysis_frames(rate); + let order = predictor_order(rate); + let max_order = max_synthesis_order(order); + let blend_step = ((1638 * 44_100) / rate.as_u32() as usize).max(1) as i32; let d1 = -std::f64::consts::LN_2 / 0.9_f64.ln(); let d2 = rate.hz() as f64 * d1 / 44100.0; let mut result = Self { config, rate, - input: vec![0; HISTORY_FRAMES], - temporary: vec![0_i32; (2 * (rate.as_u32() as usize / 40) + MAX_ORDER + 256).max(2865)], - inverse: vec![[0; MAX_ORDER]; BANKS], - models: vec![[0; MAX_ORDER]; BANKS], + history_frames: hist_frames, + analysis_frames: ana_frames, + order, + max_order, + blend_step, + input: vec![0; hist_frames].into_boxed_slice(), + temporary: vec![0_i32; (hist_frames + max_order + 256).max(2865)].into_boxed_slice(), + inverse: vec![0; BANKS * max_order].into_boxed_slice(), + models: vec![0; BANKS * max_order].into_boxed_slice(), orders: [0; BANKS], - stamps: vec![Stamp::default(); HISTORY_FRAMES], + stamps: vec![Stamp::default(); hist_frames].into_boxed_slice(), current: BANKS - 1, previous: 0, blend: 0, design_counter: 0, - history: [[0; MAX_ORDER]; 2], + history: [ + vec![0; max_order].into_boxed_slice(), + vec![0; max_order].into_boxed_slice(), + ], history_index: 0, - correlation_history: [[0; 111]; 2], - correlation_sum: [0; 111], + correlation_history: [ + vec![0; order + 1].into_boxed_slice(), + vec![0; order + 1].into_boxed_slice(), + ], + correlation_sum: vec![0; order + 1].into_boxed_slice(), + correlations: vec![0; order + 1].into_boxed_slice(), + parcor: vec![0; max_order].into_boxed_slice(), + scratch: vec![0; max_order + 2].into_boxed_slice(), smooth_index: 0, smooth_filled: 0, smooth_reset: true, @@ -269,10 +315,10 @@ impl Formant { width: 16384, width_squared: 16384, stretch: 16384, - stretch_count: ORDER, - stretch_map: [0; MAX_ORDER], - areas: [0; MAX_ORDER], - stretched_areas: [0; MAX_ORDER], + stretch_count: order, + stretch_map: vec![0; max_order].into_boxed_slice(), + areas: vec![0; max_order].into_boxed_slice(), + stretched_areas: vec![0; max_order].into_boxed_slice(), noise_filter: Biquad::new(), noise_gain: 0_i32, noise_amplitude: 0_i32, @@ -285,21 +331,22 @@ impl Formant { /// Quantizes the validated controls, prepares the Q7 map for the area /// interpolation and updates the coefficients of the aspiration filter. /// - /// The histories do not change. A valid stretch gives a model with 25 to - /// 99 entries. Thus, the last point of the map and the denominators of - /// the interpolation are always defined. + /// The histories do not change. A valid stretch in `0.5..=2.0` gives at + /// least five entries. Thus, the last point of the map and the + /// denominators of the interpolation are always defined. pub(crate) fn set_config(&mut self, config: FormantConfig) { + let order = self.order; self.config = config; self.width = (config.width as f64 * 16384.0) as i32; self.width_squared = (config.width as f64 * config.width as f64 * 16384.0) as i32; self.stretch = (config.stretch as f64 * 16384.0) as i32; self.stretch_count = - (((ORDER - 1) as f64 * config.stretch as f64 + 1.001) as usize).min(MAX_ORDER); + (((order - 1) as f64 * config.stretch as f64 + 1.001) as usize).min(self.max_order); for i in 0..self.stretch_count - 1 { let fraction = i as f64 / (self.stretch_count - 1) as f64; - self.stretch_map[i] = ((ORDER - 1) as f64 * fraction * 128.0) as i32; + self.stretch_map[i] = ((order - 1) as f64 * fraction * 128.0) as i32; } - self.stretch_map[self.stretch_count - 1] = ((ORDER - 1) * 128) as i32; + self.stretch_map[self.stretch_count - 1] = ((order - 1) * 128) as i32; self.noise_gain = (config.aspiration_mix as f64 * 16384.0) as i32; let frequency = (config.aspiration_cutoff_hz as i32) .min((self.rate.hz() as f64 * 0.48) as i32) @@ -312,13 +359,14 @@ impl Formant { /// the aspiration filter. /// /// The function also selects and clears the initial bank pair, and starts - /// the correlation smoothing again. The other banks stay allocated. The + /// the correlation average again. The other banks stay allocated. The /// stage clears each bank when it uses that bank again. pub(crate) fn reset(&mut self) { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER]; 2]; + self.history[0].fill(0); + self.history[1].fill(0); self.history_index = 0; self.current = BANKS - 1; self.next_filter(); @@ -377,31 +425,35 @@ impl Formant { /// The function clears the inverse coefficients, the forward coefficients /// and the active order of the new bank. fn next_filter(&mut self) { + let max_order = self.max_order; self.previous = self.current; self.current += 1; if self.current == BANKS { self.current = 0; } self.blend = 0; - self.inverse[self.current].fill(0_i32); + let start = self.current * max_order; + let end = start + max_order; + self.inverse[start..end].fill(0_i32); - self.models[self.current].fill(0_i32); + self.models[start..end].fill(0_i32); self.orders[self.current] = 0; } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. /// - /// The slice must fit in the histories of 111 entries. The function - /// divides each input by two before it adds the input to the sum. The - /// compensation for the first window keeps that order of division. - fn smooth(&mut self, values: &mut [i32]) { + /// `self.correlations` has `order + 1` entries. The function divides each + /// entry by two before it adds the entry to the sum. The compensation for + /// the first window keeps that order of division. + fn smooth(&mut self) { + let len = self.correlations.len(); if self.smooth_reset { self.smooth_index = 0; self.smooth_filled = 0; self.smooth_reset = false; - self.correlation_sum[..values.len()].fill(0_i32); + self.correlation_sum[..len].fill(0_i32); } - for (i, value) in values.iter_mut().enumerate() { + for (i, value) in self.correlations.iter_mut().enumerate() { if self.smooth_filled == 2 { self.correlation_sum[i] = self.correlation_sum[i] .wrapping_sub(self.correlation_history[self.smooth_index][i]); @@ -411,7 +463,7 @@ impl Formant { self.correlation_sum[i] = self.correlation_sum[i].wrapping_add(*value); } self.smooth_filled = (self.smooth_filled + 1).min(2); - for (i, value) in values.iter_mut().enumerate() { + for (i, value) in self.correlations.iter_mut().enumerate() { *value = if self.smooth_filled < 2 { self.correlation_sum[i] .wrapping_div(self.smooth_filled as i32) @@ -422,10 +474,10 @@ impl Formant { } self.smooth_index = (self.smooth_index + 1) % 2; } - /// Tries a model that uses the pitch each ANALYSIS_FRAMES, and stamps + /// Tries a model that uses the pitch each `analysis_frames`, and stamps /// each frame. /// - /// If a pitch is available, the segment folds adjacent cycles. If not, + /// If a pitch is available, the segment averages adjacent cycles. If not, /// the segment is a window of approximately 10 ms. Before the Durbin /// analysis, the function does these steps on the correlations: /// 1. It rescales them during the sum. @@ -438,23 +490,25 @@ impl Formant { /// - If not, the area conversion makes the model. If the conversion /// fails, the new synthesis order stays at zero. /// - /// If the Durbin analysis fails, smoothing starts again. The selected - /// bank keeps the inverse coefficients that the analysis wrote. + /// If the Durbin analysis fails, the correlation average starts again. The + /// selected bank keeps the inverse coefficients that the analysis wrote. fn design(&mut self, periods: &[Q6], position: usize, output_period_q6: i32) { + let hist_frames = self.history_frames; + let order = self.order; + let max_order = self.max_order; let period = output_period_q6.wrapping_shr(6).max(0) as usize; let design_now = self.design_counter == 0; self.design_counter += 1; let one = 16384; if design_now { - self.design_counter -= ANALYSIS_FRAMES as i32; + self.design_counter -= self.analysis_frames as i32; let count; if period == 0 { count = (self.rate.as_u32() as usize + 50) / 100; for i in 0..count { - self.temporary[i] = - self.input[(position + HISTORY_FRAMES - i) % HISTORY_FRAMES]; + self.temporary[i] = self.input[(position + hist_frames - i) % hist_frames]; } - self.temporary[count..count + ORDER].fill(0_i32); + self.temporary[count..count + order].fill(0_i32); } else { count = if periods[position] == Q6::ZERO { period * 2 @@ -464,12 +518,11 @@ impl Formant { let extra = (period / 10).max(1); if periods[position] == Q6::ZERO { for i in 0..count + extra { - self.temporary[i] = - self.input[(position + HISTORY_FRAMES - i) % HISTORY_FRAMES]; + self.temporary[i] = self.input[(position + hist_frames - i) % hist_frames]; } } else { for i in 0..count + extra { - let index = (position + HISTORY_FRAMES - i) % HISTORY_FRAMES; + let index = (position + hist_frames - i) % hist_frames; let mut accumulator = (index as i32) << 6; let mut sum = 0_i32; let mut reads = 0; @@ -477,7 +530,7 @@ impl Formant { let index = accumulator .wrapping_add(32) .wrapping_shr(6) - .rem_euclid(HISTORY_FRAMES as i32) + .rem_euclid(hist_frames as i32) as usize; sum = sum.wrapping_add(self.input[index]); reads += 1; @@ -496,12 +549,12 @@ impl Formant { .wrapping_add(mul14(blend, self.temporary[i + count])); blend -= step; } - for i in count..count + ORDER { + for i in count..count + order { self.temporary[i] = self.temporary[i - count]; } } let mut previous = self.temporary[count - 1]; - for sample in &mut self.temporary[..count + ORDER] { + for sample in &mut self.temporary[..count + order] { let current = *sample; *sample = current .saturating_sub(round_q14(i64::from(previous) * i64::from(self.glottal))); @@ -512,17 +565,18 @@ impl Formant { // Do not add the products first, and do not reduce the lanes in a // different order. These changes move the points where the shifts // occur, and thus change the model. - let mut correlations = [0_i32; 111]; + self.correlations.fill(0_i32); let mut shift = 0; - for lag in 0..=ORDER { + for lag in 0..=order { let mut correlation = 0_i32; let (left_chunks, left_tail) = self.temporary[..count].as_chunks::<4>(); let (right_chunks, right_tail) = self.temporary[lag..lag + count].as_chunks::<4>(); + let prior_correlations = &mut self.correlations[..lag]; let mut accumulate = |product: i32| { correlation = correlation.wrapping_add(product.wrapping_shr(shift)); if correlation.wrapping_abs() > 0x4000000 { shift += 1; - for prior in &mut correlations[..lag] { + for prior in &mut *prior_correlations { *prior = prior.wrapping_shr(1); } correlation = correlation.wrapping_shr(1); @@ -542,48 +596,51 @@ impl Formant { for (&left, &right) in left_tail.iter().zip(right_tail) { accumulate(left.wrapping_mul(right)); } - correlations[lag] = correlation; + self.correlations[lag] = correlation; } let mut normalization = 0; - while correlations[0] > one { - correlations[0] = correlations[0].wrapping_shr(1); + while self.correlations[0] > one { + self.correlations[0] = self.correlations[0].wrapping_shr(1); normalization += 1; } - for value in &mut correlations[1..=ORDER] { + for value in &mut self.correlations[1..=order] { *value = value.wrapping_shr(normalization); } let scale = (8192 / if period != 0 { period } else { count }) - .min((2.0 / ORDER as f64 * 16384.0) as usize) as i32; + .min((2.0 / order as f64 * 16384.0) as usize) as i32; let mut accumulator = 0; - for value in &mut correlations[1..=ORDER] { + for value in &mut self.correlations[1..=order] { accumulator += scale; let sinc = fast_sinc(accumulator); *value = mul14(*value, mul14(sinc, sinc)); } - self.smooth(&mut correlations[..=ORDER]); + self.smooth(); // Select a cleared bank before the solve. If the solve fails, some // inverse coefficients can stay in the bank. But the synthesis // order stays zero until all necessary model changes complete. self.next_filter(); self.generation = self.generation.wrapping_add(1); let design_gain = ((db_to_gain(-60.0) + 1.0) * 16384.0) as i32; - correlations[0] = mul14(correlations[0], design_gain).wrapping_add(200); - let mut parcor = [0; MAX_ORDER]; - let mut scratch = [0; 112]; + self.correlations[0] = mul14(self.correlations[0], design_gain).wrapping_add(200); + self.parcor.fill(0); + self.scratch.fill(0); + let bank_start = self.current * max_order; let valid = lpc::durbin( - &correlations, - &mut self.inverse[self.current][..ORDER], - &mut parcor, - &mut scratch, + &self.correlations, + &mut self.inverse[bank_start..bank_start + order], + &mut self.parcor, + &mut self.scratch, ); if valid { if self.width != one || self.stretch != one { - if let Some(scale) = lpc::parcor_to_areas(&parcor[..ORDER], &mut self.areas) { + if let Some(scale) = + lpc::parcor_to_areas(&self.parcor[..order], &mut self.areas) + { for i in 0..self.stretch_count { let map = self.stretch_map[i]; - let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; + let index = map.wrapping_shr(7).min((order - 2) as i32) as usize; let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); self.stretched_areas[i] = mul14( mul14(one.wrapping_sub(fraction), self.areas[index]) @@ -596,29 +653,29 @@ impl Formant { } if lpc::areas_to_parcor( &self.stretched_areas[..self.stretch_count], - &mut parcor, + &mut self.parcor, scale, ) { lpc::parcor_to_pef( - &parcor[..self.stretch_count], - &mut self.models[self.current], - &mut scratch, + &self.parcor[..self.stretch_count], + &mut self.models[bank_start..bank_start + max_order], + &mut self.scratch, 14, ); self.orders[self.current] = self.stretch_count; } } } else { - self.models[self.current][..ORDER] - .copy_from_slice(&self.inverse[self.current][..ORDER]); - self.orders[self.current] = ORDER; + self.models[bank_start..bank_start + order] + .copy_from_slice(&self.inverse[bank_start..bank_start + order]); + self.orders[self.current] = order; } } else { self.smooth_reset = true; } } if self.blend < 16384 { - self.blend = (self.blend + 1638).min(16384); + self.blend = (self.blend + self.blend_step).min(16384); } self.stamps[position] = Stamp { current: self.current, @@ -627,30 +684,34 @@ impl Formant { }; } - /// Applies the blended 50th-order prediction-error filter to the delayed - /// input. + /// Applies the blended prediction-error filter to the delayed input. /// /// The full sum of Q28 products accumulates in `i64` before one signed /// shift and an `i32` clamp. The function blends the coefficients for the /// current transition. Then it multiplies them with the previous samples. fn inverse(&self, position: usize) -> i32 { - let read = if position < ANALYSIS_FRAMES { - position + HISTORY_FRAMES - ANALYSIS_FRAMES + let hist_frames = self.history_frames; + let ana_frames = self.analysis_frames; + let max_order = self.max_order; + let read = if position < ana_frames { + position + hist_frames - ana_frames } else { - position - ANALYSIS_FRAMES + position - ana_frames }; + let previous_base = self.previous * max_order; + let current_base = self.current * max_order; let mut cursor = read; let mut sum = 0_i64; - for i in 0..ORDER { + for i in 0..self.order { let coefficient = if self.blend < 16384 { - mul14(16384 - self.blend, self.inverse[self.previous][i]) - .saturating_add(mul14(self.blend, self.inverse[self.current][i])) + mul14(16384 - self.blend, self.inverse[previous_base + i]) + .saturating_add(mul14(self.blend, self.inverse[current_base + i])) } else { - self.inverse[self.current][i] + self.inverse[current_base + i] }; cursor = if cursor == 0 { - HISTORY_FRAMES - 1 + hist_frames - 1 } else { cursor - 1 }; @@ -684,17 +745,20 @@ impl Formant { /// Returns the length of the active prefix that the function writes to /// `output`. The entries after the prefix are not specified, and you must /// not use them. Negative positions wrap in the ring. - fn coefficients(&self, position: i32, output: &mut [i32; MAX_ORDER]) -> usize { - let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; + fn coefficients(&self, position: i32, output: &mut [i32; MAX_SYNTHESIS_ORDER]) -> usize { + let stamp = self.stamps[position.rem_euclid(self.history_frames as i32) as usize]; + let max_order = self.max_order; + let previous_base = stamp.previous * max_order; + let current_base = stamp.current * max_order; let mut order = self.orders[stamp.current]; if stamp.blend < 16384 && self.orders[stamp.previous] != 0 { order = order.max(self.orders[stamp.previous]); for (i, value) in output[..order].iter_mut().enumerate() { - *value = mul14(16384 - stamp.blend, self.models[stamp.previous][i]) - .saturating_add(mul14(stamp.blend, self.models[stamp.current][i])); + *value = mul14(16384 - stamp.blend, self.models[previous_base + i]) + .saturating_add(mul14(stamp.blend, self.models[current_base + i])); } } else { - output[..order].copy_from_slice(&self.models[stamp.current][..order]); + output[..order].copy_from_slice(&self.models[current_base..current_base + order]); } order } @@ -705,16 +769,20 @@ impl Formant { /// Finds and blends the analysis coefficients of the stamp at a signed /// history frame, in the same way as [`Self::coefficients`]. /// - /// The function writes ORDER entries to the start of `output`. - fn analysis_coefficients(&self, position: i32, output: &mut [i32; MAX_ORDER]) { - let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; + /// The function writes `self.order` entries to the start of `output`. + fn analysis_coefficients(&self, position: i32, output: &mut [i32; MAX_SYNTHESIS_ORDER]) { + let stamp = self.stamps[position.rem_euclid(self.history_frames as i32) as usize]; + let max_order = self.max_order; + let previous_base = stamp.previous * max_order; + let current_base = stamp.current * max_order; + let order = self.order; if stamp.blend < 16384 { - for (i, value) in output[..ORDER].iter_mut().enumerate() { - *value = mul14(16384 - stamp.blend, self.inverse[stamp.previous][i]) - .saturating_add(mul14(stamp.blend, self.inverse[stamp.current][i])); + for (i, value) in output[..order].iter_mut().enumerate() { + *value = mul14(16384 - stamp.blend, self.inverse[previous_base + i]) + .saturating_add(mul14(stamp.blend, self.inverse[current_base + i])); } } else { - output[..ORDER].copy_from_slice(&self.inverse[stamp.current][..ORDER]); + output[..order].copy_from_slice(&self.inverse[current_base..current_base + order]); } } /// Writes the magnitude response of the two models of the stamp at a @@ -737,15 +805,16 @@ impl Formant { input: &mut [f32], output: &mut [f32], ) -> bool { - let mut synthesis = [0; MAX_ORDER]; + let mut synthesis = [0; MAX_SYNTHESIS_ORDER]; let order = self.coefficients(position, &mut synthesis); if order == 0 { input.fill(0.0); output.fill(0.0); return false; } - let mut analysis = [0; MAX_ORDER]; + let mut analysis = [0; MAX_SYNTHESIS_ORDER]; self.analysis_coefficients(position, &mut analysis); + let analysis_order = self.order; let points = input.len(); let step = if points > 1 { std::f64::consts::PI * 2.0 * max_frequency_hz as f64 @@ -774,7 +843,8 @@ impl Formant { let emphasis = ((1.0 - glottal * cosine).powi(2) + (glottal * sine).powi(2)) .sqrt() .max(1e-6); - *input = (1.0 / (magnitude(&analysis[..ORDER], cosine, sine) * emphasis)) as f32; + *input = + (1.0 / (magnitude(&analysis[..analysis_order], cosine, sine) * emphasis)) as f32; *output = (width / (magnitude(&synthesis[..order], cosine, sine) * emphasis)) as f32; } true @@ -791,13 +861,14 @@ impl Formant { context: &mut NumericContext, ) -> i32 { let sample = self.add_noise(sample, context); - let mut coefficients = [0; MAX_ORDER]; + let mut coefficients = [0; MAX_SYNTHESIS_ORDER]; let order = self.coefficients(position, &mut coefficients); + let max_order = self.max_order; let mut sum = 0_i64; let mut cursor = self.history_index; for &coefficient in &coefficients[..order] { cursor = if cursor == 0 { - MAX_ORDER - 1 + max_order - 1 } else { cursor - 1 }; @@ -806,7 +877,7 @@ impl Formant { let sample = sample.saturating_add(round_q14(sum)); self.history[0][self.history_index] = sample; self.history_index += 1; - if self.history_index == MAX_ORDER { + if self.history_index == max_order { self.history_index = 0; } round_q14(i64::from(sample) * i64::from(self.width)) @@ -830,14 +901,15 @@ impl Formant { for sample in &mut samples { *sample = sample.saturating_add(noise); } - let mut coefficients = [0; MAX_ORDER]; + let mut coefficients = [0; MAX_SYNTHESIS_ORDER]; let order = self.coefficients(position, &mut coefficients); + let max_order = self.max_order; for (channel, sample) in samples.iter_mut().enumerate() { let mut sum = 0_i64; for (i, &coefficient) in coefficients[..order].iter().enumerate() { sum = sum.saturating_add( i64::from( - self.history[channel][(self.history_index + MAX_ORDER - i - 1) % MAX_ORDER], + self.history[channel][(self.history_index + max_order - i - 1) % max_order], ) * i64::from(coefficient), ); } @@ -845,7 +917,7 @@ impl Formant { self.history[channel][self.history_index] = *sample; *sample = round_q14(i64::from(*sample) * i64::from(self.width)); } - self.history_index = (self.history_index + 1) % MAX_ORDER; + self.history_index = (self.history_index + 1) % max_order; samples } } diff --git a/src/lib.rs b/src/lib.rs index f17bc85..74b868a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,11 @@ //! A crate for vocal pitch correction, choir, harmony, formant control and effects. //! //! [`Processor`] changes mono signed 16-bit PCM into the same number of stereo -//! or mono frames. The sample rate is 44.1 kHz or 48 kHz. The signal chain is -//! Punch → Warm → pitch tracking and resynthesis → Alien → reverb → output -//! gain. The default configuration enables chromatic pitch correction and one -//! choir voice. The optional effects and the formant stage are disabled. +//! or mono frames. Ten sample rates from 8 kHz to 192 kHz are available. The +//! signal chain is Punch → Warm → pitch tracking and resynthesis → Alien → +//! reverb → output gain. The default configuration enables chromatic pitch +//! correction and one choir voice. The optional effects and the formant stage +//! are disabled. //! //! # Preparing and configuring //! diff --git a/src/lpc.rs b/src/lpc.rs index d8f706f..becd59b 100644 --- a/src/lpc.rs +++ b/src/lpc.rs @@ -38,34 +38,66 @@ pub(crate) fn durbin( if correlation[0] <= 0_i32 { return false; } - let mut alpha = correlation[0]; let one = 16384; + if order <= 50 { + let mut alpha = correlation[0]; + for i in 0..order { + let mut sum = 0_i32; + for j in 0..i { + sum = sum.wrapping_add(coefficients[j].wrapping_mul(correlation[i - j])); + } + sum = sum.wrapping_shr(14); + if alpha == 0_i32 { + return false; + } + let k = correlation[i + 1] + .wrapping_sub(sum) + .wrapping_shl(14) + .wrapping_div(alpha); + parcor[i] = k; + if k.wrapping_abs() >= one { + return false; + } + scratch[i] = k; + for j in 0..i { + scratch[j] = coefficients[j] + .wrapping_shl(14) + .wrapping_sub(k.wrapping_mul(coefficients[i - j - 1])) + .wrapping_shr(14); + } + coefficients[..=i].copy_from_slice(&scratch[..=i]); + alpha = mul14(alpha, one.wrapping_sub(mul14(k, k))); + } + return true; + } + // High-order models above 44.1 kHz keep Q24 internal words in 32-bit + // arithmetic so step truncation does not bias reflection magnitudes. + let mut alpha = correlation[0].wrapping_shl(10); for i in 0..order { let mut sum = 0_i32; for j in 0..i { - sum = sum.wrapping_add(coefficients[j].wrapping_mul(correlation[i - j])); + sum = sum.wrapping_add((coefficients[j] >> 10).wrapping_mul(correlation[i - j]) >> 4); } - sum = sum.wrapping_shr(14); - if alpha == 0_i32 { + let divisor = alpha >> 8; + if divisor <= 0_i32 { return false; } - let k = correlation[i + 1] - .wrapping_sub(sum) - .wrapping_shl(14) - .wrapping_div(alpha); + let numerator = correlation[i + 1].wrapping_shl(10).wrapping_sub(sum) >> 8; + let k = numerator.wrapping_shl(14).wrapping_div(divisor); parcor[i] = k; if k.wrapping_abs() >= one { return false; } - scratch[i] = k; + scratch[i] = k.wrapping_shl(10); for j in 0..i { - scratch[j] = coefficients[j] - .wrapping_shl(14) - .wrapping_sub(k.wrapping_mul(coefficients[i - j - 1])) - .wrapping_shr(14); + scratch[j] = + coefficients[j].wrapping_sub(k.wrapping_mul(coefficients[i - j - 1] >> 10) >> 4); } coefficients[..=i].copy_from_slice(&scratch[..=i]); - alpha = mul14(alpha, one.wrapping_sub(mul14(k, k))); + alpha = divisor.wrapping_mul(one.wrapping_sub(mul14(k, k))) >> 6; + } + for coefficient in &mut coefficients[..order] { + *coefficient = coefficient.wrapping_shr(10); } true } diff --git a/src/numeric.rs b/src/numeric.rs index e67db8f..4079784 100644 --- a/src/numeric.rs +++ b/src/numeric.rs @@ -8,6 +8,7 @@ pub(crate) mod fixed; pub(crate) mod rng; mod tables; +use crate::SampleRate; use rng::RandomStream; use tables::{SINC, TAN}; @@ -181,9 +182,30 @@ impl NumericContext { } } } -/// The capacity in frames of the history for pitch and resynthesis. The -/// value is the same at the two supported rates. -pub(crate) const HISTORY: usize = 11_568; +/// Returns the decimation stride of pitch acquisition for `rate`. +/// +/// The stride keeps the decimated rate between 4 kHz and 6 kHz. At 44.1 kHz +/// and 48 kHz, the stride is 8. +pub(crate) const fn pitch_stride(rate: SampleRate) -> usize { + match rate { + SampleRate::Hz8000 => 2, + SampleRate::Hz16000 | SampleRate::Hz22050 | SampleRate::Hz24000 => 4, + SampleRate::Hz32000 | SampleRate::Hz44100 | SampleRate::Hz48000 => 8, + SampleRate::Hz88200 | SampleRate::Hz96000 => 16, + SampleRate::Hz192000 => 32, + } +} + +/// Returns the capacity in frames of the history for pitch, formant and +/// resynthesis at `rate`. +/// +/// The capacity is 11,568 frames at 44.1 kHz and scales with `rate` as a +/// multiple of the pitch acquisition stride. +pub(crate) const fn history_frames(rate: SampleRate) -> usize { + let stride = pitch_stride(rate); + let raw = (11_568 * rate.as_u32() as usize + 22_050) / 44_100; + (raw + stride - 1) & !(stride - 1) +} /// The value 1.0 as a plain Q14 word, for algorithms that set the binary /// scale at runtime. pub(crate) const ONE: i32 = 16_384; @@ -197,10 +219,10 @@ pub(crate) fn mul14(left: i32, right: i32) -> i32 { mul_shift(left, right, 14) } -/// Wraps a signed frame index into 0..HISTORY with the Euclidean remainder. +/// Wraps a signed frame index into `0..len` with the Euclidean remainder. /// /// Negative reader positions also wrap correctly. #[inline] -pub(crate) fn ring(index: i32) -> usize { - index.rem_euclid(HISTORY as i32) as usize +pub(crate) fn ring(index: i32, len: usize) -> usize { + index.rem_euclid(len as i32) as usize } diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..04bf2cd 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 rate-scaled window of candidate lags. The reporting bounds filter only +//! the feedback to the host. mod search; pub(crate) mod tracker; diff --git a/src/pitch/search.rs b/src/pitch/search.rs index cd9d212..01b7164 100644 --- a/src/pitch/search.rs +++ b/src/pitch/search.rs @@ -1,20 +1,20 @@ //! The search for the lag with the minimum value, with four independent //! comparison chains. -/// The number of candidate lags around the tracked period. -pub(super) const TRACKING_LAGS: usize = 40; /// The number of independent comparison chains. They decrease the dependency /// depth of the lag search. const LANES: usize = 4; -/// Returns the index of the first minimum of exactly 40 candidates. +/// Returns the index of the first minimum of `count` candidates. /// -/// The candidates are examined in index order. Four independent minima -/// decrease the dependencies between comparisons. Then a final reduction -/// selects the lowest index if two values are equal. `value_at` must return -/// the same value for an index, independent of the order of comparisons. +/// `count` must be a positive multiple of four. The candidates are examined in +/// index order. Four independent minima decrease the dependencies between +/// comparisons. Then a final reduction selects the lowest index if two values +/// are equal. `value_at` must return the same value for an index, independent +/// of the order of comparisons. #[inline] -pub(super) fn tracking_minimum(value_at: impl Fn(usize) -> i32) -> usize { +pub(super) fn tracking_minimum(count: usize, value_at: impl Fn(usize) -> i32) -> usize { + debug_assert!(count >= LANES && count.is_multiple_of(LANES)); let first = value_at(0); let mut minima = [first; LANES]; let mut indices = [0; LANES]; @@ -25,7 +25,7 @@ pub(super) fn tracking_minimum(value_at: impl Fn(usize) -> i32) -> usize { indices[lane] = lane; } } - for group in 1..TRACKING_LAGS / LANES { + for group in 1..count / LANES { for lane in 0..LANES { let index = group * LANES + lane; let value = value_at(index); diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index 1fc3a46..b0b2f91 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -1,22 +1,22 @@ //! A two-stage pitch estimator with circular sample histories. //! -//! Acquisition applies a low-pass filter to the signal and examines one -//! sample in eight. The minima of the normalized cycle difference must repeat -//! with a constant spacing. Then acquisition starts a full-rate tracking -//! window. Tracking updates the energy and cross terms at each frame. It -//! refines the minimum every five frames. A parabola gives the Q6 sub-sample -//! resolution of the period. +//! Acquisition applies a low-pass filter to the signal and decimates it by a +//! stride that scales with the sample rate. The minima of the normalized cycle +//! difference must repeat with a constant spacing. Then acquisition starts a +//! full-rate tracking window. Tracking updates the energy and cross terms at +//! each frame. It refines the minimum every five frames. A parabola gives the +//! Q6 sub-sample resolution of the period. //! -//! The 40-lag window moves to keep the minimum near its center. If the +//! The tracking 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. -use super::search::{tracking_minimum, TRACKING_LAGS}; +use super::search::tracking_minimum; use crate::filter::{Biquad, Design}; use crate::numeric::fixed::{Q14, Q6}; -use crate::numeric::{mul14, ring, HISTORY, ONE}; +use crate::numeric::{history_frames, mul14, pitch_stride, ring, ONE}; use crate::{PitchConfig, SampleRate}; /// The result of one full-rate input sample. @@ -43,22 +43,63 @@ pub(crate) struct PitchStep { pub restarted: bool, } -/// The number of lags that acquisition compares. -const ACQUISITION_LAGS: usize = 137; +/// Returns the number of decimated lags that acquisition compares for `rate`. +const fn acquisition_lags(rate: SampleRate) -> usize { + match rate { + SampleRate::Hz8000 | SampleRate::Hz16000 | SampleRate::Hz32000 => 105, + SampleRate::Hz44100 => 137, + SampleRate::Hz22050 | SampleRate::Hz88200 => 148, + SampleRate::Hz24000 | SampleRate::Hz48000 | SampleRate::Hz96000 | SampleRate::Hz192000 => { + 160 + } + } +} + +/// Returns the number of full-rate candidate lags in the local tracking window. +/// +/// The count is 40 at 44.1 kHz and stays a multiple of four with at least 8 +/// lags. +const fn tracking_lags(rate: SampleRate) -> usize { + let scaled = (40 * rate.as_u32() as usize + 22_050) / 44_100; + let aligned = (scaled + 2) & !3; + if aligned < 8 { + 8 + } else { + aligned + } +} + +/// Returns the inclusive upper bound of rejected short full-rate lags. +/// +/// The value is 19 at 44.1 kHz, so accepted periods correspond to frequencies +/// at or below approximately 2.2 kHz. +const fn minimum_lag(rate: SampleRate) -> i32 { + ((19 * rate.as_u32() as usize) / 44_100) as i32 +} /// 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 { - /// Two low-pass sections before the 8:1 decimation for acquisition. + /// Two low-pass sections before decimation for acquisition. /// /// Full-rate tracking uses the raw audio. pre: [Biquad; 2], - /// Full-rate Q14 sample words in a fixed ring on the heap. - raw: Box<[i32; HISTORY]>, + /// Full-rate Q14 sample words in a preallocated ring on the heap. + raw: Box<[i32]>, + /// The bitmask `stride - 1` for the power-of-two acquisition cadence. + stride_mask: usize, + /// The right shift that converts a Q11 decimated period to full-rate lags. + q11_shift: u32, + /// The half-unit Q11 offset added before `q11_shift`. + q11_round: i32, + /// Half of `tracking_lags`, subtracted to center the tracking window. + tracking_half: i32, + /// Full-rate lags at or below this threshold restart acquisition. + min_lag: i32, /// The current full-rate history frame. It also sets the acquisition - /// cadence of one frame in eight. + /// cadence. write: usize, /// `true` if acquisition is active instead of full-rate local tracking. detecting: bool, @@ -67,22 +108,23 @@ pub(crate) struct PitchTracker { first: bool, /// Low-pass filtered and decimated Q14 audio, with space for two maximum /// acquisition lags. - detection: [i32; 2 * ACQUISITION_LAGS], - /// The next slot in the decimated ring, less than twice - /// `ACQUISITION_LAGS`. + detection: Box<[i32]>, + /// The next slot in the decimated ring, less than `detection.len()`. detection_index: usize, /// The wrapping count of decimated samples since acquisition started. detection_count: i32, /// The window energies for each lag. They normalize the acquisition cycle /// difference. - energy: [i32; ACQUISITION_LAGS], + energy: Box<[i32]>, /// The cross products for each lag, with the same binary scale as their /// energies. - cross: [i32; ACQUISITION_LAGS], - /// Full-rate energies for the 40 adjacent candidate lags. - tracking_energy: [i32; TRACKING_LAGS], + cross: Box<[i32]>, + /// Preallocated normalized difference table for acquisition searches. + normalized: Box<[i32]>, + /// Full-rate energies for the adjacent candidate lags. + tracking_energy: Box<[i32]>, /// Full-rate cross products for the tracking energies. - tracking_cross: [i32; TRACKING_LAGS], + tracking_cross: Box<[i32]>, /// The full-rate integer lag of tracking slot zero. base: i32, /// The number of frames since the last local minimum search. A search @@ -104,29 +146,38 @@ 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 low-pass cutoffs sit at `rate / (4 * stride)` and at 1.5 times that + /// cutoff. The validated sensitivity is quantized to Q14. pub(crate) fn new(rate: SampleRate, config: PitchConfig) -> Self { + let stride = pitch_stride(rate); + let history = history_frames(rate); + let acq_lags = acquisition_lags(rate); + let trk_lags = tracking_lags(rate); + let q11_shift = 11 - stride.trailing_zeros(); let mut pre = [Biquad::new(), Biquad::new()]; - let cutoff = rate.hz() / 16.0 / 2.0; + let cutoff = rate.hz() / (2.0 * stride as f32) / 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, - raw: vec![0; HISTORY] - .into_boxed_slice() - .try_into() - .expect("prepared pitch history length"), + raw: vec![0; history].into_boxed_slice(), + stride_mask: stride - 1, + q11_shift, + q11_round: 1_i32 << (q11_shift - 1), + tracking_half: (trk_lags / 2) as i32, + min_lag: minimum_lag(rate), write: 0, detecting: true, first: true, - detection: [0; 2 * ACQUISITION_LAGS], + detection: vec![0; 2 * acq_lags].into_boxed_slice(), detection_index: 0, detection_count: 0, - energy: [0; ACQUISITION_LAGS], - cross: [0; ACQUISITION_LAGS], - tracking_energy: [0; TRACKING_LAGS], - tracking_cross: [0; TRACKING_LAGS], + energy: vec![0; acq_lags].into_boxed_slice(), + cross: vec![0; acq_lags].into_boxed_slice(), + normalized: vec![0; acq_lags].into_boxed_slice(), + tracking_energy: vec![0; trk_lags].into_boxed_slice(), + tracking_cross: vec![0; trk_lags].into_boxed_slice(), base: 0, tracking_counter: 0, period: Q6::default(), @@ -274,10 +325,12 @@ impl PitchTracker { /// only if its interpolated value is less than the threshold. /// /// The first 10 decimated samples after a restart give no candidate. - /// The function subtracts 20 from the selected full-rate period. This puts - /// the period at the center of the 40-lag tracking window before the - /// window starts. + /// The function subtracts half of the tracking window from the selected + /// full-rate period. This puts the period at the center of the tracking + /// window before the window starts. fn detection_lag(&mut self, sample: i32) -> i32 { + let acq_lags = self.energy.len(); + let detection_len = self.detection.len(); if self.first { self.first = false; self.detection.fill(0); @@ -290,16 +343,16 @@ impl PitchTracker { let mut index1 = self.detection_index; let mut index2 = index1; self.detection_index += 1; - if self.detection_index == 2 * ACQUISITION_LAGS { + if self.detection_index == detection_len { self.detection_index = 0; } self.detection[index1] = sample; let square = mul14(sample, sample); let mut lag = 0; - while lag < ACQUISITION_LAGS { + while lag < acq_lags { // Neither input window wraps in this run. For all lanes, the two // input cursors cross a maximum of two different boundaries. - let count = (ACQUISITION_LAGS - lag).min(index1 + 1).min(index2 / 2 + 1); + let count = (acq_lags - lag).min(index1 + 1).min(index2 / 2 + 1); let end = lag + count; let current_low = index1 + 1 - count; let delayed_low = index2 - (count - 1) * 2; @@ -312,12 +365,12 @@ impl PitchTracker { &mut self.cross[lag..end], ); index1 = if count == index1 + 1 { - 273 + detection_len - 1 } else { index1 - count }; index2 = if count == index2 / 2 + 1 { - index2 + 2 * ACQUISITION_LAGS - count * 2 + index2 + detection_len - count * 2 } else { index2 - count * 2 }; @@ -327,8 +380,8 @@ impl PitchTracker { if self.detection_count <= 10 { return 0; } - let maximum = ((self.detection_count - 6) / 2).min(ACQUISITION_LAGS as i32 - 1) as usize; - let mut normalized = [0_i32; ACQUISITION_LAGS]; + let maximum = ((self.detection_count - 6) / 2).min(acq_lags as i32 - 1) as usize; + self.normalized[..maximum].fill(0); #[allow( clippy::needless_range_loop, reason = "one lag index drives three tables in the hot loop" @@ -342,12 +395,13 @@ impl PitchTracker { energy >>= sh; cross >>= sh; } - normalized[lag] = if energy > 0 { + self.normalized[lag] = if energy > 0 { (energy / 2).wrapping_sub(cross).wrapping_shl(14) / energy } else { ONE }; } + let normalized = &self.normalized[..]; let mut lag = 2; while lag < maximum.saturating_sub(2) { if normalized[lag] > 9830 { @@ -415,16 +469,19 @@ impl PitchTracker { if best == 0 { 0 } else { - ((128_i32.wrapping_add(best)) >> 8).wrapping_sub(20) + ((self.q11_round.wrapping_add(best)) >> self.q11_shift).wrapping_sub(self.tracking_half) } } - /// Builds the energies and cross terms for 40 full-rate lags from a - /// positive base. + /// Builds the energies and cross terms for the full-rate tracking lags + /// from a positive base. + /// /// Candidate acquisition makes sure that the necessary history fits in /// the ring. The counter starts at four, so the next tracking sample /// searches immediately. fn initialize_tracking(&mut self, period: i32) { + let history = self.raw.len(); + let trk_lags = self.tracking_energy.len(); self.base = period; let mut energy: i32 = 0; let mut index = self.write; @@ -439,7 +496,7 @@ impl PitchTracker { energy = energy .wrapping_add(Self::energy_slice(&self.raw[index + 1 - step..=index])); index = if index + 1 == step { - HISTORY - 1 + history - 1 } else { index - step }; @@ -448,16 +505,16 @@ impl PitchTracker { } } self.tracking_energy[0] = energy; - index = ring(self.write as i32 - period * 2); - for lag in 1..TRACKING_LAGS { + index = ring(self.write as i32 - period * 2, history); + for lag in 1..trk_lags { let first = self.raw[index]; - index = if index == 0 { HISTORY - 1 } else { index - 1 }; + index = if index == 0 { history - 1 } else { index - 1 }; let second = self.raw[index]; - index = if index == 0 { HISTORY - 1 } else { index - 1 }; + index = if index == 0 { history - 1 } else { index - 1 }; energy = energy.wrapping_add(mul14(first, first).wrapping_add(mul14(second, second))); self.tracking_energy[lag] = energy; } - for lag in 0..TRACKING_LAGS { + for lag in 0..trk_lags { self.tracking_cross[lag] = self.cross_at(period + lag as i32); } self.tracking_counter = 4; @@ -484,15 +541,17 @@ impl PitchTracker { /// Calculates the wrapping Q14 cross sum of two adjacent periods of raw /// audio. + /// /// The positive integer period and its two-period window must fit in the /// history. fn cross_at(&self, period: i32) -> i32 { if period <= 0 { return 0; } + let history = self.raw.len(); let p = period as usize; let mut first = self.write; - let mut second = ring(self.write as i32 - period); + let mut second = ring(self.write as i32 - period, history); if first + 1 >= p && second + 1 >= p { return Self::cross_slice( &self.raw[first + 1 - p..=first], @@ -508,12 +567,12 @@ impl PitchTracker { &self.raw[second + 1 - step..=second], )); first = if first + 1 == step { - HISTORY - 1 + history - 1 } else { first - step }; second = if second + 1 == step { - HISTORY - 1 + history - 1 } else { second - step }; @@ -524,21 +583,26 @@ impl PitchTracker { /// Increments the full-rate energy and cross windows when all reads are /// contiguous. - /// The fixed array lengths encode 40 lag samples and 79 samples with a - /// stride of two. The separate wrapping path in `process_sample` uses the - /// same arithmetic. + /// + /// `middle` has one sample per tracking lag, and `delayed` has + /// `2 * lags - 1` samples for the stride of two. The separate wrap path in + /// `process_sample` uses the same arithmetic. #[inline] fn track_contiguous( current: i32, - middle: &[i32; TRACKING_LAGS], - delayed: &[i32; 2 * TRACKING_LAGS - 1], - energy: &mut [i32; TRACKING_LAGS], - cross: &mut [i32; TRACKING_LAGS], + middle: &[i32], + delayed: &[i32], + energy: &mut [i32], + cross: &mut [i32], ) { + let lags = energy.len(); + debug_assert_eq!(cross.len(), lags); + debug_assert_eq!(middle.len(), lags); + debug_assert_eq!(delayed.len(), 2 * lags - 1); let current_sq = mul14(current, current); - for lag in 0..TRACKING_LAGS { - let middle = middle[TRACKING_LAGS - 1 - lag]; - let delayed = delayed[2 * (TRACKING_LAGS - 1) - lag * 2]; + for lag in 0..lags { + let middle = middle[lags - 1 - lag]; + let delayed = delayed[2 * (lags - 1) - lag * 2]; energy[lag] = energy[lag].wrapping_add(current_sq.wrapping_sub(mul14(delayed, delayed))); cross[lag] = cross[lag] @@ -549,17 +613,19 @@ impl PitchTracker { /// Stores one Q14 sample word, advances acquisition or tracking, and /// reports transitions. /// - /// The filters always advance. Acquisition uses only every eighth frame. - /// Every five frames, tracking finds its minimum again and interpolates a - /// Q6 period. If the minimum is outside slots 18..=21, the lag window - /// first moves one lag toward it. + /// The filters always advance. Acquisition uses the decimated cadence for + /// the sample rate. Every five frames, tracking finds its minimum again + /// and interpolates a Q6 period. If the minimum moves away from the center + /// slots, the lag window first moves one lag toward it. /// - /// If the minimum is at a window boundary, its lag is 19 or less, or the - /// curvature is zero, acquisition starts again. The last usable period is - /// not discarded. + /// If the minimum is at a window boundary, its lag is at or below the + /// minimum lag threshold, or the curvature is zero, acquisition starts + /// again. The last usable period is not discarded. pub(crate) fn process_sample(&mut self, sample: i32) -> PitchStep { + let history = self.raw.len(); + let trk_lags = self.tracking_energy.len(); self.write += 1; - if self.write == HISTORY { + if self.write == history { self.write = 0; } self.raw[self.write] = sample; @@ -570,7 +636,7 @@ impl PitchTracker { let filtered = filtered.to_bits(); let mut step = PitchStep::default(); if self.detecting { - if self.write & 7 == 0 { + if self.write & self.stride_mask == 0 { let lag = self.detection_lag(filtered); if lag > 0 { self.initialize_tracking(lag); @@ -579,30 +645,26 @@ impl PitchTracker { } } else { let current = self.raw[self.write]; - let mut first = ring(self.write as i32 - self.base); - let mut second = ring(self.write as i32 - self.base * 2); - if first >= TRACKING_LAGS - 1 && second >= 2 * (TRACKING_LAGS - 1) { + let mut first = ring(self.write as i32 - self.base, history); + let mut second = ring(self.write as i32 - self.base * 2, history); + if first >= trk_lags - 1 && second >= 2 * (trk_lags - 1) { // Contiguous windows let each lag update without a wrap of // its indices. Self::track_contiguous( current, - self.raw[first - (TRACKING_LAGS - 1)..=first] - .try_into() - .expect("a full tracking window"), - self.raw[second - 2 * (TRACKING_LAGS - 1)..=second] - .try_into() - .expect("79 tracking samples"), + &self.raw[first - (trk_lags - 1)..=first], + &self.raw[second - 2 * (trk_lags - 1)..=second], &mut self.tracking_energy, &mut self.tracking_cross, ); } else { let current_sq = mul14(current, current); - for lag in 0..TRACKING_LAGS { + for lag in 0..trk_lags { let middle = self.raw[first]; - first = if first == 0 { HISTORY - 1 } else { first - 1 }; + first = if first == 0 { history - 1 } else { first - 1 }; let delayed = self.raw[second]; second = if second < 2 { - second + HISTORY - 2 + second + history - 2 } else { second - 2 }; @@ -615,35 +677,35 @@ impl PitchTracker { self.tracking_counter += 1; if self.tracking_counter == 5 { self.tracking_counter = 0; - let mut best = tracking_minimum(|lag| { + let mut best = tracking_minimum(trk_lags, |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 half = trk_lags / 2; + if best == trk_lags - 1 || best == 0 || self.base + best as i32 <= self.min_lag { self.restart(); step.restarted = true; } else { - if best <= 17 && self.base > 1 { + if best <= half - 3 && self.base > 1 { self.base -= 1; best += 1; - self.tracking_energy.copy_within(0..TRACKING_LAGS - 1, 1); - self.tracking_cross.copy_within(0..TRACKING_LAGS - 1, 1); - let first = self.raw[ring(self.write as i32 - self.base * 2)]; - let second = self.raw[ring(self.write as i32 - self.base * 2 - 1)]; + self.tracking_energy.copy_within(0..trk_lags - 1, 1); + self.tracking_cross.copy_within(0..trk_lags - 1, 1); + let first = self.raw[ring(self.write as i32 - self.base * 2, history)]; + let second = self.raw[ring(self.write as i32 - self.base * 2 - 1, history)]; self.tracking_energy[0] = self.tracking_energy[1] .wrapping_sub(mul14(first, first).wrapping_add(mul14(second, second))); self.tracking_cross[0] = self.cross_at(self.base); - } else if best > 21 { + } else if best > half + 1 && (self.base as usize) + trk_lags < history / 2 { self.base += 1; best -= 1; - self.tracking_energy.copy_within(1..TRACKING_LAGS, 0); - self.tracking_cross.copy_within(1..TRACKING_LAGS, 0); - let total = self.base + TRACKING_LAGS as i32 - 1; - let first = self.raw[ring(self.write as i32 - total * 2 + 2)]; - let second = self.raw[ring(self.write as i32 - total * 2 + 1)]; - self.tracking_energy[TRACKING_LAGS - 1] = self.tracking_energy - [TRACKING_LAGS - 2] + self.tracking_energy.copy_within(1..trk_lags, 0); + self.tracking_cross.copy_within(1..trk_lags, 0); + let total = self.base + trk_lags as i32 - 1; + let first = self.raw[ring(self.write as i32 - total * 2 + 2, history)]; + let second = self.raw[ring(self.write as i32 - total * 2 + 1, history)]; + self.tracking_energy[trk_lags - 1] = self.tracking_energy[trk_lags - 2] .wrapping_add(mul14(second, second).wrapping_add(mul14(first, first))); - self.tracking_cross[TRACKING_LAGS - 1] = self.cross_at(total); + self.tracking_cross[trk_lags - 1] = self.cross_at(total); } let y0 = (self.tracking_energy[best - 1] >> 1) .wrapping_sub(self.tracking_cross[best - 1]); diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..1c13777 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -7,7 +7,7 @@ use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; -use crate::resynthesis::{self, Resynthesis}; +use crate::resynthesis::Resynthesis; use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. @@ -90,9 +90,9 @@ impl Processor { /// I/O. Audio histories, pitch reports and meters start clear. The random /// stream starts from the low 32 bits of `random_seed`. /// - /// Punch uses its default cached drive until the first window of 100 - /// frames with Punch enabled. The initial note table of correction has the - /// rate behavior that [`crate::CorrectionConfig`] describes. + /// Punch uses its default cached drive until the first peak window + /// completes with Punch enabled. Construction loads the correction note + /// table for the prepared sample rate. /// /// # Errors /// @@ -103,7 +103,7 @@ impl Processor { pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { config.validate()?; let rate = preparation.sample_rate; - // Drive uses the default gain until the first 100-frame peak window. + // Drive uses the default gain until the first peak window completes. let mut punch = Punch::new(rate, PunchConfig::default()); punch.set_config(config.punch); Ok(Self { @@ -112,7 +112,7 @@ impl Processor { punch, warm: Warm::new(rate, config.warm), resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), - alien: Alien::new(config.alien), + alien: Alien::new(rate, config.alien), reverb: Reverb::new(rate, config.reverb), numeric: NumericContext::new(config.resynthesis.random_seed as u32), peak: 0, @@ -295,13 +295,11 @@ impl Processor { /// silence. It can also stop filter output that continues for a long /// time. pub fn tail_frames(&self) -> usize { + let rate = self.preparation.sample_rate; self.resynthesis .tail_frames() - .saturating_add(alien::tail_frames(self.config.alien)) - .saturating_add(reverb::tail_frames( - self.preparation.sample_rate, - self.config.reverb, - )) + .saturating_add(alien::tail_frames(rate, self.config.alien)) + .saturating_add(reverb::tail_frames(rate, self.config.reverb)) } /// Returns the fixed sample rate and block limit. @@ -319,13 +317,14 @@ impl Processor { self.config } - /// Returns the nominal resynthesis latency: 1,593 frames at both rates. + /// Returns the nominal resynthesis latency in frames for the prepared + /// sample rate (1,593 frames at 44.1 kHz; 1,733 frames at 48 kHz). /// - /// The dry path has a delay of 1,543 frames. Resampled voices, choir delays - /// and effects have their own timing. Thus, this value does not align all - /// paths. + /// The dry path adds only the overlap delay (1,543 frames at 44.1 kHz). + /// Resampled voices, choir delays and effects have their own timing. Thus, + /// this value does not align all paths. pub fn latency_frames(&self) -> usize { - resynthesis::LATENCY_FRAMES + self.resynthesis.latency_frames() } /// Returns the pitch, stereo peak and frame count, and does not clear them. @@ -859,17 +858,21 @@ pub struct Telemetry { /// /// The value is the ratio of the two input envelopes times the /// configured input gain. It is more than 1 at an attack. Punch updates - /// it every 100 frames. The value is 1 while Punch is disabled. + /// it after each peak window (100 frames at 44.1 kHz). The value is 1 + /// while Punch is disabled. pub punch_gain: f32, /// The linear gain that Warm applies before its saturation curve and /// removes after it. /// /// The value is the inverse of the input peak envelope. For input below - /// -30 dB, it is the gain of +30 dB. Warm updates it every 100 frames. - /// The value is 1 while Warm is disabled. + /// -30 dB, it is the gain of +30 dB. Warm updates it after each peak + /// window (100 frames at 44.1 kHz). The value is 1 while Warm is + /// disabled. pub warm_gain: f32, - /// The length of the Alien loop in frames, as - /// [`crate::AlienConfig::loop_frames`] gives. + /// The active length of the Alien loop in frames. + /// + /// The value is [`crate::AlienConfig::loop_frames`], clamped to half of + /// the prepared Alien history capacity. pub alien_loop_frames: u32, /// The current frame in the Alien loop. It is less than /// [`alien_loop_frames`](Self::alien_loop_frames). @@ -877,10 +880,11 @@ pub struct Telemetry { /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. pub alien_phase_frames: u32, - /// The wrapping count of formant analyses since construction. + /// The count of formant analyses since construction, with wrap at + /// `u32::MAX`. /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if - /// [`Processor::formant_envelope`] can give a new result. + /// The count increases once in each 10 ms analysis interval (441 frames + /// at 44.1 kHz) while the formant stage is enabled. Compare two values + /// to find if [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 91d14d5..ab403ab 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -31,11 +31,11 @@ mod history; use crate::error::{check_count, check_range}; use crate::filter::{Biquad, Design}; -use crate::formant::{Formant, FormantConfig, ANALYSIS_FRAMES}; +use crate::formant::{analysis_frames, Formant, FormantConfig}; use crate::harmony::{HarmonyConfig, HarmonyState, HARMONY_VOICES}; use crate::midi::MidiEvent; use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; -use crate::numeric::{clamp_i32, ring, NumericContext, HISTORY}; +use crate::numeric::{clamp_i32, history_frames, ring, NumericContext}; use crate::pitch::tracker::PitchTracker; use crate::pitch::{PitchConfig, PitchEstimate}; use crate::scale::{CorrectionTable, NoteMask}; @@ -73,12 +73,8 @@ pub enum MultiVoiceMode { /// mask again. Reset releases the correction keys 0..=126. It keeps key 127 /// and the active note table. Key 127 has no effect on the note table. /// -/// At construction, the chromatic table uses 44.1 kHz periods, also for a -/// 48 kHz processor. Each of these events loads the periods for the prepared -/// rate: -/// - An initial mask that is not chromatic. -/// - A later change to the mask or to `enabled`. -/// - A correction MIDI event. +/// Construction loads the periods for the prepared sample rate and the +/// configured `notes` mask. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -153,10 +149,10 @@ impl CorrectionConfig { /// Validation applies to all controls, also when their stage or voice mode /// is not active. /// -/// The dry path takes the audio after Punch and Warm and delays it by 1,543 -/// frames. The wet voice readers have more delay, which changes with the -/// pitch. After this stage, the two paths go through Alien, reverb and the -/// final output gain. +/// The dry path takes the audio after Punch and Warm and adds the overlap +/// delay (1,543 frames at 44.1 kHz). The wet voice readers have more delay, +/// which changes with the pitch. After this stage, the two paths go through +/// Alien, reverb and the final output gain. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -202,9 +198,9 @@ pub struct ResynthesisConfig { /// The scale of the choir delay table, 20..=200, without a unit. The /// default is 60. /// - /// A value of 200 uses the full fixed table of frame offsets. The unit is - /// not milliseconds. The table offset of the lead voice is zero at all - /// settings. + /// A value of 200 uses the full prepared table of frame offsets. The + /// offsets scale with the sample rate. The unit is not milliseconds. The + /// table offset of the lead voice is zero at all settings. pub choir_delay: f32, /// The stereo width of the choir, 0..=100%. The default is 100%. /// @@ -238,9 +234,9 @@ pub struct ResynthesisConfig { /// The dry fraction at the resynthesis stage, 0..=1. The default is 0. /// /// The code truncates this value to Q8. The wet weight is 1.0 minus the - /// Q8 dry weight. The dry path starts after Punch and Warm and has a - /// delay of 1,543 frames. Alien, reverb and the output gain still occur - /// after this stage. + /// Q8 dry weight. The dry path starts after Punch and Warm and adds the + /// overlap delay (1,543 frames at 44.1 kHz). Alien, reverb and the output + /// gain still occur after this stage. pub dry_mix: f32, /// The seed for choir drift and aspiration, which use the same stream. /// The default is `0x1234_abcd`. @@ -311,29 +307,65 @@ impl ResynthesisConfig { } } -/// The fixed choir delay offsets in frames, before the scale by -/// `choir_delay / 200`. +/// The reference choir delay offsets in frames at 44.1 kHz, before the scale +/// by `choir_delay / 200`. /// -/// The offset of the lead voice is zero. The values are the same at the two -/// supported rates. Thus, the duration in time changes with the sample rate. +/// The offset of the lead voice is zero. Construction scales these offsets +/// for the prepared sample rate. const SEEDS: [i32; 16] = [ 0, 0x14d1, 0x07f3, 0x115c, 0x1213, 0x1904, 0x0800, 0x2116, 0x1a53, 0x221c, 0x028d, 0x1dee, 0x0dda, 0x01da, 0x167f, 0x0896, ]; -/// The length of the analysis overlap buffer. The dry path has the same -/// delay. -const OVERLAP_FRAMES: usize = 1543; -/// The offset from the history position of a reader to its position for -/// formant synthesis. -const FORMANT_OFFSET_FRAMES: i32 = (OVERLAP_FRAMES - ANALYSIS_FRAMES) as i32; -/// The number of frames that a new reader stays behind the write position. -const READER_LAG_FRAMES: i32 = 50; -/// The nominal latency of resynthesis. Each reader moves with the pitch and -/// the delay. -/// -/// The dry path uses only `OVERLAP_FRAMES`. -pub(crate) const LATENCY_FRAMES: usize = OVERLAP_FRAMES + READER_LAG_FRAMES as usize; +/// Returns the overlap buffer length in frames (~35 ms; 1,543 frames at +/// 44.1 kHz). +const fn overlap_frames(rate: SampleRate) -> usize { + (1543 * rate.as_u32() as usize + 22_050) / 44_100 +} + +/// Returns the initial lag in frames that puts a new reader behind the writer +/// (50 frames at 44.1 kHz). +const fn reader_lag_frames(rate: SampleRate) -> i32 { + let frames = (50 * rate.as_u32() as usize + 22_050) / 44_100; + if frames < 1 { + 1 + } else { + frames as i32 + } +} + +/// Returns the minimum distance in frames between a reader and the writer +/// before a period jump (40 frames at 44.1 kHz). +const fn reader_margin_frames(rate: SampleRate) -> i32 { + let frames = (40 * rate.as_u32() as usize + 22_050) / 44_100; + if frames < 2 { + 2 + } else { + frames as i32 + } +} + +/// Returns the Q14 crossfade step for each frame after a lead-reader jump +/// (`0x333` at 44.1 kHz). +const fn fade_step(rate: SampleRate) -> Q14 { + let hz = rate.as_u32() as usize; + let step = (0x333 * 44_100 + hz / 2) / hz; + let clamped = if step < 1 { + 1 + } else if step > 16_384 { + 16_384 + } else { + step + }; + Q14::from_bits(clamped as i32) +} + +/// Scales the 44.1 kHz choir delay offsets for `rate`. +fn scaled_seeds(rate: SampleRate) -> [i32; 16] { + let hz = i64::from(rate.as_u32()); + SEEDS.map(|seed| ((i64::from(seed) * hz + 22_050) / 44_100) as i32) +} + /// The counter value at which a control step runs. Usually, a step runs /// every 101 eligible frames. /// @@ -343,8 +375,6 @@ const CONTROL_DUE: i32 = 100; /// The largest choir drift for each step, as a Q14 ratio offset /// (approximately 0.2). 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); /// Returns the reader position at the start of the history frame `frame`. #[inline] @@ -364,12 +394,27 @@ pub(crate) struct Resynthesis { /// The sample rate, which does not change. The code uses it to convert /// periods, filters and times. rate: SampleRate, + /// The ring history capacity in frames for `rate`. + history: usize, + /// The formant analysis delay in frames for `rate`. + analysis_frames: usize, + /// The offset from a reader history position to its formant synthesis + /// position. + formant_offset_frames: i32, + /// The initial distance in frames behind the writer for a new reader. + reader_lag_frames: i32, + /// The minimum distance in frames behind the writer before a period jump. + reader_margin_frames: i32, + /// The Q14 crossfade step for each frame after a lead-reader jump. + fade_step: Q14, + /// The choir delay reference offsets in frames for `rate`. + seeds: [i32; 16], /// The current resynthesis controls. The public API validates them. config: ResynthesisConfig, /// The pitch estimator at the full rate, with decimated acquisition. pitch: PitchTracker, /// The Q14 input history after Punch and Warm, before formant analysis. - raw: Box<[Q14; HISTORY]>, + raw: Box<[Q14]>, /// The current frame. The raw, period, ratio and rendered histories use /// the same frame. write: usize, @@ -386,30 +431,30 @@ pub(crate) struct Resynthesis { scale: CorrectionTable, /// The delayed source audio after the two prepared shift filters. If /// formants are enabled, the source is inverse-filtered. - filtered: Box<[Q14; HISTORY]>, + filtered: Box<[Q14]>, /// The history of the rendered choir lead. All secondary choir voices /// read this history. - lead: Box<[Q14; HISTORY]>, + lead: Box<[Q14]>, /// The Q6 tracked periods, aligned to the audio. The lead voice can /// replace a delayed entry with its resampled output period. This aligns /// the secondary voices. - periods: Box<[Q6; HISTORY]>, + periods: Box<[Q6]>, /// The last usable Q6 tracker periods. The code keeps them through /// unvoiced gaps. - previous_periods: Box<[Q6; HISTORY]>, + previous_periods: Box<[Q6]>, /// The Q14 ratios of the correction only, aligned to each recorded input /// frame. - ratios: Box<[Q14; HISTORY]>, - /// The fixed memory for the analysis overlap. It gives the source a delay - /// of 1,543 frames. - overlap: [Q14; OVERLAP_FRAMES], + ratios: Box<[Q14]>, + /// The preallocated memory for the analysis overlap. The dry path has the + /// same delay. + overlap: Box<[Q14]>, /// The current slot in the overlap ring. overlap_index: usize, /// The configured integer frame offset of each voice. Harmony uses /// offsets of zero. delays: [i32; 16], /// The Q14 fractional reader positions. When the writer wraps, the code - /// moves them back by HISTORY. + /// moves them back by `history`. positions: [Q14; 16], /// The Q14 random choir drift offsets of the secondary voices. drift: [Q14; 16], @@ -489,11 +534,22 @@ pub(crate) struct Resynthesis { impl Resynthesis { /// Creates the state from a configuration that the public API validated. pub(crate) fn new(rate: SampleRate, config: ResynthesisConfig) -> Self { + let history = history_frames(rate); + let overlap_len = overlap_frames(rate); + let analysis = analysis_frames(rate); + let reader_lag = reader_lag_frames(rate); let mut result = Self { rate, + history, + analysis_frames: analysis, + formant_offset_frames: (overlap_len - analysis) as i32, + reader_lag_frames: reader_lag, + reader_margin_frames: reader_margin_frames(rate), + fade_step: fade_step(rate), + seeds: scaled_seeds(rate), config, pitch: PitchTracker::new(rate, config.pitch), - raw: prepare_history(Q14::ZERO), + raw: prepare_history(Q14::ZERO, history), write: 0, cosine: { let mut phase = 0.0_f64; @@ -505,23 +561,13 @@ impl Resynthesis { }, formant: Formant::new(rate, config.formant), harmony: HarmonyState::new(rate, config.harmony), - scale: { - // The initial chromatic table uses 44.1 kHz periods at the two - // rates. If the notes load again, the periods for the - // configured rate become active. - let mut scale = CorrectionTable::new(SampleRate::Hz44100, NoteMask::default()); - scale.set_sample_rate(rate); - if config.correction.notes != NoteMask::default() { - scale.set_notes(config.correction.notes); - } - scale - }, - filtered: prepare_history(Q14::ZERO), - lead: prepare_history(Q14::ZERO), - periods: prepare_history(Q6::ZERO), - previous_periods: prepare_history(Q6::ZERO), - ratios: prepare_history(Q14::ONE), - overlap: [Q14::ZERO; OVERLAP_FRAMES], + scale: CorrectionTable::new(rate, config.correction.notes), + filtered: prepare_history(Q14::ZERO, history), + lead: prepare_history(Q14::ZERO, history), + periods: prepare_history(Q6::ZERO, history), + previous_periods: prepare_history(Q6::ZERO, history), + ratios: prepare_history(Q14::ONE, history), + overlap: prepare_history(Q14::ZERO, overlap_len), overlap_index: 0, delays: [0; 16], positions: [Q14::ZERO; 16], @@ -544,7 +590,7 @@ impl Resynthesis { modulation: 0, modulation_phase: Q14::ZERO, dry_mix: Q8::ZERO, - old_position: position_of(-READER_LAG_FRAMES), + old_position: position_of(-reader_lag), fade: Q14::ONE, current_output_period: Q6::ZERO, control_counter: CONTROL_DUE, @@ -623,7 +669,7 @@ impl Resynthesis { } } - /// Scales the fixed choir frame offsets and puts all readers behind the + /// Scales the prepared choir frame offsets and puts all readers behind the /// writer. /// /// Harmony uses offsets of zero. This function moves the readers. It does @@ -634,10 +680,10 @@ impl Resynthesis { } else { 0.0 }; - for (voice, seed) in SEEDS.iter().enumerate() { + for (voice, seed) in self.seeds.iter().enumerate() { self.delays[voice] = (*seed as f64 * (parameter as f64 * 0.005)) as i32; self.positions[voice] = - position_of(self.write as i32 - READER_LAG_FRAMES - self.delays[voice]); + position_of(self.write as i32 - self.reader_lag_frames - self.delays[voice]); } } @@ -737,6 +783,13 @@ impl Resynthesis { self.scale_initialized = false; } + /// Returns the nominal resynthesis latency in frames. + /// + /// The dry path uses only `overlap.len()`. + pub(crate) fn latency_frames(&self) -> usize { + self.overlap.len() + self.reader_lag_frames as usize + } + /// Returns the finite number of frames for a drain of resynthesis. /// /// The number is the sum of these items: @@ -747,7 +800,7 @@ impl Resynthesis { /// This is a configured limit for the truncation. It does not find /// actual silence. pub(crate) fn tail_frames(&self) -> usize { - 2 * HISTORY + 2 * self.history + if self.config.formant.enabled { self.rate.as_u32() as usize * 2 } else { @@ -926,7 +979,7 @@ impl Resynthesis { /// /// If the delayed audio is voiced, the function uses it. If not, it uses /// the current audio. If that is also unvoiced, it uses the last usable - /// delayed period. The indices must be less than HISTORY. + /// delayed period. The indices must be less than `history`. fn period_for(&self, delayed: usize, current: usize) -> (Q6, Q14) { if self.periods[delayed] != Q6::ZERO { (self.periods[delayed], self.ratios[delayed]) @@ -944,12 +997,13 @@ impl Resynthesis { #[inline] fn reader_bounds(&self, period: Q6, offset: i32) -> (Q14, Q14, Q14) { let write = self.write as i32; - let upper = position_of(write - 40 - offset); + let margin = self.reader_margin_frames; + let upper = position_of(write - margin - offset); let span = (period.to_bits() >> 6).wrapping_mul(12).wrapping_div(10); let lower = position_of( write .wrapping_sub(span) - .wrapping_sub(40) + .wrapping_sub(margin) .wrapping_sub(offset), ); (upper, lower, period.rescale()) @@ -1019,7 +1073,7 @@ impl Resynthesis { /// state that follows. fn render_lead(&mut self, delayed: usize, numeric: &mut NumericContext) -> (Q14, Q14) { let write = self.write; - let delay = ring(delayed as i32 - self.delays[0]); + let delay = ring(delayed as i32 - self.delays[0], self.history); let (period, mut ratio) = self.period_for(delay, write); self.current_output_period = period; ratio = ratio.mul::<14, 14>(self.drift_ratio[0]).mul(self.shift); @@ -1035,10 +1089,10 @@ impl Resynthesis { if self.fade < Q14::ONE { let (old, _) = history::interpolation(&self.filtered, self.old_position); value = value.mul(self.fade) + old.mul(Q14::ONE - self.fade); - self.fade = (self.fade + FADE_STEP).min(Q14::ONE); + self.fade = (self.fade + self.fade_step).min(Q14::ONE); } if self.config.formant.enabled { - self.formant_position = center - FORMANT_OFFSET_FRAMES; + self.formant_position = center - self.formant_offset_frames; value = Q14::from_bits(self.formant.forward( value.to_bits(), self.formant_position, @@ -1070,8 +1124,10 @@ impl Resynthesis { /// tracking was active before this frame. pub(crate) fn process_sample(&mut self, input: i16, numeric: &mut NumericContext) -> [Q14; 2] { let sample = Q14::from_bits(i32::from(input) >> 1); + let history = self.history; + let overlap_len = self.overlap.len(); self.write += 1; - if self.write == HISTORY { + if self.write == history { self.write = 0; } self.raw[self.write] = sample; @@ -1089,9 +1145,9 @@ impl Resynthesis { 5 }; for position in &mut self.positions[..voices] { - *position = *position - position_of(HISTORY as i32); + *position = *position - position_of(history as i32); } - self.old_position = self.old_position - position_of(HISTORY as i32); + self.old_position = self.old_position - position_of(history as i32); } if step.restarted { self.correction = Q14::ONE; @@ -1126,31 +1182,31 @@ impl Resynthesis { self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; self.overlap_index += 1; - if self.overlap_index == OVERLAP_FRAMES { + if self.overlap_index == overlap_len { self.overlap_index = 0; } self.overlap[self.overlap_index] = if self.config.formant.enabled { - let previous = self.raw[ring(write as i32 - 1)]; + let previous = self.raw[ring(write as i32 - 1, history)]; Q14::from_bits(self.formant.process_analysis( sample.to_bits(), previous.to_bits(), - self.periods.as_slice(), + &self.periods, write, step.previous_period.to_bits(), )) } else { - self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] + self.raw[ring(write as i32 - self.analysis_frames as i32, history)] }; - // 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 - // of the source is OVERLAP_FRAMES in the two formant modes. - let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; + // 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 of the source is `overlap_len` in the two formant modes. + let overlap_read = (self.overlap_index + self.analysis_frames) % overlap_len; let mut filtered = self.overlap[overlap_read]; for filter in &mut self.post { filtered = filter.process_sample(filtered); } self.filtered[write] = filtered; - let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); + let delayed = ring(write as i32 - overlap_len as i32, history); let dry = self.raw[delayed]; let mut mix = [Q14::ZERO; 2]; let mut final_ratio = Q14::ONE; @@ -1178,7 +1234,7 @@ impl Resynthesis { // voice order. for (lane, position) in positions.iter_mut().enumerate() { let current_voice = voice + lane; - let delay = ring(delayed as i32 - self.delays[current_voice]); + let delay = ring(delayed as i32 - self.delays[current_voice], history); let (period, _) = self.period_for(delay, write); self.current_output_period = period; let ratio = self.drift_ratio[current_voice]; @@ -1210,7 +1266,7 @@ impl Resynthesis { // The zero to three secondary readers that are left use // scalar code. for voice in voice..voice_count { - let delay = ring(delayed as i32 - self.delays[voice]); + let delay = ring(delayed as i32 - self.delays[voice], history); let (period, _) = self.period_for(delay, write); self.current_output_period = period; let ratio = self.drift_ratio[voice]; @@ -1288,7 +1344,8 @@ impl Resynthesis { } } if self.config.formant.enabled { - self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; + self.formant_position = + (self.positions[0].to_bits() >> 14) - self.formant_offset_frames; mix = self .formant .forward_stereo(mix.map(Q14::to_bits), self.formant_position, numeric) diff --git a/src/resynthesis/history.rs b/src/resynthesis/history.rs index f355efc..5134158 100644 --- a/src/resynthesis/history.rs +++ b/src/resynthesis/history.rs @@ -1,31 +1,22 @@ //! Audio histories on the heap and three-point parabolic interpolation. use crate::numeric::fixed::Q14; -use crate::numeric::{clamp_i32, ring, HISTORY}; +use crate::numeric::{clamp_i32, ring}; -/// Allocates exactly HISTORY copies of `value` on the heap and keeps that -/// length in the boxed-array type. -/// -/// The conversion from slice to array cannot fail, because the allocation -/// gives the slice the necessary length. -pub(super) fn prepare_history(value: T) -> Box<[T; HISTORY]> { - // Allocate directly on the heap. The fixed history length is then part - // of the type for index operations, and no large temporary array goes on - // the stack. - vec![value; HISTORY] - .into_boxed_slice() - .try_into() - .unwrap_or_else(|_| unreachable!("prepared voice history length")) +/// Allocates `len` copies of `value` on the heap as a boxed slice. +pub(super) fn prepare_history(value: T, len: usize) -> Box<[T]> { + vec![value; len].into_boxed_slice() } -/// Returns the previous, center and next positions in the ring buffer. +/// Returns the previous, center and next positions in a ring buffer of length +/// `len`. /// /// The center can be negative or more than one full history length. #[inline] -fn interpolation_indices(center: i32) -> [usize; 3] { - let middle = ring(center); - let left = if middle == 0 { HISTORY - 1 } else { middle - 1 }; - let right = if middle + 1 == HISTORY { 0 } else { middle + 1 }; +fn interpolation_indices(center: i32, len: usize) -> [usize; 3] { + let middle = ring(center, len); + let left = if middle == 0 { len - 1 } else { middle - 1 }; + let right = if middle + 1 == len { 0 } else { middle + 1 }; [left, middle, right] } @@ -33,13 +24,14 @@ fn interpolation_indices(center: i32) -> [usize; 3] { /// /// If possible, the function reads a contiguous slice. If not, it wraps the /// center and the two adjacent positions. The two paths keep the tap order. -fn interpolation_taps(buffer: &[T; HISTORY], center: i32) -> [T; 3] { - if center > 0 && center < (HISTORY - 1) as i32 { +fn interpolation_taps(buffer: &[T], center: i32) -> [T; 3] { + let len = buffer.len(); + if center > 0 && center < (len - 1) as i32 { let center = center as usize; let taps = &buffer[center - 1..center + 2]; [taps[0], taps[1], taps[2]] } else { - let [left, middle, right] = interpolation_indices(center); + let [left, middle, right] = interpolation_indices(center, len); [buffer[left], buffer[middle], buffer[right]] } } @@ -55,7 +47,7 @@ fn interpolation_taps(buffer: &[T; HISTORY], center: i32) -> [T; 3] { /// relative to that center. The taps wrap through the history, but the /// returned center does not. Coordinate offsets wrap at 32 bits. Sample /// products use `i64` arithmetic and clamp to `i32`. -pub(super) fn interpolation(buffer: &[Q14; HISTORY], position: Q14) -> (Q14, i32) { +pub(super) fn interpolation(buffer: &[Q14], position: Q14) -> (Q14, i32) { let bits = position.to_bits(); let center = if position > Q14::ZERO { bits.wrapping_add(8192) >> 14 diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..434b02e 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -183,11 +183,11 @@ impl CorrectionTable { result } - /// Calculates the period table again for `rate`, but does not reload the - /// active scale. + /// Calculates the period table for `rate`. /// - /// The new periods apply from the next `set_notes` call. - pub(crate) fn set_sample_rate(&mut self, rate: SampleRate) { + /// `CorrectionTable::new` calls `set_notes` right after this method so the + /// active targets match `rate` immediately. + fn set_sample_rate(&mut self, rate: SampleRate) { let frequency = ((-9.0 * std::f64::consts::LN_2 / 12.0).exp() * 440.0) as f32; let mut base = rate.hz() / frequency; while base < 10820.625 { diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..add70aa 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -119,18 +119,19 @@ pub struct WasmProcessor { impl WasmProcessor { /// Prepares a processor and its reusable PCM buffers. /// - /// `sample_rate` must be 44100 or 48000. `max_block_frames` must be an - /// integer in 1..=4294967295. It is a limit for each call, and smaller - /// blocks and empty blocks are also valid. If you omit `config`, the - /// processor uses the default configuration. The constructor validates - /// the settings before it allocates the processor or the PCM buffers. In - /// TypeScript, use `new Tunelet(sampleRate, maxBlockFrames, config)`. + /// `sample_rate` must be 8000, 16000, 22050, 24000, 32000, 44100, 48000, + /// 88200, 96000 or 192000. `max_block_frames` must be an integer in + /// 1..=4294967295. It is a limit for each call, and smaller blocks and + /// empty blocks are also valid. If you omit `config`, the processor uses + /// the default configuration. The constructor validates the settings + /// before it allocates the processor or the PCM buffers. In TypeScript, + /// use `new Tunelet(sampleRate, maxBlockFrames, config)`. /// /// # Errors /// /// The constructor throws if one of these conditions occurs: /// - /// - The rate is not 44100 or 48000. + /// - The rate is not one of the ten supported sample rates. /// - The block limit is not an integer or is out of range. /// - The configuration object is malformed or a field is missing. /// - The configuration is not valid. @@ -147,9 +148,21 @@ impl WasmProcessor { // Accept JavaScript numbers without the u32 coercion of wasm-bindgen. // That coercion silently truncates fractions and wraps large values. let rate = match sample_rate { + 8000.0 => SampleRate::Hz8000, + 16000.0 => SampleRate::Hz16000, + 22050.0 => SampleRate::Hz22050, + 24000.0 => SampleRate::Hz24000, + 32000.0 => SampleRate::Hz32000, 44100.0 => SampleRate::Hz44100, 48000.0 => SampleRate::Hz48000, - _ => return Err(JsError::new("sampleRate must be 44100 or 48000")), + 88200.0 => SampleRate::Hz88200, + 96000.0 => SampleRate::Hz96000, + 192000.0 => SampleRate::Hz192000, + _ => { + return Err(JsError::new( + "sampleRate must be 8000, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000 or 192000", + )) + } }; if !(1.0..=f64::from(u32::MAX)).contains(&max_block_frames) || max_block_frames.fract() != 0.0 @@ -191,11 +204,12 @@ impl WasmProcessor { self.input.len() } - /// The nominal resynthesis latency: 1,593 frames at both sample rates. + /// The nominal resynthesis latency in frames for the prepared sample rate + /// (1,593 frames at 44.1 kHz; 1,733 frames at 48 kHz). /// - /// The dry path has a delay of 1,543 frames. Resampled voices, choir delays - /// and effects have their own timing. Thus, this value does not align all - /// paths. + /// The dry path adds only the overlap delay (1,543 frames at 44.1 kHz). + /// Resampled voices, choir delays and effects have their own timing. Thus, + /// this value does not align all paths. #[wasm_bindgen(getter, js_name = latencyFrames)] pub fn latency_frames(&self) -> usize { self.processor.latency_frames()