diff --git a/README.md b/README.md index 83a8f47..09fbd1c 100644 --- a/README.md +++ b/README.md @@ -198,8 +198,14 @@ The default is 4. `FixedInterval` and `SmartInterval` use the first `voices` voices. The other voices release with the usual gain envelope. The chord and MIDI sources ignore this field. -`resynthesis.harmony_gain` scales the four harmony voices in mono and in -stereo. It does not scale the lead voice. +`resynthesis.lead_gain` (`0..=1`, default `1`) scales the lead voice in mono +and in stereo. `resynthesis.harmony_gain` (`0..=1`, default `0.5`) scales the +four harmony voices in mono and in stereo. It does not scale the lead voice. On +`resynthesis.harmony`, `voice_gains` (`0..=1`), `voice_pans` (`-1..=1`) and +`voice_mutes` control each of the four harmony voices. If +`resynthesis.formant.enabled` is `true`, `voice_formant_stretch` and +`voice_formant_width` (`0.5..=2`, default `1`) set separate vocal-tract length +and width models for the four harmony voices. ## Process audio @@ -451,10 +457,11 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +JavaScript `Error`. Optional fields (`resynthesis.leadGain`, and `voices`, +`voiceGains`, `voicePans`, `voiceMutes`, `voiceFormantStretch` and +`voiceFormantWidth` on `resynthesis.harmony`) use their defaults if they are +absent. The conversion ignores extra object properties. The generated +declarations contain the parameter documentation from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/src/formant.rs b/src/formant.rs index bf9ee5a..b5de9d2 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -20,6 +20,7 @@ use crate::error::check_range; use crate::filter::{Biquad, Design}; +use crate::harmony::HARMONY_VOICES; use crate::lpc; use crate::numeric::fixed::{Q14, Q6}; use crate::numeric::{clamp_i32, db_to_gain, fast_sinc, mul14, round_q14, NumericContext}; @@ -119,6 +120,9 @@ const MAX_ORDER: usize = 110; /// The number of coefficient banks in the ring. The stamps of the audio /// history refer to these banks. const BANKS: usize = 30; +/// The number of synthesis voice models: the lead voice and four harmony +/// voices. +pub(crate) const SYNTHESIS_BANKS: usize = HARMONY_VOICES + 1; /// The model selection for one frame of input history. /// @@ -147,7 +151,7 @@ impl Default for Stamp { } /// The formant stage. It holds preallocated analysis memory, the model -/// history and the synthesis state for two channels. +/// histories and the synthesis state for five voice banks. #[derive(Debug)] pub(crate) struct Formant { /// The validated formant controls. The resynthesis caller decides if this @@ -164,12 +168,12 @@ pub(crate) struct Formant { temporary: Vec, /// The Q14 coefficient banks for the inverse filter. inverse: Vec<[i32; ORDER]>, - /// The Q14 coefficient banks for the forward filter. `orders` holds the - /// active lengths. - models: Vec<[i32; MAX_ORDER]>, - /// The valid synthesis order for each bank. Zero means that there is no - /// feedback model. - orders: [usize; BANKS], + /// The Q14 coefficient banks for the five forward synthesis filters. + /// `orders` holds the active lengths. + models: Vec<[[i32; MAX_ORDER]; SYNTHESIS_BANKS]>, + /// The valid synthesis order for each voice bank and ring slot. Zero means + /// that there is no feedback model. + orders: [[usize; BANKS]; SYNTHESIS_BANKS], /// One record of a bank pair and a blend for each frame of input history. stamps: Vec, /// The index of the current coefficient bank. @@ -183,10 +187,10 @@ pub(crate) struct Formant { /// A counter that increases from a negative value to zero. At zero, the /// stage tries to make a model. 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], - /// The next slot in the synthesis history. The two channels use the same + /// The separate Q14 feedback histories of the synthesis, for the lead + /// voice and the four harmony voices. Choir uses slot zero. + history: [[i32; MAX_ORDER]; SYNTHESIS_BANKS], + /// The next slot in the synthesis history. All voice banks use the same /// slot. history_index: usize, /// The two previous normalized autocorrelation vectors for the moving @@ -205,20 +209,20 @@ pub(crate) struct Formant { dirty: bool, /// The Q14 first-order coefficient for pre-emphasis and de-emphasis. glottal: i32, - /// The Q14 width control. The stage also uses it as the output gain of - /// the forward filter. - width: i32, - /// The Q14 square of the width, for the scale of the tract areas. - width_squared: i32, - /// The Q14 stretch control. The stage uses it to decide if a change to - /// the areas is necessary. - stretch: i32, - /// The number of active coefficients in the stretched model, not more + /// The Q14 width control for each voice bank. The stage also uses it as + /// the output gain of the forward filter. + width: [i32; SYNTHESIS_BANKS], + /// The Q14 square of each width, for the scale of the tract areas. + width_squared: [i32; SYNTHESIS_BANKS], + /// The Q14 stretch control for each voice bank. The stage uses it to + /// decide if a change to the areas is necessary. + stretch: [i32; SYNTHESIS_BANKS], + /// The number of active coefficients in each stretched model, not more /// 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], + stretch_count: [usize; SYNTHESIS_BANKS], + /// The Q7 positions that map each stretched model into the area model with + /// 50 sections. + stretch_map: [[i32; MAX_ORDER]; SYNTHESIS_BANKS], /// The original tract areas, with the runtime scale that the LPC /// conversion returns. areas: [i32; MAX_ORDER], @@ -263,7 +267,12 @@ impl Formant { /// At the supported rates, the capacity of the temporary segment holds /// the longest analysis segment and the predictor padding. Later calls /// use this memory again. - pub(crate) fn new(rate: SampleRate, config: FormantConfig) -> Self { + pub(crate) fn new( + rate: SampleRate, + config: FormantConfig, + voice_width: [f32; HARMONY_VOICES], + voice_stretch: [f32; HARMONY_VOICES], + ) -> Self { let d1 = -std::f64::consts::LN_2 / 0.9_f64.ln(); let d2 = rate.hz() as f64 * d1 / 44100.0; let mut result = Self { @@ -272,14 +281,14 @@ impl Formant { input: vec![0; HISTORY_FRAMES], temporary: vec![0_i32; (2 * (rate.as_u32() as usize / 40) + MAX_ORDER + 256).max(2865)], inverse: vec![[0; ORDER]; BANKS], - models: vec![[0; MAX_ORDER]; BANKS], - orders: [0; BANKS], + models: vec![[[0; MAX_ORDER]; SYNTHESIS_BANKS]; BANKS], + orders: [[0; BANKS]; SYNTHESIS_BANKS], stamps: vec![Stamp::default(); HISTORY_FRAMES], current: 1, previous: 0, blend: 0, design_counter: 0, - history: [[0; MAX_ORDER]; 2], + history: [[0; MAX_ORDER]; SYNTHESIS_BANKS], history_index: 0, correlation_history: [[0; 111]; 2], correlation_sum: [0; 111], @@ -288,11 +297,11 @@ impl Formant { smooth_reset: true, dirty: false, glottal: (0.5_f64.powf(1.0 / d2) * 16384.0) as i32, - width: 16384, - width_squared: 16384, - stretch: 16384, - stretch_count: ORDER, - stretch_map: [0; MAX_ORDER], + width: [16384; SYNTHESIS_BANKS], + width_squared: [16384; SYNTHESIS_BANKS], + stretch: [16384; SYNTHESIS_BANKS], + stretch_count: [ORDER; SYNTHESIS_BANKS], + stretch_map: [[0; MAX_ORDER]; SYNTHESIS_BANKS], areas: [0; MAX_ORDER], stretched_areas: [0; MAX_ORDER], noise_filter: Biquad::new(), @@ -300,27 +309,26 @@ impl Formant { noise_amplitude: 0_i32, generation: 0, }; - result.set_config(config); + result.set_config(config, voice_width, voice_stretch); result } - /// Quantizes the validated controls, prepares the Q7 map for the area + /// Quantizes the validated controls, prepares the Q7 maps 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 + /// 99 entries. Thus, the last point of each map and the denominators of /// the interpolation are always defined. - pub(crate) fn set_config(&mut self, config: FormantConfig) { + pub(crate) fn set_config( + &mut self, + config: FormantConfig, + voice_width: [f32; HARMONY_VOICES], + voice_stretch: [f32; HARMONY_VOICES], + ) { 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); - 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.prepare_bank(0, config.width, config.stretch); + for voice in 0..HARMONY_VOICES { + self.prepare_bank(voice + 1, voice_width[voice], voice_stretch[voice]); } - 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) @@ -329,6 +337,25 @@ impl Formant { self.noise_filter .set_design(Design::high_pass(self.rate.hz(), frequency as f32, 0.707)); } + /// Quantizes the width and stretch controls for one synthesis bank. + fn prepare_bank(&mut self, bank: usize, width: f32, stretch: f32) { + self.width[bank] = (width as f64 * 16384.0) as i32; + self.width_squared[bank] = (width as f64 * width as f64 * 16384.0) as i32; + self.stretch[bank] = (stretch as f64 * 16384.0) as i32; + let count = (((ORDER - 1) as f64 * stretch as f64 + 1.001) as usize).min(MAX_ORDER); + self.stretch_count[bank] = count; + for (i, entry) in self.stretch_map[bank][..count - 1].iter_mut().enumerate() { + let fraction = i as f64 / (count - 1) as f64; + *entry = ((ORDER - 1) as f64 * fraction * 128.0) as i32; + } + self.stretch_map[bank][count - 1] = ((ORDER - 1) * 128) as i32; + } + /// Clears the synthesis feedback of the four harmony banks. + pub(crate) fn clear_harmony_history(&mut self) { + for history in &mut self.history[1..] { + history.fill(0_i32); + } + } /// Clears the audio, the stamps, the synthesis history and the history of /// the aspiration filter. /// @@ -343,7 +370,7 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER]; 2]; + self.history = [[0; MAX_ORDER]; SYNTHESIS_BANKS]; self.history_index = 0; self.current = BANKS - 1; self.next_filter(); @@ -411,8 +438,10 @@ impl Formant { self.blend = 0; self.inverse[self.current].fill(0_i32); - self.models[self.current].fill(0_i32); - self.orders[self.current] = 0; + for bank in 0..SYNTHESIS_BANKS { + self.models[self.current][bank].fill(0_i32); + self.orders[bank][self.current] = 0; + } } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. @@ -615,38 +644,50 @@ impl Formant { ); if valid { - if self.width != one || self.stretch != one { - if let Some(scale) = lpc::parcor_to_areas(&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 fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); - self.stretched_areas[i] = mul14( - mul14(one.wrapping_sub(fraction), self.areas[index]) - .wrapping_add(mul14(fraction, self.areas[index + 1])), - self.width_squared, - ); - if self.stretched_areas[i] == 0_i32 { - self.stretched_areas[i] = 1; + let needs_areas = (0..SYNTHESIS_BANKS) + .any(|bank| self.width[bank] != one || self.stretch[bank] != one); + let area_scale = if needs_areas { + lpc::parcor_to_areas(&parcor[..ORDER], &mut self.areas) + } else { + None + }; + for bank in 0..SYNTHESIS_BANKS { + if self.width[bank] != one || self.stretch[bank] != one { + if let Some(scale) = area_scale { + let count = self.stretch_count[bank]; + for i in 0..count { + let map = self.stretch_map[bank][i]; + 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]) + .wrapping_add(mul14(fraction, self.areas[index + 1])), + self.width_squared[bank], + ); + if self.stretched_areas[i] == 0_i32 { + self.stretched_areas[i] = 1; + } + } + if lpc::areas_to_parcor( + &self.stretched_areas[..count], + &mut parcor, + scale, + ) { + lpc::parcor_to_pef( + &parcor[..count], + &mut self.models[self.current][bank], + &mut scratch, + 14, + ); + self.orders[bank][self.current] = count; } } - if lpc::areas_to_parcor( - &self.stretched_areas[..self.stretch_count], - &mut parcor, - scale, - ) { - lpc::parcor_to_pef( - &parcor[..self.stretch_count], - &mut self.models[self.current], - &mut scratch, - 14, - ); - self.orders[self.current] = self.stretch_count; - } + } else { + self.models[self.current][bank][..ORDER] + .copy_from_slice(&self.inverse[self.current]); + self.orders[bank][self.current] = ORDER; } - } else { - self.models[self.current][..ORDER].copy_from_slice(&self.inverse[self.current]); - self.orders[self.current] = ORDER; } } else { self.smooth_reset = true; @@ -708,35 +749,41 @@ impl Formant { mul14(sample, 16384_i32.saturating_sub(self.noise_gain)) .saturating_add(mul14(noise, self.noise_gain)) } - /// Finds the synthesis model of the stamp at a signed history frame. + /// Finds the synthesis model of `bank` at a signed history frame. /// /// If `stamp.blend` is 16384 or the previous bank has order zero, the /// function borrows the current bank. If not, the function returns `None`. /// Negative positions wrap in the ring. #[inline] - fn coefficients(&self, position: i32) -> Option<&[i32]> { + fn coefficients(&self, bank: usize, position: i32) -> Option<&[i32]> { let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; let current = usize::from(stamp.current); let previous = usize::from(stamp.previous); - if stamp.blend < 16384 && self.orders[previous] != 0 { + if stamp.blend < 16384 && self.orders[bank][previous] != 0 { None } else { - Some(&self.models[current][..self.orders[current]]) + Some(&self.models[current][bank][..self.orders[bank][current]]) } } - /// Blends the two synthesis banks at a signed history frame into `output`. + /// Blends the two synthesis models of `bank` at a signed history frame + /// into `output`. /// /// Returns the active prefix of `output`. Negative positions wrap in the /// ring. - fn blend_coefficients<'a>(&self, position: i32, output: &'a mut [i32; MAX_ORDER]) -> &'a [i32] { + fn blend_coefficients<'a>( + &self, + bank: usize, + position: i32, + output: &'a mut [i32; MAX_ORDER], + ) -> &'a [i32] { let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; let current = usize::from(stamp.current); let previous = usize::from(stamp.previous); let blend = i32::from(stamp.blend); - let order = self.orders[current].max(self.orders[previous]); + let order = self.orders[bank][current].max(self.orders[bank][previous]); for (i, value) in output[..order].iter_mut().enumerate() { - *value = mul14(16384 - blend, self.models[previous][i]) - .saturating_add(mul14(blend, self.models[current][i])); + *value = mul14(16384 - blend, self.models[previous][bank][i]) + .saturating_add(mul14(blend, self.models[current][bank][i])); } &output[..order] } @@ -783,11 +830,11 @@ impl Formant { output: &mut [f32], ) -> bool { let mut blended; - let synthesis = if let Some(slice) = self.coefficients(position) { + let synthesis = if let Some(slice) = self.coefficients(0, position) { slice } else { blended = [0; MAX_ORDER]; - self.blend_coefficients(position, &mut blended) + self.blend_coefficients(0, position, &mut blended) }; if synthesis.is_empty() { input.fill(0.0); @@ -805,7 +852,7 @@ impl Formant { 0.0 }; let glottal = self.glottal as f64 / 16384.0; - let width = self.width as f64 / 16384.0; + let width = self.width[0] as f64 / 16384.0; // |1 - sum(c[i] * z^-(i+1))| at z = e^(j * omega). let magnitude = |coefficients: &[i32], cosine: f64, sine: f64| { let (mut real, mut imaginary) = (1.0, 0.0); @@ -829,10 +876,10 @@ impl Formant { } true } - /// Applies the optional aspiration and the stamped synthesis model to one - /// Q14 excitation, then scales the result by the width. + /// Applies the optional aspiration and the lead synthesis model to one + /// Q14 excitation, then scales the result by the lead width. /// - /// The function uses the feedback history of channel zero. `position` is + /// The function uses the feedback history of bank zero. `position` is /// an integer frame of the input history. Resynthesis aligns this frame. pub(crate) fn forward( &mut self, @@ -843,11 +890,11 @@ impl Formant { self.dirty = true; let sample = self.add_noise(sample, context); let mut blended; - let coefficients = if let Some(slice) = self.coefficients(position) { + let coefficients = if let Some(slice) = self.coefficients(0, position) { slice } else { blended = [0; MAX_ORDER]; - self.blend_coefficients(position, &mut blended) + self.blend_coefficients(0, position, &mut blended) }; let sum = ring_sum(&self.history[0], self.history_index, coefficients); let sample = sample.saturating_add(round_q14(sum)); @@ -856,43 +903,49 @@ impl Formant { if self.history_index == MAX_ORDER { self.history_index = 0; } - round_q14(i64::from(sample) * i64::from(self.width)) + round_q14(i64::from(sample) * i64::from(self.width[0])) } - /// Synthesizes two Q14 channels with one stamped model for the two - /// channels. Each channel has its own feedback history. + /// Synthesizes the lead voice and four harmony voices with their separate + /// stamped models and feedback histories. /// - /// The function applies the aspiration mix one time to the stereo - /// midpoint. Then it adds the change of the midpoint to the two channels. - /// If aspiration is active, the function reads one random value for each - /// frame. The history cursor is the same for the two channels. It - /// advances only after the two channels. - pub(crate) fn forward_stereo( + /// If aspiration is active, the function reads one random value for the + /// frame and filters it one time. Each voice modulates that filtered noise + /// with its own Q14 excitation. The history cursor is the same for all + /// five banks and advances after the five voices. + pub(crate) fn forward_voices( &mut self, - mut samples: [i32; 2], - position: i32, + mut samples: [i32; SYNTHESIS_BANKS], + positions: [i32; SYNTHESIS_BANKS], context: &mut NumericContext, - ) -> [i32; 2] { + ) -> [i32; SYNTHESIS_BANKS] { self.dirty = true; - let mid = ((i64::from(samples[0]) + i64::from(samples[1])) >> 1) as i32; - let noise = self.add_noise(mid, context).saturating_sub(mid); - for sample in &mut samples { - *sample = sample.saturating_add(noise); - } - let mut blended; - let coefficients = if let Some(slice) = self.coefficients(position) { - slice + let shaped_noise = if self.config.aspiration_mix <= 0.01 { + None } else { - blended = [0; MAX_ORDER]; - self.blend_coefficients(position, &mut blended) + let random = (context.random.next_u31() >> 17) - 8192; + let filtered = self + .noise_filter + .process_sample(Q14::from_bits(random)) + .to_bits(); + Some(mul14(self.noise_amplitude, filtered)) }; - let sums = [ - ring_sum(&self.history[0], self.history_index, coefficients), - ring_sum(&self.history[1], self.history_index, coefficients), - ]; - for (channel, sample) in samples.iter_mut().enumerate() { - *sample = sample.saturating_add(round_q14(sums[channel])); - self.history[channel][self.history_index] = *sample; - *sample = round_q14(i64::from(*sample) * i64::from(self.width)); + for (bank, sample) in samples.iter_mut().enumerate() { + if let Some(shaped) = shaped_noise { + let noise = clamp_i32(i64::from(mul14(shaped, *sample)) << 6); + *sample = mul14(*sample, 16384_i32.saturating_sub(self.noise_gain)) + .saturating_add(mul14(noise, self.noise_gain)); + } + let mut blended; + let coefficients = if let Some(slice) = self.coefficients(bank, positions[bank]) { + slice + } else { + blended = [0; MAX_ORDER]; + self.blend_coefficients(bank, positions[bank], &mut blended) + }; + let sum = ring_sum(&self.history[bank], self.history_index, coefficients); + *sample = sample.saturating_add(round_q14(sum)); + self.history[bank][self.history_index] = *sample; + *sample = round_q14(i64::from(*sample) * i64::from(self.width[bank])); } self.history_index += 1; if self.history_index == MAX_ORDER { diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..0889101 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -240,6 +240,7 @@ pub enum Inversion { /// - A register of 50%. /// - A closed voicing and zero portamento. /// - Four voices for the interval sources. +/// - Unity gains, default stereo pans, no mutes and unity formant factors. /// /// These settings configure all sources. Only the fields for the selected /// source change the target notes. Validation always checks all fields. @@ -328,14 +329,91 @@ pub struct HarmonyConfig { tsify(optional) )] pub voices: u8, + /// Four linear gains for the harmony voices, each in 0..=1. + /// + /// The default is `[1, 1, 1, 1]`. Each gain multiplies + /// [`crate::ResynthesisConfig::harmony_gain`] and the controller envelope + /// in mono and stereo modes. In JavaScript, the field is optional and an + /// absent value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_voice_unit"), + tsify(optional, type = "[number, number, number, number]") + )] + pub voice_gains: [f32; HARMONY_VOICES], + /// Four stereo pan positions for the harmony voices, each in -1..=1. + /// + /// A value of -1 is full left, 0 is center and 1 is full right. The + /// default is `[-1/3, 1/3, -1, 1]`. Resynthesis uses these pans only if + /// [`crate::ResynthesisConfig::stereo_output`] is `true`. In JavaScript, + /// the field is optional and an absent value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_voice_pans"), + tsify(optional, type = "[number, number, number, number]") + )] + pub voice_pans: [f32; HARMONY_VOICES], + /// Four mute switches for the harmony voices. + /// + /// The default is `[false, false, false, false]`. If an entry is `true`, + /// resynthesis sets the mix gain of that voice to zero in mono and stereo + /// modes. In JavaScript, the field is optional and an absent value gives + /// the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional, type = "[boolean, boolean, boolean, boolean]") + )] + pub voice_mutes: [bool; HARMONY_VOICES], + /// Four vocal-tract length factors for the harmony voices, each in + /// 0.5..=2. + /// + /// The default is `[1, 1, 1, 1]`. If the formant stage is enabled, each + /// factor sets the area interpolation and the filter order of its voice + /// bank. In JavaScript, the field is optional and an absent value gives + /// the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_voice_unit"), + tsify(optional, type = "[number, number, number, number]") + )] + pub voice_formant_stretch: [f32; HARMONY_VOICES], + /// Four vocal-tract width factors for the harmony voices, each in + /// 0.5..=2. + /// + /// The default is `[1, 1, 1, 1]`. If the formant stage is enabled, the + /// square of each factor scales the tract areas of its voice bank. The + /// factor also scales the synthesized output of that voice. In JavaScript, + /// the field is optional and an absent value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_voice_unit"), + tsify(optional, type = "[number, number, number, number]") + )] + pub voice_formant_width: [f32; HARMONY_VOICES], } +/// The default stereo pans for the four harmony voices. +const DEFAULT_VOICE_PANS: [f32; HARMONY_VOICES] = [-1.0 / 3.0, 1.0 / 3.0, -1.0, 1.0]; + /// The default count of interval voices: all of them. #[cfg(all(feature = "wasm", target_arch = "wasm32"))] fn default_voices() -> u8 { HARMONY_VOICES as u8 } +/// The default unity array for per-voice gains and formant factors. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_voice_unit() -> [f32; HARMONY_VOICES] { + [1.0; HARMONY_VOICES] +} + +/// The default stereo pans for JavaScript configurations that omit the field. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_voice_pans() -> [f32; HARMONY_VOICES] { + DEFAULT_VOICE_PANS +} + impl Default for HarmonyConfig { fn default() -> Self { Self { @@ -351,6 +429,11 @@ impl Default for HarmonyConfig { voicing_spread_percent: 0.0, portamento_ms: 0.0, voices: HARMONY_VOICES as u8, + voice_gains: [1.0; HARMONY_VOICES], + voice_pans: DEFAULT_VOICE_PANS, + voice_mutes: [false; HARMONY_VOICES], + voice_formant_stretch: [1.0; HARMONY_VOICES], + voice_formant_width: [1.0; HARMONY_VOICES], } } } @@ -389,7 +472,22 @@ impl HarmonyConfig { self.portamento_ms, 0.0, 10_000.0, - ) + )?; + for gain in self.voice_gains { + check_range("resynthesis.harmony.voice_gains", gain, 0.0, 1.0)?; + } + for pan in self.voice_pans { + check_range("resynthesis.harmony.voice_pans", pan, -1.0, 1.0)?; + } + for stretch in self.voice_formant_stretch { + let field = "resynthesis.harmony.voice_formant_stretch"; + check_range(field, stretch, 0.5, 2.0)?; + } + for width in self.voice_formant_width { + let field = "resynthesis.harmony.voice_formant_width"; + check_range(field, width, 0.5, 2.0)?; + } + Ok(()) } } @@ -539,7 +637,15 @@ impl HarmonyState { if old.portamento_ms != config.portamento_ms { self.prepare_portamento(); } - if old != config { + if old.source != config.source + || old.key != config.key + || old.scale != config.scale + || old.chord != config.chord + || old.degree != config.degree + || old.inversion != config.inversion + || old.register_percent != config.register_percent + || old.voicing_spread_percent != config.voicing_spread_percent + { self.setup_chord(); } } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..3772e2c 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -12,8 +12,8 @@ //! //! Choir renders the lead voice first. Then it makes delayed secondary voices //! with drift from the lead history. Harmony renders the lead voice and four -//! readers with independent controls. It applies formant synthesis after the -//! voices are mixed. +//! readers with independent controls. It applies formant synthesis to each +//! voice before the gain and pan sum. //! //! A reader jumps by one pitch period to stay in a range behind the writer. //! The choir lead uses a crossfade across these jumps. Harmonic modulation @@ -31,7 +31,7 @@ mod history; use crate::error::{check_count, check_range}; use crate::filter::{Biquad, Design}; -use crate::formant::{Formant, FormantConfig, ANALYSIS_FRAMES}; +use crate::formant::{Formant, FormantConfig, ANALYSIS_FRAMES, SYNTHESIS_BANKS}; use crate::harmony::{HarmonyConfig, HarmonyState, HARMONY_VOICES}; use crate::midi::MidiEvent; use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; @@ -223,11 +223,23 @@ pub struct ResynthesisConfig { /// Validation applies to these controls, and they can receive MIDI, also /// while Choir is selected. pub harmony: HarmonyConfig, + /// The linear gain of the lead voice in [`MultiVoiceMode::Harmony`], + /// 0..=1. The default is 1. + /// + /// This gain applies in mono and stereo modes. Choir does not use this + /// control. In JavaScript, the field is optional and an absent value gives + /// the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_lead_gain"), + tsify(optional) + )] + pub lead_gain: f32, /// The linear gain of the four harmony voices, 0..=1. The default is 0.5. /// - /// If `stereo_output` is `true`, the stereo pan gains include this gain. - /// If `stereo_output` is `false`, this gain scales each harmony voice - /// directly. It does not scale the lead voice. + /// Resynthesis multiplies this gain with the gain of each harmony voice in + /// mono and stereo modes. It does not scale the lead voice, and Choir does + /// not use it. pub harmony_gain: f32, /// The modulation depth, 0..=24, without a unit. The default is 0 (off). /// @@ -267,6 +279,7 @@ impl Default for ResynthesisConfig { choir_spread_percent: 100.0, stereo_output: false, harmony: HarmonyConfig::default(), + lead_gain: 1.0, harmony_gain: 0.5, harmonic_modulation: 0.0, dry_mix: 0.0, @@ -298,6 +311,7 @@ impl ResynthesisConfig { check_range("resynthesis.choir_delay", self.choir_delay, 20.0, 200.0)?; let field = "resynthesis.choir_spread_percent"; check_range(field, self.choir_spread_percent, 0.0, 100.0)?; + check_range("resynthesis.lead_gain", self.lead_gain, 0.0, 1.0)?; check_range("resynthesis.harmony_gain", self.harmony_gain, 0.0, 1.0)?; let field = "resynthesis.harmonic_modulation"; check_range(field, self.harmonic_modulation, 0.0, 24.0)?; @@ -311,6 +325,12 @@ impl ResynthesisConfig { } } +/// The default linear gain of the lead voice in Harmony mode. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_lead_gain() -> f32 { + 1.0 +} + /// The fixed choir delay offsets in frames, before the scale by /// `choir_delay / 200`. /// @@ -419,11 +439,11 @@ pub(crate) struct Resynthesis { /// The Q14 left and right gains of the choir voices. The code reads them /// only if the stereo pan is enabled. pan: [[Q14; 2]; 16], - /// If stereo pan is off, the Q14 linear gain of the harmony voices. - harmony_gain: Q14, - /// The Q14 pan gains of the harmony voices. They include the configured - /// harmony level. + /// The Q14 left and right gains of the harmony voices. They include the + /// harmony gain, the per-voice gain, the mute state and the optional pan. harmony_pan: [[Q14; 2]; HARMONY_VOICES], + /// The Q14 linear gain of the lead voice in Harmony mode. + lead_gain: Q14, /// The last Q14 target ratios from the harmony controller. harmony_ratios: [Q14; HARMONY_VOICES], /// The last Q12 gain envelopes from the harmony controller. An audio @@ -483,9 +503,9 @@ pub(crate) struct Resynthesis { /// The Q14 weight of new drift, from the choir detune and the drift /// decay. drift_amount: Q14, - /// The previous Q14 synthesized output for each channel. The glottal + /// The previous Q14 synthesized output for each voice bank. The glottal /// envelope uses it. - previous_output: [Q14; 2], + previous_output: [Q14; SYNTHESIS_BANKS], } impl Resynthesis { @@ -505,7 +525,12 @@ impl Resynthesis { value }) }, - formant: Formant::new(rate, config.formant), + formant: Formant::new( + rate, + config.formant, + config.harmony.voice_formant_width, + config.harmony.voice_formant_stretch, + ), harmony: HarmonyState::new(rate, config.harmony), scale: { // The initial chromatic table uses 44.1 kHz periods at the two @@ -530,8 +555,8 @@ impl Resynthesis { drift: [Q14::ZERO; 16], drift_ratio: [Q14::ONE; 16], pan: [[Q14::ONE; 2]; 16], - harmony_gain: Q14::ZERO, harmony_pan: [[Q14::ZERO; 2]; HARMONY_VOICES], + lead_gain: Q14::ONE, harmony_ratios: [Q14::ONE; HARMONY_VOICES], harmony_gains: [Q12::ZERO; HARMONY_VOICES], voice_ratios: [Q14::ONE; HARMONY_VOICES + 1], @@ -553,7 +578,7 @@ impl Resynthesis { control_counter: CONTROL_DUE, drift_decay: Q14::ZERO, drift_amount: Q14::ZERO, - previous_output: [Q14::ZERO; 2], + previous_output: [Q14::ZERO; SYNTHESIS_BANKS], }; result.configure_coefficients(); result.configure_shift_filters(); @@ -563,14 +588,13 @@ impl Resynthesis { } /// Quantizes the controls and calculates the decay coefficients and the - /// voice pan gains again. + /// voice mix and pan gains again. /// /// The coefficients are the correction decay, the drift decay and the /// drift amount. The histories and the controller phase do not change. - /// The stereo pan gains include the harmony gain. The mono harmony path - /// uses a separate Q14 gain. fn configure_coefficients(&mut self) { self.shift = Q14::from_f64(self.config.pitch_ratio as f64); + self.lead_gain = Q14::from_f64(self.config.lead_gain as f64); self.modulation = (self.config.harmonic_modulation as f64 / 8.0 * 16.0) as i32; self.dry_mix = Q8::from_f64((self.config.dry_mix * 100.0) as f64 / 100.0); self.correction_decay = if self.config.correction.retune_ms == 0.0 { @@ -595,17 +619,23 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } - self.harmony_gain = Q14::from_f64(self.config.harmony_gain as f64); - for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] - .into_iter() - .enumerate() - { - let angle: f64 = 1.57079632713 * fraction; - let gain = self.config.harmony_gain as f64; - self.harmony_pan[voice] = [ - Q14::from_f64(gain * angle.cos()), - Q14::from_f64(gain * angle.sin()), - ]; + for voice in 0..HARMONY_VOICES { + if self.config.harmony.voice_mutes[voice] { + self.harmony_pan[voice] = [Q14::ZERO; 2]; + } else { + let gain = f64::from(self.config.harmony_gain) + * f64::from(self.config.harmony.voice_gains[voice]); + if self.config.stereo_output { + let fraction = (f64::from(self.config.harmony.voice_pans[voice]) + 1.0) * 0.5; + let angle: f64 = 1.57079632713 * fraction; + self.harmony_pan[voice] = [ + Q14::from_f64(gain * angle.cos()), + Q14::from_f64(gain * angle.sin()), + ]; + } else { + self.harmony_pan[voice] = [Q14::from_f64(gain); 2]; + } + } } } @@ -650,8 +680,16 @@ impl Resynthesis { let old = self.config; self.config = config; self.pitch.set_config(config.pitch); - self.formant.set_config(config.formant); + self.formant.set_config( + config.formant, + config.harmony.voice_formant_width, + config.harmony.voice_formant_stretch, + ); self.harmony.apply_config(config.harmony); + if old.mode != config.mode { + self.formant.clear_harmony_history(); + self.previous_output[1..].fill(Q14::ZERO); + } if old.correction.notes != config.correction.notes || old.correction.enabled != config.correction.enabled { @@ -736,7 +774,7 @@ impl Resynthesis { self.overlap[1..written + 1].fill(Q14::ZERO); } self.overlap_index = 0; - self.previous_output = [Q14::ZERO; 2]; + self.previous_output = [Q14::ZERO; SYNTHESIS_BANKS]; for filter in &mut self.post { filter.reset(); } @@ -1279,7 +1317,9 @@ impl Resynthesis { } } let bounds = self.reader_bounds(period, 0); - for slot in 0..5 { + let mut values = [Q14::ZERO; SYNTHESIS_BANKS]; + let mut formant_positions = [0_i32; SYNTHESIS_BANKS]; + for slot in 0..SYNTHESIS_BANKS { let mut current: Q14 = if slot == 0 { ratio } else { @@ -1292,46 +1332,49 @@ impl Resynthesis { final_ratio = current; self.voice_ratios[slot] = current; let position = self.step_reader(slot, current, bounds, false); - // If the Q12 gain or the stereo pan is zero, the voice adds - // zero to the mix. - if slot > 0 { - let voice = slot - 1; - let pan = self.harmony_pan[voice]; - let silent_pan = - self.config.stereo_output && (pan[0].to_bits() | pan[1].to_bits()) == 0; - if self.harmony_gains[voice] == Q12::ZERO || silent_pan { + // If formants are disabled and the mix gain of the slot is + // zero, the slot adds zero to the mix. + if !self.config.formant.enabled { + let silent = if slot == 0 { + self.lead_gain == Q14::ZERO + } else { + let voice = slot - 1; + let pan = self.harmony_pan[voice]; + self.harmony_gains[voice] == Q12::ZERO + || (pan[0].to_bits() | pan[1].to_bits()) == 0 + }; + if silent { continue; } } - let (mut value, _) = history::interpolation(&self.filtered, position); - if slot > 0 { - value = value.mul(self.harmony_gains[slot - 1]); - if !self.config.stereo_output { - value = value.mul(self.harmony_gain); - } - } - for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output && slot > 0 { - value.mul(self.harmony_pan[slot - 1][channel]) - } else { - value - }; - } + let (value, center) = history::interpolation(&self.filtered, position); + values[slot] = value; + formant_positions[slot] = center - FORMANT_OFFSET_FRAMES; } if self.config.formant.enabled { - self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; - mix = self - .formant - .forward_stereo(mix.map(Q14::to_bits), self.formant_position, numeric) - .map(Q14::from_bits); - for (channel, value) in mix.iter_mut().enumerate() { - *value = - Q14::from_bits(self.formant.model_glottal( - value.to_bits(), - self.previous_output[channel].to_bits(), - )); - self.previous_output[channel] = *value; + self.formant_position = formant_positions[0]; + let synthesized = self.formant.forward_voices( + values.map(Q14::to_bits), + formant_positions, + numeric, + ); + for (slot, sample) in synthesized.into_iter().enumerate() { + let output = Q14::from_bits( + self.formant + .model_glottal(sample, self.previous_output[slot].to_bits()), + ); + self.previous_output[slot] = output; + values[slot] = output; + } + } + let lead = values[0].mul(self.lead_gain); + for sum in &mut mix { + *sum = *sum + lead; + } + for voice in 0..HARMONY_VOICES { + let value: Q14 = values[voice + 1].mul(self.harmony_gains[voice]); + for (channel, sum) in mix.iter_mut().enumerate() { + *sum = *sum + value.mul(self.harmony_pan[voice][channel]); } } } diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..79f5985 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,7 +19,9 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - Optional fields (`resynthesis.leadGain`, `resynthesis.harmony.voices`, +//! `voiceGains`, `voicePans`, `voiceMutes`, `voiceFormantStretch` and +//! `voiceFormantWidth`) use their defaults if they are absent. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use