From 4b1b05b86b6cfbf21c9e20f6aaea89d97e6f9085 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:55:20 +0000 Subject: [PATCH 1/2] feat(harmony): add per-voice mix controls and formant banks - Add lead_gain to ResynthesisConfig with validation. - Add per-voice gain, pan, mute and formant controls to HarmonyConfig. - Preallocate five forward synthesis banks and histories in Formant. - Run per-voice formant synthesis and glottal de-emphasis in Harmony. - Scale the harmony voices by harmony_gain in mono and stereo modes. - Accept absent mix and formant fields in the Wasm configuration. - Document the new controls in the rustdoc and README.md. --- README.md | 17 ++- src/formant.rs | 293 +++++++++++++++++++++++++++------------------ src/harmony.rs | 110 ++++++++++++++++- src/resynthesis.rs | 152 +++++++++++++++-------- src/wasm.rs | 4 +- 5 files changed, 397 insertions(+), 179 deletions(-) diff --git a/README.md b/README.md index d2993dc..e913164 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,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.lead_gain` (`0..=1`, default `1`) and `resynthesis.harmony_gain` +(`0..=1`, default `0.5`) scale the lead voice and the harmony voices in mono +and stereo modes. On `resynthesis.harmony`, `voice_gains` (`0..=1`), +`voice_pans` (`-1..=1`) and `voice_mutes` control each of the four harmony +voices. When `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 To prepare a processor, do these steps: @@ -444,10 +452,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 5072ee1..a965e6e 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::{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. /// @@ -145,7 +149,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 @@ -163,12 +167,12 @@ pub(crate) struct Formant { /// 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]>, - /// 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. @@ -182,10 +186,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 @@ -202,20 +206,20 @@ pub(crate) struct Formant { smooth_reset: 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], @@ -242,7 +246,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 { @@ -251,14 +260,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; MAX_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: BANKS - 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], @@ -266,11 +275,11 @@ impl Formant { smooth_filled: 0, smooth_reset: true, 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(), @@ -278,28 +287,27 @@ impl Formant { noise_amplitude: 0_i32, generation: 0, }; - result.set_config(config); + result.set_config(config, voice_width, voice_stretch); result.reset(); 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) @@ -308,6 +316,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 in 0..count - 1 { + let fraction = i as f64 / (count - 1) as f64; + self.stretch_map[bank][i] = ((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 slot in 1..SYNTHESIS_BANKS { + self.history[slot].fill(0_i32); + } + } /// Clears the audio, the stamps, the synthesis history and the history of /// the aspiration filter. /// @@ -318,7 +345,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(); @@ -385,8 +412,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. @@ -578,39 +607,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][..ORDER]); + self.orders[bank][self.current] = ORDER; } - } else { - self.models[self.current][..ORDER] - .copy_from_slice(&self.inverse[self.current][..ORDER]); - self.orders[self.current] = ORDER; } } else { self.smooth_reset = true; @@ -683,17 +723,17 @@ 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 { + fn coefficients(&self, bank: usize, position: i32, output: &mut [i32; MAX_ORDER]) -> usize { let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; - let mut order = self.orders[stamp.current]; - if stamp.blend < 16384 && self.orders[stamp.previous] != 0 { - order = order.max(self.orders[stamp.previous]); + let mut order = self.orders[bank][stamp.current]; + if stamp.blend < 16384 && self.orders[bank][stamp.previous] != 0 { + order = order.max(self.orders[bank][stamp.previous]); for (i, value) in output[..order].iter_mut().enumerate() { - *value = mul14(16384 - stamp.blend, self.models[stamp.previous][i]) - .wrapping_add(mul14(stamp.blend, self.models[stamp.current][i])); + *value = mul14(16384 - stamp.blend, self.models[stamp.previous][bank][i]) + .wrapping_add(mul14(stamp.blend, self.models[stamp.current][bank][i])); } } else { - output[..order].copy_from_slice(&self.models[stamp.current][..order]); + output[..order].copy_from_slice(&self.models[stamp.current][bank][..order]); } order } @@ -737,7 +777,7 @@ impl Formant { output: &mut [f32], ) -> bool { let mut synthesis = [0; MAX_ORDER]; - let order = self.coefficients(position, &mut synthesis); + let order = self.coefficients(0, position, &mut synthesis); if order == 0 { input.fill(0.0); output.fill(0.0); @@ -754,7 +794,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); @@ -778,10 +818,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, @@ -791,7 +831,7 @@ impl Formant { ) -> i32 { let sample = self.add_noise(sample, context); let mut coefficients = [0; MAX_ORDER]; - let order = self.coefficients(position, &mut coefficients); + let order = self.coefficients(0, position, &mut coefficients); let mut sum = 0_i32; let mut cursor = self.history_index; for &coefficient in &coefficients[..order] { @@ -808,42 +848,57 @@ impl Formant { if self.history_index == MAX_ORDER { self.history_index = 0; } - round_q14(sample.wrapping_mul(self.width)) + round_q14(sample.wrapping_mul(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] { - let mid = samples[0].wrapping_add(samples[1]).wrapping_shr(1); - let noise = self.add_noise(mid, context).wrapping_sub(mid); - for sample in &mut samples { - *sample = sample.wrapping_add(noise); - } + ) -> [i32; SYNTHESIS_BANKS] { + let shaped_noise = if self.config.aspiration_mix <= 0.01 { + None + } else { + 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 mut coefficients = [0; MAX_ORDER]; - let order = self.coefficients(position, &mut coefficients); - for (channel, sample) in samples.iter_mut().enumerate() { + for (bank, sample) in samples.iter_mut().enumerate() { + if let Some(shaped) = shaped_noise { + let noise = mul14(shaped, *sample).wrapping_shl(6); + *sample = mul14(*sample, 16384_i32.wrapping_sub(self.noise_gain)) + .wrapping_add(mul14(noise, self.noise_gain)); + } + let order = self.coefficients(bank, positions[bank], &mut coefficients); let mut sum = 0_i32; - for (i, &coefficient) in coefficients[..order].iter().enumerate() { - sum = sum.wrapping_add( - self.history[channel][(self.history_index + MAX_ORDER - i - 1) % MAX_ORDER] - .wrapping_mul(coefficient), - ); + let mut cursor = self.history_index; + for &coefficient in &coefficients[..order] { + cursor = if cursor == 0 { + MAX_ORDER - 1 + } else { + cursor - 1 + }; + sum = sum.wrapping_add(self.history[bank][cursor].wrapping_mul(coefficient)); } *sample = sample.wrapping_add(round_q14(sum)); - self.history[channel][self.history_index] = *sample; - *sample = round_q14(sample.wrapping_mul(self.width)); + self.history[bank][self.history_index] = *sample; + *sample = round_q14(sample.wrapping_mul(self.width[bank])); + } + self.history_index += 1; + if self.history_index == MAX_ORDER { + self.history_index = 0; } - self.history_index = (self.history_index + 1) % MAX_ORDER; samples } } diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..9c87e15 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 34e98fa..5b4a246 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 pan gain of the harmony voices, 0..=1. The default is 0.5. + /// The linear gain of the lead voice in [`MultiVoiceMode::Harmony`], + /// 0..=1. The default is 1. /// - /// The code applies this gain only if `stereo_output` is `true`. The - /// harmony path without pan does not use this control. It does not scale - /// the lead voice. + /// 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 harmony voices, 0..=1. The default is 0.5. + /// + /// 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,9 +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], - /// 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 @@ -479,9 +501,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 { @@ -501,7 +523,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 @@ -527,6 +554,7 @@ impl Resynthesis { drift_ratio: [Q14::ONE; 16], pan: [[Q14::ONE; 2]; 16], 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], @@ -547,7 +575,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(); @@ -556,14 +584,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 harmony level is part of the stereo pan gains. Thus, the path - /// without pan never applies that control. 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 { @@ -588,16 +615,23 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } - 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]; + } + } } } @@ -642,8 +676,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 { @@ -703,7 +745,7 @@ impl Resynthesis { self.ratios.fill(Q14::ONE); self.overlap.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(); } @@ -1220,7 +1262,9 @@ impl Resynthesis { self.harmony_gains[voice] = gain; } } - 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 { @@ -1233,32 +1277,34 @@ impl Resynthesis { final_ratio = current; self.voice_ratios[slot] = current; let position = self.move_reader(slot, current, period, 0, false); - let (mut value, _) = history::interpolation(&self.filtered, position); - if slot > 0 { - value = value.mul(self.harmony_gains[slot - 1]); - } - 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 c9cec08..e496792 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 From fc7d1d9a18e2293b48b7ed8b8f2e3a911503e3e7 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:43:42 +0000 Subject: [PATCH 2/2] style(formant): fix Clippy range loops for Rust 1.100 - Iterate the stretch map with enumerate in Formant::prepare_bank - Iterate the harmony histories as a slice in clear_harmony_history - Keep the audio output identical across all stages --- src/formant.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/formant.rs b/src/formant.rs index 9051998..b5de9d2 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -344,16 +344,16 @@ impl Formant { 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 in 0..count - 1 { + for (i, entry) in self.stretch_map[bank][..count - 1].iter_mut().enumerate() { let fraction = i as f64 / (count - 1) as f64; - self.stretch_map[bank][i] = ((ORDER - 1) as f64 * fraction * 128.0) as i32; + *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 slot in 1..SYNTHESIS_BANKS { - self.history[slot].fill(0_i32); + for history in &mut self.history[1..] { + history.fill(0_i32); } } /// Clears the audio, the stamps, the synthesis history and the history of