From a585e2bbd4a0c42f90bb4024b2e4bcdca3ccfed2 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:39:55 +0000 Subject: [PATCH 1/4] feat: add per-voice channel strips and formant banks - Add lead_gain to ResynthesisConfig with 0..=1 range validation - Add per-voice mix and formant controls to HarmonyConfig - Preallocate five forward synthesis banks and histories in Formant - Convert LPC tract areas into five forward models at each design step - Run stamped per-voice LPC synthesis before the Harmony stereo pan sum - Read at most one aspiration random word per frame in Harmony mode - Expose optional camelCase TypeScript fields with serde defaults - Document the new Harmony controls and optional fields in README.md --- README.md | 26 ++- src/formant.rs | 344 +++++++++++++++++++++++-------------- src/harmony.rs | 115 ++++++++++++- src/resynthesis.rs | 199 ++++++++++++++------- src/resynthesis/history.rs | 30 ++-- src/wasm.rs | 7 +- 6 files changed, 503 insertions(+), 218 deletions(-) diff --git a/README.md b/README.md index 83a8f47..86e91fb 100644 --- a/README.md +++ b/README.md @@ -198,8 +198,15 @@ 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 +`Harmony` mode. `resynthesis.harmony_gain` (`0..=1`, default `0.5`) sets the +master gain of the four harmony voices in mono and in stereo. In +`resynthesis.harmony`, `voice_gains` (`0..=1`), `voice_pans` (`-1..=1`, when +`stereo_output` is `true`) and `voice_mutes` control the mix of each harmony +voice. When `resynthesis.formant.enabled` is `true`, `voice_formant_stretch` +and `voice_formant_width` (`0.5..=2`, default `[1, 1, 1, 1]`) shape an +independent LPC synthesis filter for each harmony voice before the stereo pan +sum. ## Process audio @@ -451,10 +458,17 @@ 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`. These optional fields use defaults if they are absent: + +- `resynthesis.leadGain` defaults to `1`. +- `resynthesis.harmony.voices` defaults to `4`. +- `resynthesis.harmony.voiceGains`, `voiceFormantStretch` and + `voiceFormantWidth` default to `[1, 1, 1, 1]`. +- `resynthesis.harmony.voicePans` defaults to `[-1/3, 1/3, -1, 1]`. +- `resynthesis.harmony.voiceMutes` defaults to `[false, false, false, false]`. + +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..86955f6 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -5,21 +5,24 @@ //! 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 -//! is not 1, the code changes the reflection coefficients into tract areas. -//! Then it changes these areas into a synthesis model. +//! smoothed. Then they become reflection coefficients. For each voice bank +//! whose width or stretch is not 1, the code changes the reflection +//! coefficients into tract areas. Then it changes these areas into a +//! synthesis model for that voice. //! -//! 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 -//! operations changes the output samples. +//! Thirty model banks keep the history of the coefficients for the lead voice +//! and for the four harmony voices. 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 operations changes the +//! output samples. 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 +122,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 slots: the lead voice and the four harmony +/// voices. +const VOICE_BANKS: usize = HARMONY_VOICES + 1; /// The model selection for one frame of input history. /// @@ -147,7 +153,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 voices. #[derive(Debug)] pub(crate) struct Formant { /// The validated formant controls. The resynthesis caller decides if this @@ -164,12 +170,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 voices. + /// `orders` holds the active lengths. + models: Vec<[[i32; MAX_ORDER]; BANKS]>, + /// The valid synthesis order for each voice slot and bank. Zero means + /// that there is no feedback model. + orders: [[usize; BANKS]; VOICE_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,12 +189,13 @@ 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 - /// slot. - history_index: usize, + /// The separate Q14 feedback histories of the synthesis, for the lead + /// voice and the four harmony voices. + history: [[i32; MAX_ORDER]; VOICE_BANKS], + /// The next slot in the synthesis history of each voice. + history_index: [usize; VOICE_BANKS], + /// Marks each voice history that holds nonzero synthesis feedback. + history_dirty: [bool; VOICE_BANKS], /// The two previous normalized autocorrelation vectors for the moving /// average. correlation_history: [[i32; 111]; 2], @@ -205,20 +212,21 @@ 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 of each voice. The stage also uses it as the + /// output gain of that forward filter. + width: [i32; VOICE_BANKS], + /// The Q14 square of the width of each voice, for the scale of the tract + /// areas. + width_squared: [i32; VOICE_BANKS], + /// The Q14 stretch control of each voice. The stage uses it to decide if + /// a change to the areas is necessary. + stretch: [i32; VOICE_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; VOICE_BANKS], + /// The Q7 positions that map the stretched sections of each voice into + /// the area model with 50 sections. + stretch_map: [[i32; MAX_ORDER]; VOICE_BANKS], /// The original tract areas, with the runtime scale that the LPC /// conversion returns. areas: [i32; MAX_ORDER], @@ -263,7 +271,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,15 +285,16 @@ 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]; BANKS]; VOICE_BANKS], + orders: [[0; BANKS]; VOICE_BANKS], stamps: vec![Stamp::default(); HISTORY_FRAMES], current: 1, previous: 0, blend: 0, design_counter: 0, - history: [[0; MAX_ORDER]; 2], - history_index: 0, + history: [[0; MAX_ORDER]; VOICE_BANKS], + history_index: [0; VOICE_BANKS], + history_dirty: [false; VOICE_BANKS], correlation_history: [[0; 111]; 2], correlation_sum: [0; 111], smooth_index: 0, @@ -288,11 +302,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; VOICE_BANKS], + width_squared: [16384; VOICE_BANKS], + stretch: [16384; VOICE_BANKS], + stretch_count: [ORDER; VOICE_BANKS], + stretch_map: [[0; MAX_ORDER]; VOICE_BANKS], areas: [0; MAX_ORDER], stretched_areas: [0; MAX_ORDER], noise_filter: Biquad::new(), @@ -300,27 +314,44 @@ 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 width and the stretch for one synthesis voice slot and + /// builds its Q7 area map. + fn configure_voice_tract(&mut self, slot: usize, width: f64, stretch: f64) { + self.width[slot] = (width * 16384.0) as i32; + self.width_squared[slot] = (width * width * 16384.0) as i32; + self.stretch[slot] = (stretch * 16384.0) as i32; + let count = (((ORDER - 1) as f64 * stretch + 1.001) as usize).min(MAX_ORDER); + self.stretch_count[slot] = count; + for (i, entry) in self.stretch_map[slot][..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[slot][count - 1] = ((ORDER - 1) * 128) as i32; + } + /// 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; + let lead_width = f64::from(config.width); + let lead_stretch = f64::from(config.stretch); + self.configure_voice_tract(0, lead_width, lead_stretch); + for voice in 0..HARMONY_VOICES { + let width = (lead_width * f64::from(voice_width[voice])).clamp(0.5, 2.0); + let stretch = (lead_stretch * f64::from(voice_stretch[voice])).clamp(0.5, 2.0); + self.configure_voice_tract(voice + 1, width, stretch); } - 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,8 +360,8 @@ impl Formant { self.noise_filter .set_design(Design::high_pass(self.rate.hz(), frequency as f32, 0.707)); } - /// Clears the audio, the stamps, the synthesis history and the history of - /// the aspiration filter. + /// Clears the audio, the stamps, the synthesis histories and the history + /// of 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 @@ -343,8 +374,9 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER]; 2]; - self.history_index = 0; + self.history = [[0; MAX_ORDER]; VOICE_BANKS]; + self.history_index = [0; VOICE_BANKS]; + self.history_dirty = [false; VOICE_BANKS]; self.current = BANKS - 1; self.next_filter(); self.next_filter(); @@ -410,9 +442,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 slot in 0..VOICE_BANKS { + self.models[slot][self.current].fill(0_i32); + self.orders[slot][self.current] = 0; + } } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. @@ -615,38 +648,60 @@ 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 needs_areas = (0..VOICE_BANKS) + .any(|slot| self.width[slot] != one || self.stretch[slot] != one); + let area_scale = if needs_areas { + lpc::parcor_to_areas(&parcor[..ORDER], &mut self.areas) + } else { + None + }; + let mut voice_parcor = [0; MAX_ORDER]; + for slot in 0..VOICE_BANKS { + if self.width[slot] == one && self.stretch[slot] == one { + self.models[slot][self.current][..ORDER] + .copy_from_slice(&self.inverse[self.current]); + self.orders[slot][self.current] = ORDER; + } else if let Some(prev) = (0..slot).find(|&prev| { + let count = self.stretch_count[slot]; + self.width_squared[prev] == self.width_squared[slot] + && self.stretch[prev] == self.stretch[slot] + && self.stretch_count[prev] == count + && self.stretch_map[prev][..count] == self.stretch_map[slot][..count] + }) { + let order = self.orders[prev][self.current]; + let (head, tail) = self.models.split_at_mut(slot); + tail[0][self.current][..order] + .copy_from_slice(&head[prev][self.current][..order]); + self.orders[slot][self.current] = order; + } else if let Some(scale) = area_scale { + let count = self.stretch_count[slot]; + for i in 0..count { + let map = self.stretch_map[slot][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, + self.width_squared[slot], ); if self.stretched_areas[i] == 0_i32 { self.stretched_areas[i] = 1; } } if lpc::areas_to_parcor( - &self.stretched_areas[..self.stretch_count], - &mut parcor, + &self.stretched_areas[..count], + &mut voice_parcor, scale, ) { lpc::parcor_to_pef( - &parcor[..self.stretch_count], - &mut self.models[self.current], + &voice_parcor[..count], + &mut self.models[slot][self.current], &mut scratch, 14, ); - self.orders[self.current] = self.stretch_count; + self.orders[slot][self.current] = count; } } - } 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 +763,42 @@ 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 `slot` at the stamp of 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, slot: 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[slot][previous] != 0 { None } else { - Some(&self.models[current][..self.orders[current]]) + Some(&self.models[slot][current][..self.orders[slot][current]]) } } - /// Blends the two synthesis banks at a signed history frame into `output`. + /// Blends the two synthesis banks of `slot` 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, + slot: 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[slot][current].max(self.orders[slot][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[slot][previous][i]) + .saturating_add(mul14(blend, self.models[slot][current][i])); } &output[..order] } @@ -783,11 +845,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 +867,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); @@ -841,63 +903,79 @@ impl Formant { context: &mut NumericContext, ) -> i32 { self.dirty = true; + self.history_dirty[0] = 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 index = self.history_index[0]; + let sum = ring_sum(&self.history[0], index, coefficients); 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 { - self.history_index = 0; - } - round_q14(i64::from(sample) * i64::from(self.width)) + self.history[0][index] = sample; + self.history_index[0] = if index + 1 == MAX_ORDER { 0 } else { index + 1 }; + 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. + /// Reads at most one random value for the current Harmony frame and + /// advances the aspiration filter one time. /// - /// 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 the aspiration level is 0.01 or less, the function returns `None`. + /// Then the random stream and the noise filter do not advance. + pub(crate) fn prepare_noise(&mut self, context: &mut NumericContext) -> Option { + if self.config.aspiration_mix <= 0.01 { + return None; + } + self.dirty = true; + let random = (context.random.next_u31() >> 17) - 8192; + Some( + self.noise_filter + .process_sample(Q14::from_bits(random)) + .to_bits(), + ) + } + /// Clears the synthesis feedback history of a voice that enters silence or + /// mute. + pub(crate) fn bypass_voice(&mut self, slot: usize) { + if self.history_dirty[slot] { + self.history[slot].fill(0_i32); + self.history_index[slot] = 0; + self.history_dirty[slot] = false; + } + } + /// Synthesizes one Harmony voice slot with its stamped model, its own + /// feedback history and the shared aspiration sample of the frame. + pub(crate) fn forward_voice( &mut self, - mut samples: [i32; 2], + slot: usize, + sample: i32, position: i32, - context: &mut NumericContext, - ) -> [i32; 2] { + frame_noise: Option, + ) -> i32 { 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); - } + self.history_dirty[slot] = true; + let sample = if let Some(filtered_random) = frame_noise { + let modulated = mul14(filtered_random, sample); + let noise = clamp_i32(i64::from(mul14(self.noise_amplitude, modulated)) << 6); + mul14(sample, 16384_i32.saturating_sub(self.noise_gain)) + .saturating_add(mul14(noise, self.noise_gain)) + } else { + sample + }; let mut blended; - let coefficients = if let Some(slice) = self.coefficients(position) { + let coefficients = if let Some(slice) = self.coefficients(slot, position) { slice } else { blended = [0; MAX_ORDER]; - self.blend_coefficients(position, &mut blended) + self.blend_coefficients(slot, position, &mut blended) }; - 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)); - } - self.history_index += 1; - if self.history_index == MAX_ORDER { - self.history_index = 0; - } - samples + let index = self.history_index[slot]; + let sum = ring_sum(&self.history[slot], index, coefficients); + let sample = sample.saturating_add(round_q14(sum)); + self.history[slot][index] = sample; + self.history_index[slot] = if index + 1 == MAX_ORDER { 0 } else { index + 1 }; + round_q14(i64::from(sample) * i64::from(self.width[slot])) } } diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..4abe641 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -240,6 +240,9 @@ pub enum Inversion { /// - A register of 50%. /// - A closed voicing and zero portamento. /// - Four voices for the interval sources. +/// - Unity voice gains and no voice mutes. +/// - Stereo voice pans of -1/3, 1/3, -1 and 1. +/// - Unity voice formant stretch and width. /// /// These settings configure all sources. Only the fields for the selected /// source change the target notes. Validation always checks all fields. @@ -328,14 +331,94 @@ pub struct HarmonyConfig { tsify(optional) )] pub voices: u8, + /// Four linear gains for the harmony voices, each in 0..=1. The default + /// is `[1.0; 4]`. + /// + /// Each value multiplies [`crate::ResynthesisConfig::harmony_gain`] and + /// the envelope of that voice. A value of zero mutes 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_unity"), + 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. The + /// default is `[-1.0 / 3.0, 1.0 / 3.0, -1.0, 1.0]`. + /// + /// A value of -1 sends the voice to the left channel. A value of 0 + /// centers the voice, and 1 sends it to the right channel. This control + /// applies 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 mutes for the harmony voices. The default is `[false; 4]`. + /// + /// If an entry is `true`, that voice outputs zero amplitude immediately. + /// 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.0; 4]`. + /// + /// Each value multiplies [`crate::FormantConfig::stretch`] for that + /// voice, and the stage clamps the product to 0.5..=2. This control + /// applies only if [`crate::FormantConfig::enabled`] 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_unity"), + 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.0; 4]`. + /// + /// Each value multiplies [`crate::FormantConfig::width`] for that voice, + /// and the stage clamps the product to 0.5..=2. This control applies only + /// if [`crate::FormantConfig::enabled`] 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_unity"), + tsify(optional, type = "[number, number, number, number]") + )] + pub voice_formant_width: [f32; HARMONY_VOICES], } +/// The default stereo pan positions 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 multipliers for the four harmony voices. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_voice_unity() -> [f32; HARMONY_VOICES] { + [1.0; HARMONY_VOICES] +} + +/// The default stereo pan positions for JavaScript deserialization. +#[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 +434,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 +477,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 +642,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..0cfcae9 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 +//! active voice before the stereo 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 @@ -223,11 +223,26 @@ 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 four harmony voices, 0..=1. The default is 0.5. + /// The linear gain of the lead voice in Harmony mode, 0..=1. The default + /// is 1. /// - /// 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. + /// A value of zero mutes the lead voice so only the harmony voices sound. + /// Choir does not use this value. 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 master linear gain of the four harmony voices, 0..=1. The default + /// is 0.5. + /// + /// Each harmony voice multiplies this value by its entry in + /// [`HarmonyConfig::voice_gains`]. If `stereo_output` is `true`, the + /// stereo pan gains include this product. If `stereo_output` is `false`, + /// this product scales each harmony voice directly. It does not scale the + /// lead voice. pub harmony_gain: f32, /// The modulation depth, 0..=24, without a unit. The default is 0 (off). /// @@ -253,6 +268,12 @@ pub struct ResynthesisConfig { pub random_seed: u64, } +/// 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 +} + impl Default for ResynthesisConfig { fn default() -> Self { Self { @@ -267,6 +288,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 +320,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)?; @@ -419,10 +442,12 @@ 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 linear gain of the lead voice in Harmony mode. + lead_gain: Q14, + /// If stereo pan is off, the Q14 linear gain of each harmony voice. + harmony_voice_gain: [Q14; HARMONY_VOICES], + /// The Q14 pan gains of the harmony voices. They include the master + /// harmony gain, the voice gain and the mute. harmony_pan: [[Q14; 2]; HARMONY_VOICES], /// The last Q14 target ratios from the harmony controller. harmony_ratios: [Q14; HARMONY_VOICES], @@ -483,9 +508,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 slot. The glottal /// envelope uses it. - previous_output: [Q14; 2], + previous_output: [Q14; HARMONY_VOICES + 1], } impl Resynthesis { @@ -505,7 +530,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,7 +560,8 @@ impl Resynthesis { drift: [Q14::ZERO; 16], drift_ratio: [Q14::ONE; 16], pan: [[Q14::ONE; 2]; 16], - harmony_gain: Q14::ZERO, + lead_gain: Q14::ONE, + harmony_voice_gain: [Q14::ZERO; HARMONY_VOICES], harmony_pan: [[Q14::ZERO; 2]; HARMONY_VOICES], harmony_ratios: [Q14::ONE; HARMONY_VOICES], harmony_gains: [Q12::ZERO; HARMONY_VOICES], @@ -553,7 +584,7 @@ impl Resynthesis { control_counter: CONTROL_DUE, drift_decay: Q14::ZERO, drift_amount: Q14::ZERO, - previous_output: [Q14::ZERO; 2], + previous_output: [Q14::ZERO; HARMONY_VOICES + 1], }; result.configure_coefficients(); result.configure_shift_filters(); @@ -595,17 +626,22 @@ 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()), - ]; + self.lead_gain = Q14::from_f64(f64::from(self.config.lead_gain)); + for voice in 0..HARMONY_VOICES { + if self.config.harmony.voice_mutes[voice] { + self.harmony_voice_gain[voice] = Q14::ZERO; + self.harmony_pan[voice] = [Q14::ZERO; 2]; + } else { + let gain = f64::from(self.config.harmony_gain) + * f64::from(self.config.harmony.voice_gains[voice]); + self.harmony_voice_gain[voice] = Q14::from_f64(gain); + 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()), + ]; + } } } @@ -649,8 +685,19 @@ impl Resynthesis { pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; self.config = config; - self.pitch.set_config(config.pitch); - self.formant.set_config(config.formant); + if old.pitch != config.pitch { + self.pitch.set_config(config.pitch); + } + if old.formant != config.formant + || old.harmony.voice_formant_width != config.harmony.voice_formant_width + || old.harmony.voice_formant_stretch != config.harmony.voice_formant_stretch + { + self.formant.set_config( + config.formant, + config.harmony.voice_formant_width, + config.harmony.voice_formant_stretch, + ); + } self.harmony.apply_config(config.harmony); if old.correction.notes != config.correction.notes || old.correction.enabled != config.correction.enabled @@ -736,7 +783,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; HARMONY_VOICES + 1]; for filter in &mut self.post { filter.reset(); } @@ -1278,6 +1325,11 @@ impl Resynthesis { self.harmony_gains[voice] = gain; } } + let frame_noise = if self.config.formant.enabled { + self.formant.prepare_noise(numeric) + } else { + None + }; let bounds = self.reader_bounds(period, 0); for slot in 0..5 { let mut current: Q14 = if slot == 0 { @@ -1292,46 +1344,63 @@ 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 { - continue; - } + if slot == 0 && self.config.formant.enabled { + self.formant_position = history::center_of(position) - FORMANT_OFFSET_FRAMES; } - 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); + // If the voice gain, the mute or the stereo pan gives zero + // output, skip interpolation and synthesis for that voice. + let silent = if slot == 0 { + self.lead_gain == Q14::ZERO + } else { + let voice = slot - 1; + let silent_level = if self.config.stereo_output { + let pan = self.harmony_pan[voice]; + (pan[0].to_bits() | pan[1].to_bits()) == 0 + } else { + self.harmony_voice_gain[voice] == Q14::ZERO + }; + self.harmony_gains[voice] == Q12::ZERO || silent_level + }; + if silent { + if self.config.formant.enabled { + self.formant.bypass_voice(slot); } + self.previous_output[slot] = Q14::ZERO; + continue; } - 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 (mut value, center) = history::interpolation(&self.filtered, position); + if self.config.formant.enabled { + let formant_position = center - FORMANT_OFFSET_FRAMES; + value = Q14::from_bits(self.formant.forward_voice( + slot, + value.to_bits(), + formant_position, + frame_noise, + )); + value = Q14::from_bits( + self.formant + .model_glottal(value.to_bits(), self.previous_output[slot].to_bits()), + ); + self.previous_output[slot] = value; } - } - 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; + if slot == 0 { + value = value.mul(self.lead_gain); + for sum in &mut mix { + *sum = *sum + value; + } + } else { + let voice = slot - 1; + value = value.mul(self.harmony_gains[voice]); + if self.config.stereo_output { + for (channel, sum) in mix.iter_mut().enumerate() { + *sum = *sum + value.mul(self.harmony_pan[voice][channel]); + } + } else { + value = value.mul(self.harmony_voice_gain[voice]); + for sum in &mut mix { + *sum = *sum + value; + } + } } } } diff --git a/src/resynthesis/history.rs b/src/resynthesis/history.rs index f355efc..5779041 100644 --- a/src/resynthesis/history.rs +++ b/src/resynthesis/history.rs @@ -44,24 +44,32 @@ fn interpolation_taps(buffer: &[T; HISTORY], center: i32) -> [T; 3] { } } +/// Returns the integer center frame for a Q14 reader position without wrap. +/// +/// The function adds a half frame to a positive position. For other +/// positions, it subtracts a half frame, then truncates toward zero. +#[inline] +pub(super) fn center_of(position: Q14) -> i32 { + let bits = position.to_bits(); + if position > Q14::ZERO { + bits.wrapping_add(8192) >> 14 + } else { + -(8192_i32.wrapping_sub(bits) >> 14) + } +} + /// Returns the value of a three-point parabola at a Q14 frame position. /// /// The result has two parts: the Q14 sample and the integer center frame /// without wrap. The formant model uses this center for alignment. To find -/// the center, the function adds a half frame to a positive position. For -/// other positions, it subtracts a half frame. +/// the center, [`center_of`] rounds to the nearest integer frame. /// -/// Then it truncates the result toward zero. The fraction that is left is -/// 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`. +/// The fraction that is left is 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) { let bits = position.to_bits(); - let center = if position > Q14::ZERO { - bits.wrapping_add(8192) >> 14 - } else { - -(8192_i32.wrapping_sub(bits) >> 14) - }; + let center = center_of(position); let fraction = Q14::from_bits(bits.wrapping_sub(center.wrapping_shl(14))); let [left, middle, right] = interpolation_taps(buffer, center); let left_i64 = i64::from(left.to_bits()); diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..0cdaef6 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,7 +19,12 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - Optional `resynthesis.leadGain` defaults to 1. +//! - Optional harmony `voices` defaults to 4. +//! - Optional harmony `voiceGains`, `voiceFormantStretch` and +//! `voiceFormantWidth` default to `[1, 1, 1, 1]`. +//! - Optional harmony `voicePans` defaults to `[-1/3, 1/3, -1, 1]`. +//! - Optional harmony `voiceMutes` defaults to `[false, false, false, false]`. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use From b696c4ad96bf423d8701bde074c7f911d52199a3 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:09:02 +0000 Subject: [PATCH 2/4] fix(resynthesis)!: clear harmony formant state on mode change - Clear previous_output[1..] when ResynthesisConfig::mode changes - Call Formant::bypass_voice for slots 1..5 on mode changes BREAKING CHANGE: default Harmony pan and formant paths change samples. --- src/resynthesis.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/resynthesis.rs b/src/resynthesis.rs index fe4903e..a0df155 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -699,6 +699,12 @@ impl Resynthesis { if old.mode != config.mode || old.choir_delay != config.choir_delay { self.create_delays(); } + if old.mode != config.mode { + self.previous_output[1..].fill(Q14::ZERO); + for slot in 1..5 { + self.formant.bypass_voice(slot); + } + } if old.choir_voices < config.choir_voices { for voice in old.choir_voices as usize..config.choir_voices as usize { self.positions[voice] = self.positions[0]; From 76b37f313cc6693fe9278f4b3c573a32d35d003c Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:09:02 +0000 Subject: [PATCH 3/4] docs(processor): clarify Telemetry::voice_gains envelope scope - State that harmony gains report controller envelopes before mix gains - List lead_gain, harmony_gain, voice_gains, voice_mutes and stereo pan --- src/processor.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/processor.rs b/src/processor.rs index ea56dec..71a3f58 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -864,11 +864,14 @@ pub struct Telemetry { /// [`voice_ratios`](Self::voice_ratios). /// /// The lead and the choir voices have a gain of 1. The gain of a harmony - /// voice includes the MIDI velocity gain, in 0..=3.98095703125. MIDI - /// velocity 127 gives the maximum, approximately +12 dB. The gain is zero - /// for a voice that does not sound. It does not include the configured - /// harmony level or the pan. The harmony controller updates it every 101 - /// frames. + /// voice is its controller envelope, in 0..=3.98095703125. This envelope + /// includes the MIDI velocity gain, where velocity 127 gives the maximum, + /// approximately +12 dB. The envelope is zero for an inactive harmony + /// voice. These values are before [`crate::ResynthesisConfig::lead_gain`], + /// [`crate::ResynthesisConfig::harmony_gain`], + /// [`crate::HarmonyConfig::voice_gains`], + /// [`crate::HarmonyConfig::voice_mutes`] and the stereo pan. The harmony + /// controller updates its envelopes every 101 frames. pub voice_gains: [f32; 16], /// The effective linear gain of Punch at the current envelope level. /// From 7c4fe093387c8e6de4c098769f0f56bba06269f2 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:04:45 +0000 Subject: [PATCH 4/4] feat(config): expose per-voice controls in ControlActivity - Add lead_gain and per-voice harmony flags to ControlActivity. - Clarify that formant_envelope reports the lead slot 0 model. - Normalize new ControlActivity JSDoc links and update README. - Check optional per-voice fields and activity in verify-pack. --- README.md | 21 ++-- scripts/normalize-jsdoc.mjs | 10 ++ scripts/verify-pack.mjs | 185 +++++++++++++++++++++++++++++++++++- src/config.rs | 32 +++++-- src/lib.rs | 6 +- src/processor.rs | 18 ++-- src/wasm.rs | 20 ++-- 7 files changed, 256 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 875a395..83aebd6 100644 --- a/README.md +++ b/README.md @@ -371,9 +371,10 @@ These calls read the state of the processor. They do not change the audio. | `formant_envelope()` | The LPC envelopes before and after the formant controls | `Processor::control_activity()` and `ProcessorConfig::control_activity()` -return a `ControlActivity` struct. A `false` flag means that the related -control makes no sample change in the active voice mode, harmony source or -reverb network. +return a `ControlActivity` struct. Its boolean flags cover the conditional +choir controls, `lead_gain`, `harmony_gain`, the `HarmonyConfig` fields and the +`ReverbConfig` fields. A `false` flag means that the related control makes no +sample change in the active voice, stereo, harmony, formant or reverb settings. The telemetry includes these items: @@ -393,11 +394,14 @@ choir delays and effects use different delays. `formant_envelope()` writes two LPC envelopes into slices of equal length: - The vocal-tract envelope from the analysis. -- The envelope after the width and stretch controls. +- The lead (slot 0) synthesis envelope after `formant.width` and + `formant.stretch`. -The values are linear and have no absolute level. The formant stage must be -enabled. The envelopes are those of the model that the audio used for the -last frame. The method returns `Result`: +The output envelope reflects the lead vocal-tract model, not +`voice_formant_width` or `voice_formant_stretch`. The values are linear and +have no absolute level. The formant stage must be enabled. The envelopes are +those of the model that the audio used for the last frame. The method returns +`Result`: | Result | Description | | ----------- | ---------------------------------------------------------------- | @@ -646,7 +650,8 @@ which are also the cases where `voiced` is `false`: `resynthesis.pitch.minFrequencyHz` and `resynthesis.pitch.maxFrequencyHz`. `formantEnvelope(maxFrequencyHz, input, output)` fills two `Float32Array` -buffers of equal length and returns `false` if no envelope is available. +buffers of equal length with the analysis envelope and the lead (slot 0) +synthesis envelope. It returns `false` if no envelope is available. In that case, it fills both buffers with zeros. If the lengths are not equal or the frequency is not valid, it throws and does not change the buffers. The frequency must be finite, more than zero and not more than half of the sample diff --git a/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index bce9b11..2550388 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -49,6 +49,7 @@ const EXACT_REPLACEMENTS = [ "`ResynthesisConfig.choirSpreadPercent`", ], ["[`crate::ResynthesisConfig::lead_gain`]", "`ResynthesisConfig.leadGain`"], + ["[`ResynthesisConfig::lead_gain`]", "`ResynthesisConfig.leadGain`"], [ "[`crate::ResynthesisConfig::harmony_gain`]", "`ResynthesisConfig.harmonyGain`", @@ -87,7 +88,16 @@ const EXACT_REPLACEMENTS = [ ["[`crate::HarmonyConfig::voices`]", "`HarmonyConfig.voices`"], ["[`crate::HarmonyConfig::voice_gains`]", "`HarmonyConfig.voiceGains`"], ["[`HarmonyConfig::voice_gains`]", "`HarmonyConfig.voiceGains`"], + ["[`crate::HarmonyConfig::voice_pans`]", "`HarmonyConfig.voicePans`"], ["[`crate::HarmonyConfig::voice_mutes`]", "`HarmonyConfig.voiceMutes`"], + [ + "[`crate::HarmonyConfig::voice_formant_stretch`]", + "`HarmonyConfig.voiceFormantStretch`", + ], + [ + "[`crate::HarmonyConfig::voice_formant_width`]", + "`HarmonyConfig.voiceFormantWidth`", + ], ["[`ReverbConfig::mode`]", "`ReverbConfig.mode`"], ["[`ReverbConfig::mix`]", "`ReverbConfig.mix`"], ["[`ReverbConfig::diffusion`]", "`ReverbConfig.diffusion`"], diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..12b66a4 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -312,16 +312,39 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.ok(wasmExports);", "assert.ok(wasmExports.memory instanceof WebAssembly.Memory);", "", + "const defaultVoicePans = [Math.fround(-1 / 3), Math.fround(1 / 3), -1, 1];", "const initialConfig = rootModule.defaultConfig();", "initialConfig.resynthesis.correction.humanize = undefined;", "initialConfig.resynthesis.correction.flexTune = undefined;", + "initialConfig.resynthesis.leadGain = undefined;", "initialConfig.resynthesis.harmony.voices = undefined;", + "initialConfig.resynthesis.harmony.voiceGains = undefined;", + "initialConfig.resynthesis.harmony.voicePans = undefined;", + "initialConfig.resynthesis.harmony.voiceMutes = undefined;", + "initialConfig.resynthesis.harmony.voiceFormantStretch = undefined;", + "initialConfig.resynthesis.harmony.voiceFormantWidth = undefined;", "const processor = new rootModule.Tunelet(48000, 128, initialConfig);", "try {", + " const assertDefaultVoiceStrips = (resynthesis) => {", + " assert.equal(resynthesis.leadGain, 1);", + " assert.deepEqual(resynthesis.harmony.voiceGains, [1, 1, 1, 1]);", + " assert.deepEqual(resynthesis.harmony.voicePans, defaultVoicePans);", + " assert.deepEqual(resynthesis.harmony.voiceMutes, [false, false, false, false]);", + " assert.deepEqual(resynthesis.harmony.voiceFormantStretch, [1, 1, 1, 1]);", + " assert.deepEqual(resynthesis.harmony.voiceFormantWidth, [1, 1, 1, 1]);", + " };", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", - " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", + " assertDefaultVoiceStrips(processor.config().resynthesis);", + " const choirActivity = processor.controlActivity();", + " assert.equal(choirActivity.choirVoices, true);", + " assert.equal(choirActivity.leadGain, false);", + " assert.equal(choirActivity.harmonyVoiceGains, false);", + " assert.equal(choirActivity.harmonyVoicePans, false);", + " assert.equal(choirActivity.harmonyVoiceMutes, false);", + " assert.equal(choirActivity.harmonyVoiceFormantStretch, false);", + " assert.equal(choirActivity.harmonyVoiceFormantWidth, false);", " const initialTelemetry = processor.telemetry();", " assert.ok(initialTelemetry.voiceRatios instanceof Float32Array);", " assert.ok(initialTelemetry.voiceGains instanceof Float32Array);", @@ -329,6 +352,74 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(initialTelemetry.voiced, false);", " assert.equal(initialTelemetry.targetMidiNote, undefined);", "", + " const customVoiceConfig = processor.config();", + ' customVoiceConfig.resynthesis.mode = "harmony";', + " customVoiceConfig.resynthesis.leadGain = 0.5;", + " customVoiceConfig.resynthesis.harmony.voiceGains = [0.25, 0.5, 0.75, 1];", + " customVoiceConfig.resynthesis.harmony.voicePans = [-0.5, 0.5, -0.25, 0.25];", + " customVoiceConfig.resynthesis.harmony.voiceMutes = [true, false, true, false];", + " customVoiceConfig.resynthesis.harmony.voiceFormantStretch = [0.75, 1.25, 1.5, 1.75];", + " customVoiceConfig.resynthesis.harmony.voiceFormantWidth = [1.25, 0.75, 1.5, 0.5];", + " processor.setConfig(customVoiceConfig);", + " assert.equal(processor.config().resynthesis.leadGain, 0.5);", + " assert.deepEqual(processor.config().resynthesis.harmony.voiceGains, [0.25, 0.5, 0.75, 1]);", + " assert.deepEqual(processor.config().resynthesis.harmony.voicePans, [-0.5, 0.5, -0.25, 0.25]);", + " assert.deepEqual(processor.config().resynthesis.harmony.voiceMutes, [true, false, true, false]);", + " assert.deepEqual(processor.config().resynthesis.harmony.voiceFormantStretch, [0.75, 1.25, 1.5, 1.75]);", + " assert.deepEqual(processor.config().resynthesis.harmony.voiceFormantWidth, [1.25, 0.75, 1.5, 0.5]);", + " const monoHarmonyActivity = processor.controlActivity();", + " assert.equal(monoHarmonyActivity.leadGain, true);", + " assert.equal(monoHarmonyActivity.harmonyVoiceGains, true);", + " assert.equal(monoHarmonyActivity.harmonyVoicePans, false);", + " assert.equal(monoHarmonyActivity.harmonyVoiceMutes, true);", + " assert.equal(monoHarmonyActivity.harmonyVoiceFormantStretch, false);", + " assert.equal(monoHarmonyActivity.harmonyVoiceFormantWidth, false);", + "", + " const stereoFormantConfig = processor.config();", + " stereoFormantConfig.resynthesis.stereoOutput = true;", + " stereoFormantConfig.resynthesis.formant.enabled = true;", + " processor.setConfig(stereoFormantConfig);", + " const stereoFormantActivity = processor.controlActivity();", + " assert.equal(stereoFormantActivity.leadGain, true);", + " assert.equal(stereoFormantActivity.harmonyVoiceGains, true);", + " assert.equal(stereoFormantActivity.harmonyVoicePans, true);", + " assert.equal(stereoFormantActivity.harmonyVoiceMutes, true);", + " assert.equal(stereoFormantActivity.harmonyVoiceFormantStretch, true);", + " assert.equal(stereoFormantActivity.harmonyVoiceFormantWidth, true);", + "", + " const zeroIntervalConfig = processor.config();", + ' zeroIntervalConfig.resynthesis.harmony.source = "fixedInterval";', + " zeroIntervalConfig.resynthesis.harmony.voices = 0;", + " processor.setConfig(zeroIntervalConfig);", + " const zeroIntervalActivity = processor.controlActivity();", + " assert.equal(zeroIntervalActivity.leadGain, true);", + " assert.equal(zeroIntervalActivity.harmonyVoiceGains, false);", + " assert.equal(zeroIntervalActivity.harmonyVoicePans, false);", + " assert.equal(zeroIntervalActivity.harmonyVoiceMutes, false);", + " assert.equal(zeroIntervalActivity.harmonyVoiceFormantStretch, false);", + " assert.equal(zeroIntervalActivity.harmonyVoiceFormantWidth, false);", + "", + " const undefinedStripsConfig = processor.config();", + " undefinedStripsConfig.resynthesis.leadGain = undefined;", + " undefinedStripsConfig.resynthesis.harmony.voiceGains = undefined;", + " undefinedStripsConfig.resynthesis.harmony.voicePans = undefined;", + " undefinedStripsConfig.resynthesis.harmony.voiceMutes = undefined;", + " undefinedStripsConfig.resynthesis.harmony.voiceFormantStretch = undefined;", + " undefinedStripsConfig.resynthesis.harmony.voiceFormantWidth = undefined;", + " processor.setConfig(undefinedStripsConfig);", + " assertDefaultVoiceStrips(processor.config().resynthesis);", + "", + " processor.setConfig(customVoiceConfig);", + " const omittedStripsConfig = processor.config();", + " delete omittedStripsConfig.resynthesis.leadGain;", + " delete omittedStripsConfig.resynthesis.harmony.voiceGains;", + " delete omittedStripsConfig.resynthesis.harmony.voicePans;", + " delete omittedStripsConfig.resynthesis.harmony.voiceMutes;", + " delete omittedStripsConfig.resynthesis.harmony.voiceFormantStretch;", + " delete omittedStripsConfig.resynthesis.harmony.voiceFormantWidth;", + " processor.setConfig(omittedStripsConfig);", + " assertDefaultVoiceStrips(processor.config().resynthesis);", + "", " const twoVoiceConfig = processor.config();", " twoVoiceConfig.resynthesis.harmony.voices = 2;", " processor.setConfig(twoVoiceConfig);", @@ -359,16 +450,37 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", "", " const mono = new Int16Array(128);", + " processor.setConfig(customVoiceConfig);", " const eventResynthesis = processor.config().resynthesis;", " eventResynthesis.correction.humanize = undefined;", " eventResynthesis.correction.flexTune = undefined;", + " eventResynthesis.leadGain = undefined;", " eventResynthesis.harmony.voices = undefined;", + " eventResynthesis.harmony.voiceGains = undefined;", + " eventResynthesis.harmony.voicePans = undefined;", + " eventResynthesis.harmony.voiceMutes = undefined;", + " eventResynthesis.harmony.voiceFormantStretch = undefined;", + " eventResynthesis.harmony.voiceFormantWidth = undefined;", " processor.processMono(mono, [", ' { offset: 0, event: { type: "resynthesis", value: eventResynthesis } },', " ]);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + " assertDefaultVoiceStrips(processor.config().resynthesis);", + "", + " processor.setConfig(customVoiceConfig);", + " const omittedEventResynthesis = processor.config().resynthesis;", + " delete omittedEventResynthesis.leadGain;", + " delete omittedEventResynthesis.harmony.voiceGains;", + " delete omittedEventResynthesis.harmony.voicePans;", + " delete omittedEventResynthesis.harmony.voiceMutes;", + " delete omittedEventResynthesis.harmony.voiceFormantStretch;", + " delete omittedEventResynthesis.harmony.voiceFormantWidth;", + " processor.processMono(mono, [", + ' { offset: 0, event: { type: "resynthesis", value: omittedEventResynthesis } },', + " ]);", + " assertDefaultVoiceStrips(processor.config().resynthesis);", "", " const input = new Int16Array(128);", " const left = new Int16Array(128);", @@ -774,6 +886,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " ...baseConfig,", " resynthesis: {", " ...baseConfig.resynthesis,", + " leadGain: optionalVoices,", " correction: {", " ...baseConfig.resynthesis.correction,", " humanize: optionalVoices,", @@ -782,6 +895,11 @@ function verifyTypeDeclarations(consumerDir, packageName) { " harmony: {", " ...baseConfig.resynthesis.harmony,", " voices: optionalVoices,", + " voiceGains: undefined,", + " voicePans: undefined,", + " voiceMutes: undefined,", + " voiceFormantStretch: undefined,", + " voiceFormantWidth: undefined,", " },", " },", " };", @@ -801,6 +919,14 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const processor = new Tunelet(48000, 128, configWithUndefined);", " processor.setConfig(configWithUndefined);", " const activity: ControlActivity = processor.controlActivity();", + " const conditionalVoiceFlags: [boolean, boolean, boolean, boolean, boolean, boolean] = [", + " activity.leadGain,", + " activity.harmonyVoiceGains,", + " activity.harmonyVoicePans,", + " activity.harmonyVoiceMutes,", + " activity.harmonyVoiceFormantStretch,", + " activity.harmonyVoiceFormantWidth,", + " ];", " const telemetry: Telemetry = processor.telemetry();", " const voiceSlices: [Float32Array, Float32Array] = [", " telemetry.voiceRatios,", @@ -821,16 +947,37 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const monoTail: number = processor.drainMonoF32InPlace(128);", " views.refresh();", " const resynthesisUpdate: ResynthesisConfig = {", - " ...configWithUndefined.resynthesis,", + " pitch: configWithUndefined.resynthesis.pitch,", " correction: {", " enabled: configWithUndefined.resynthesis.correction.enabled,", " notes: configWithUndefined.resynthesis.correction.notes,", " retuneMs: configWithUndefined.resynthesis.correction.retuneMs,", " },", + " pitchRatio: configWithUndefined.resynthesis.pitchRatio,", + " formant: configWithUndefined.resynthesis.formant,", + " mode: configWithUndefined.resynthesis.mode,", + " choirVoices: configWithUndefined.resynthesis.choirVoices,", + " choirDetune: configWithUndefined.resynthesis.choirDetune,", + " choirDelay: configWithUndefined.resynthesis.choirDelay,", + " choirSpreadPercent: configWithUndefined.resynthesis.choirSpreadPercent,", + " stereoOutput: configWithUndefined.resynthesis.stereoOutput,", " harmony: {", - " ...configWithUndefined.resynthesis.harmony,", - " voices: undefined,", + " source: configWithUndefined.resynthesis.harmony.source,", + " key: configWithUndefined.resynthesis.harmony.key,", + " scale: configWithUndefined.resynthesis.harmony.scale,", + " chromaticIntervals: configWithUndefined.resynthesis.harmony.chromaticIntervals,", + " diatonicIntervals: configWithUndefined.resynthesis.harmony.diatonicIntervals,", + " chord: configWithUndefined.resynthesis.harmony.chord,", + " degree: configWithUndefined.resynthesis.harmony.degree,", + " inversion: configWithUndefined.resynthesis.harmony.inversion,", + " registerPercent: configWithUndefined.resynthesis.harmony.registerPercent,", + " voicingSpreadPercent: configWithUndefined.resynthesis.harmony.voicingSpreadPercent,", + " portamentoMs: configWithUndefined.resynthesis.harmony.portamentoMs,", " },", + " harmonyGain: configWithUndefined.resynthesis.harmonyGain,", + " harmonicModulation: configWithUndefined.resynthesis.harmonicModulation,", + " dryMix: configWithUndefined.resynthesis.dryMix,", + " randomSeed: configWithUndefined.resynthesis.randomSeed,", " };", " const input = new Int16Array(128);", " const left = new Int16Array(128);", @@ -865,6 +1012,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " views.dispose();", " processor.free();", " void activity;", + " void conditionalVoiceFlags;", " void voiceSlices;", " void ptrs;", " void stereoOut;", @@ -1217,10 +1365,39 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { assert.ok( controlActivityInterfaceMatch[2].includes("`HarmonyConfig.source`"), ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.voiceGains`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.voicePans`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.voiceMutes`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.voiceFormantStretch`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.voiceFormantWidth`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`ResynthesisConfig.leadGain`"), + ); assert.ok( controlActivityInterfaceMatch[2].includes("`ReverbConfig.brightnessHz`"), ); + const formantEnvelopeDoc = extractMemberJsDoc( + dts, + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+formantEnvelope\([^)]*\): boolean;/, + "formantEnvelope", + ).replace(/\s+/g, " "); + assert.ok(formantEnvelopeDoc.includes("lead (slot 0) synthesis envelope")); + assert.ok(formantEnvelopeDoc.includes("`FormantConfig.width`")); + assert.ok(formantEnvelopeDoc.includes("`FormantConfig.stretch`")); + assert.ok(formantEnvelopeDoc.includes("`HarmonyConfig.voiceFormantWidth`")); + assert.ok(formantEnvelopeDoc.includes("`HarmonyConfig.voiceFormantStretch`")); + const telemetryInterfaceMatch = /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export interface Telemetry \{([\s\S]*?)\n\}/.exec( dts, diff --git a/src/config.rs b/src/config.rs index 741d08c..0c9b3f7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -210,8 +210,8 @@ impl ProcessorConfig { /// the active modes. /// /// A `false` flag means that the related control makes no sample change in - /// the active voice mode, harmony source or reverb network. This method - /// does not allocate memory and does not validate ranges. + /// the active voice, stereo, harmony, formant or reverb settings. This + /// method does not allocate memory and does not validate ranges. pub fn control_activity(self) -> ControlActivity { let choir = self.resynthesis.mode == MultiVoiceMode::Choir; let multi_choir = choir && self.resynthesis.choir_voices > 1; @@ -222,11 +222,13 @@ impl ProcessorConfig { HarmonySource::FixedInterval | HarmonySource::SmartInterval ); let interval_voices = self.resynthesis.harmony.voices > 0; + let harmony_voices = harmony && (!interval || interval_voices); let named_or_degree = matches!( source, HarmonySource::ChordByDegree | HarmonySource::ChordByName ); let chord = named_or_degree || source == HarmonySource::ChordViaMidi; + let formant = self.resynthesis.formant.enabled; let reverb = self.reverb.enabled; let reverb_mode = self.reverb.mode; ControlActivity { @@ -251,9 +253,15 @@ impl ProcessorConfig { harmony_inversion: harmony && named_or_degree, harmony_register_percent: harmony && chord, harmony_voicing_spread_percent: harmony && chord, - harmony_portamento_ms: harmony && (!interval || interval_voices), + harmony_portamento_ms: harmony_voices, harmony_voices: harmony && interval, - harmony_gain: harmony && (!interval || interval_voices), + harmony_voice_gains: harmony_voices, + harmony_voice_pans: harmony_voices && self.resynthesis.stereo_output, + harmony_voice_mutes: harmony_voices, + harmony_voice_formant_stretch: harmony_voices && formant, + harmony_voice_formant_width: harmony_voices && formant, + lead_gain: harmony, + harmony_gain: harmony_voices, reverb_mode: reverb, reverb_mix: reverb, reverb_diffusion: reverb @@ -270,8 +278,8 @@ impl ProcessorConfig { /// /// Get this snapshot from [`ProcessorConfig::control_activity`] or /// [`crate::Processor::control_activity`]. A `false` flag means that the -/// related control makes no sample change in the active voice mode, harmony -/// source or reverb network. `Default` sets all flags to `false`. +/// related control makes no sample change in the active voice, stereo, +/// harmony, formant or reverb settings. `Default` sets all flags to `false`. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -312,6 +320,18 @@ pub struct ControlActivity { pub harmony_portamento_ms: bool, /// `true` if [`crate::HarmonyConfig::voices`] is active. pub harmony_voices: bool, + /// `true` if [`crate::HarmonyConfig::voice_gains`] is active. + pub harmony_voice_gains: bool, + /// `true` if [`crate::HarmonyConfig::voice_pans`] is active. + pub harmony_voice_pans: bool, + /// `true` if [`crate::HarmonyConfig::voice_mutes`] is active. + pub harmony_voice_mutes: bool, + /// `true` if [`crate::HarmonyConfig::voice_formant_stretch`] is active. + pub harmony_voice_formant_stretch: bool, + /// `true` if [`crate::HarmonyConfig::voice_formant_width`] is active. + pub harmony_voice_formant_width: bool, + /// `true` if [`ResynthesisConfig::lead_gain`] is active. + pub lead_gain: bool, /// `true` if [`ResynthesisConfig::harmony_gain`] is active. pub harmony_gain: bool, /// `true` if [`ReverbConfig::mode`] is active. diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..6ae5acf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -72,9 +72,9 @@ //! pitch, the voice ratios and gains, the peaks, the clarity and the effect //! state. In mono calls, the feedback and telemetry peaks measure the audio //! after the downmix. [`Processor::take_telemetry`] also clears the peak -//! windows of the telemetry. [`Processor::formant_envelope`] writes the LPC -//! envelopes before and after the formant controls. These calls do not change -//! the audio. +//! windows of the telemetry. [`Processor::formant_envelope`] writes the lead +//! LPC envelopes before and after the global formant controls. These calls do +//! not change the audio. //! //! After the last input block, call [`Processor::begin_drain`] one time. Then //! render drain blocks until a call returns zero. Each call fills the unused diff --git a/src/processor.rs b/src/processor.rs index 80eded9..2d2c5fc 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -504,8 +504,8 @@ impl Processor { /// the current configuration. /// /// A `false` flag means that the related control makes no sample change in - /// the active voice mode, harmony source or reverb network. This method - /// does not allocate memory and does not change state. + /// the active voice, stereo, harmony, formant or reverb settings. This + /// method does not allocate memory and does not change state. pub fn control_activity(&self) -> ControlActivity { self.config.control_activity() } @@ -604,14 +604,18 @@ impl Processor { self.reverb.clear_wet_peak(); } - /// Writes the formant envelopes of the model that the audio used for the + /// Writes the formant envelopes of the lead vocal-tract model from the /// last frame. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the width and stretch controls. Point - /// `k` of `n` is at the frequency `max_frequency_hz * k / (n - 1)`. The - /// values are linear magnitudes. They have no absolute level, because the - /// analysis normalizes the signal energy. Scale them for a display. + /// `output` gets the lead (slot 0) synthesis envelope after + /// [`crate::FormantConfig::width`] and [`crate::FormantConfig::stretch`]. + /// It does not include [`crate::HarmonyConfig::voice_formant_width`] or + /// [`crate::HarmonyConfig::voice_formant_stretch`]. + /// + /// Point `k` of `n` is at the frequency `max_frequency_hz * k / (n - 1)`. + /// The values are linear magnitudes. They have no absolute level, because + /// the analysis normalizes the signal energy. Scale them for a display. /// /// `max_frequency_hz` must be finite, more than zero and not more than /// half of the sample rate. The two slices must have the same length. diff --git a/src/wasm.rs b/src/wasm.rs index 0c62ce6..a15ba63 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -714,8 +714,8 @@ impl WasmProcessor { /// the active configuration. /// /// A `false` flag means that the related control makes no sample change in - /// the active voice mode, harmony source or reverb network. The audio - /// state does not change. + /// the active voice, stereo, harmony, formant or reverb settings. The + /// audio state does not change. /// /// # Errors /// @@ -757,14 +757,18 @@ impl WasmProcessor { Ok(telemetry) } - /// Writes the formant envelopes of the current model into two - /// `Float32Array` buffers of equal length. + /// Writes the formant envelopes of the current lead vocal-tract model into + /// two `Float32Array` buffers of equal length. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the width and stretch controls. Point - /// `k` of `n` is at the frequency `maxFrequencyHz * k / (n - 1)`. The - /// values are linear magnitudes with no absolute level. Scale them for a - /// display. + /// `output` gets the lead (slot 0) synthesis envelope after + /// [`crate::FormantConfig::width`] and [`crate::FormantConfig::stretch`]. + /// It does not include [`crate::HarmonyConfig::voice_formant_width`] or + /// [`crate::HarmonyConfig::voice_formant_stretch`]. + /// + /// Point `k` of `n` is at the frequency `maxFrequencyHz * k / (n - 1)`. + /// The values are linear magnitudes with no absolute level. Scale them for + /// a display. /// /// `maxFrequencyHz` must be finite, more than zero and not more than half /// of the sample rate.