From e539fb13c3a26a7e747219a3ae1d14a57061f47d 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:42:27 +0000 Subject: [PATCH] feat(harmony): add per-voice harmony mix controls - Add lead_gain to ResynthesisConfig and validate its range. - Add voice_gains, voice_pans and voice_mutes to HarmonyConfig. - Validate voice_gains and voice_pans in HarmonyConfig::validate. - Precompute Q14 lead, mono harmony and stereo pan gains. - Apply harmony mix gains in mono and stereo resynthesis. - Accept absent optional harmony mix fields in JavaScript. - Document the harmony mix fields and telemetry gains. --- README.md | 33 +++++++++++-- src/harmony.rs | 87 +++++++++++++++++++++++++++++++--- src/processor.rs | 18 ++++--- src/resynthesis.rs | 114 ++++++++++++++++++++++++++++++++------------- src/wasm.rs | 6 +++ 5 files changed, 208 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index d2993dc..066a1d1 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,19 @@ 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. +These fields mix the lead voice and the four harmony voices in `Harmony` mode: + +- `resynthesis.lead_gain` scales the lead voice, in `0..=1` (default `1`). +- `resynthesis.harmony_gain` scales all four harmony voices in mono and stereo + output, in `0..=1` (default `0.5`). +- `resynthesis.harmony.voice_gains` scales each harmony voice, in `0..=1` + (default `[1, 1, 1, 1]`). +- If `stereo_output` is `true`, `resynthesis.harmony.voice_pans` sets the + constant-power stereo pan of each harmony voice, in `-1..=1` (default + `[-0.33333334, 0.33333334, -1, 1]`). +- `resynthesis.harmony.voice_mutes` mutes individual harmony voices in mono and + stereo output (default `[false, false, false, false]`). + ## Process audio To prepare a processor, do these steps: @@ -297,7 +310,9 @@ These calls read the state of the processor. They do not change the audio. The telemetry includes these items: -- The pitch ratio and the gain of each voice. +- The pitch ratio and the controller gain of each voice. In `Harmony` mode, + `voice_gains` in telemetry reports the controller envelope and does not + include `lead_gain`, `harmony_gain` or the harmony mix controls. - The peaks of the input, of the two output channels and of the reverb wet signal. - The pitch clarity, which is a confidence score from 0 to 1. @@ -444,10 +459,18 @@ 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 their defaults if they are +absent: + +- `resynthesis.leadGain` defaults to `1`. +- `resynthesis.harmony.voices` defaults to `4`. +- `resynthesis.harmony.voiceGains` defaults to `[1, 1, 1, 1]`. +- `resynthesis.harmony.voicePans` defaults to + `[-0.33333334, 0.33333334, -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/harmony.rs b/src/harmony.rs index 67b7111..80216af 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -18,6 +18,11 @@ use chords::SCALE_TONES; /// same count. pub const HARMONY_VOICES: usize = 4; +/// The default linear gain of each harmony voice: unity. +pub(crate) const DEFAULT_VOICE_GAINS: [f32; HARMONY_VOICES] = [1.0; HARMONY_VOICES]; +/// The default stereo pan position of each harmony voice, in -1.0..=1.0. +pub(crate) const DEFAULT_VOICE_PANS: [f32; HARMONY_VOICES] = [-0.33333334, 0.33333334, -1.0, 1.0]; + /// The Q12 step that increases the gain envelope of a voice toward a higher /// target gain (attack). /// @@ -240,6 +245,7 @@ pub enum Inversion { /// - A register of 50%. /// - A closed voicing and zero portamento. /// - Four voices for the interval sources. +/// - Unity voice gains, default stereo pans and no voice mutes. /// /// These settings configure all sources. Only the fields for the selected /// source change the target notes. Validation always checks all fields. @@ -328,6 +334,45 @@ pub struct HarmonyConfig { tsify(optional) )] pub voices: u8, + /// Four linear gains for the harmony voices, each in 0..=1. + /// + /// The default is `[1.0, 1.0, 1.0, 1.0]`. Each value scales one harmony + /// voice in mono and stereo output. + /// [`crate::ResynthesisConfig::harmony_gain`] also scales all four voices. + /// 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_gains"), + 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 puts the voice on the left channel. A value of 0 puts + /// the voice in the center, and 1 puts it on the right channel. The + /// default is `[-0.33333334, 0.33333334, -1.0, 1.0]`. If + /// [`crate::ResynthesisConfig::stereo_output`] is `true`, resynthesis uses + /// these positions for a constant-power stereo pan. 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 all `false`. + /// + /// If an entry is `true`, that harmony voice has zero output gain in mono + /// and stereo output. Its reader and gain envelope continue to advance. + /// 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], } /// The default count of interval voices: all of them. @@ -336,6 +381,18 @@ fn default_voices() -> u8 { HARMONY_VOICES as u8 } +/// The default linear gains of the four harmony voices. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_voice_gains() -> [f32; HARMONY_VOICES] { + DEFAULT_VOICE_GAINS +} + +/// The default stereo pan positions of the four harmony voices. +#[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 +408,9 @@ impl Default for HarmonyConfig { voicing_spread_percent: 0.0, portamento_ms: 0.0, voices: HARMONY_VOICES as u8, + voice_gains: DEFAULT_VOICE_GAINS, + voice_pans: DEFAULT_VOICE_PANS, + voice_mutes: [false; HARMONY_VOICES], } } } @@ -359,10 +419,10 @@ impl HarmonyConfig { /// Validates all fields, which includes the fields that the selected /// source does not use. /// - /// Each element of the two interval arrays must be in its documented - /// inclusive range. The floating-point controls must be finite and in - /// their documented inclusive ranges. Validation does not clamp values. - /// It does not change the processor state. + /// Each element of the interval, gain and pan arrays must be in its + /// documented inclusive range. The floating-point controls must be finite + /// and in their documented inclusive ranges. Validation does not clamp + /// values. It does not change the processor state. /// /// # Errors /// @@ -389,7 +449,14 @@ 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)?; + } + Ok(()) } } @@ -539,7 +606,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/processor.rs b/src/processor.rs index cc910f4..e077f1a 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -840,15 +840,19 @@ pub struct Telemetry { /// pitch shift and the ratio of the voice. The entries after /// [`voice_count`](Self::voice_count) are zero. pub voice_ratios: [f32; 16], - /// The linear gain of each voice, in the order of + /// The linear controller gain of each voice, in the order of /// [`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. + /// The lead and the choir voices report a gain of 1. The gain of a harmony + /// voice is the envelope of the harmony controller, which includes the + /// MIDI velocity gain in 0..=3.98095703125. MIDI velocity 127 gives the + /// maximum, approximately +12 dB, and an inactive voice reports zero. + /// These values do not include [`crate::ResynthesisConfig::lead_gain`], + /// [`crate::ResynthesisConfig::harmony_gain`], + /// [`crate::HarmonyConfig::voice_gains`], + /// [`crate::HarmonyConfig::voice_pans`] or + /// [`crate::HarmonyConfig::voice_mutes`]. The harmony controller updates + /// them every 101 frames. pub voice_gains: [f32; 16], /// The current drive of Punch, divided by its base drive. /// diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..7692ec2 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -32,7 +32,7 @@ mod history; use crate::error::{check_count, check_range}; use crate::filter::{Biquad, Design}; use crate::formant::{Formant, FormantConfig, ANALYSIS_FRAMES}; -use crate::harmony::{HarmonyConfig, HarmonyState, HARMONY_VOICES}; +use crate::harmony::{HarmonyConfig, HarmonyState, DEFAULT_VOICE_PANS, HARMONY_VOICES}; use crate::midi::MidiEvent; use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; use crate::numeric::{ring, NumericContext, HISTORY}; @@ -223,11 +223,24 @@ 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 Harmony mode, 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. + /// A value of 0 mutes the lead voice in the Harmony mix. The lead reader + /// continues to advance, so formant synthesis keeps its alignment. 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 linear gain of the four harmony voices, 0..=1. The default is 0.5. + /// + /// Resynthesis multiplies this gain with each entry of + /// [`HarmonyConfig::voice_gains`] in mono and stereo output. It does not + /// scale the lead voice, and Choir does not use this value. pub harmony_gain: f32, /// The modulation depth, 0..=24, without a unit. The default is 0 (off). /// @@ -267,6 +280,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, @@ -275,6 +289,12 @@ impl Default for ResynthesisConfig { } } +/// The default linear gain of the lead voice in Harmony mode: unity. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_lead_gain() -> f32 { + 1.0 +} + impl ResynthesisConfig { /// Validates all fields, also the settings for stages that are disabled /// or not active. @@ -299,6 +319,7 @@ impl ResynthesisConfig { let field = "resynthesis.choir_spread_percent"; check_range(field, self.choir_spread_percent, 0.0, 100.0)?; check_range("resynthesis.harmony_gain", self.harmony_gain, 0.0, 1.0)?; + check_range("resynthesis.lead_gain", self.lead_gain, 0.0, 1.0)?; let field = "resynthesis.harmonic_modulation"; check_range(field, self.harmonic_modulation, 0.0, 24.0)?; check_range("resynthesis.dry_mix", self.dry_mix, 0.0, 1.0)?; @@ -419,8 +440,13 @@ 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 linear gain of the lead voice in Harmony mode. + lead_gain: Q14, + /// The Q14 mono gains of the harmony voices. They include `harmony_gain`, + /// `voice_gains` and `voice_mutes`. + harmony_mono: [Q14; HARMONY_VOICES], + /// The Q14 stereo pan gains of the harmony voices. They include + /// `harmony_gain`, `voice_gains`, `voice_pans` and `voice_mutes`. harmony_pan: [[Q14; 2]; HARMONY_VOICES], /// The last Q14 target ratios from the harmony controller. harmony_ratios: [Q14; HARMONY_VOICES], @@ -526,6 +552,8 @@ impl Resynthesis { drift: [Q14::ZERO; 16], drift_ratio: [Q14::ONE; 16], pan: [[Q14::ONE; 2]; 16], + lead_gain: Q14::ONE, + harmony_mono: [Q14::ZERO; HARMONY_VOICES], harmony_pan: [[Q14::ZERO; 2]; HARMONY_VOICES], harmony_ratios: [Q14::ONE; HARMONY_VOICES], harmony_gains: [Q12::ZERO; HARMONY_VOICES], @@ -556,13 +584,15 @@ impl Resynthesis { } /// Quantizes the controls and calculates the decay coefficients and the - /// voice pan gains again. + /// voice mix 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. + /// Both the mono and the stereo harmony gains include the harmony level, + /// the voice gains and the voice mutes. fn configure_coefficients(&mut self) { + const LEFT_THIRD_BITS: u32 = DEFAULT_VOICE_PANS[0].to_bits(); + const RIGHT_THIRD_BITS: u32 = DEFAULT_VOICE_PANS[1].to_bits(); self.shift = Q14::from_f64(self.config.pitch_ratio 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); @@ -588,12 +618,21 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } - for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] - .into_iter() - .enumerate() - { + self.lead_gain = Q14::from_f64(self.config.lead_gain as f64); + for voice in 0..HARMONY_VOICES { + let gain = if self.config.harmony.voice_mutes[voice] { + 0.0 + } else { + self.config.harmony_gain as f64 * self.config.harmony.voice_gains[voice] as f64 + }; + self.harmony_mono[voice] = Q14::from_f64(gain); + let pan = self.config.harmony.voice_pans[voice]; + let fraction = match pan.to_bits() { + LEFT_THIRD_BITS => 0.3333333333333333, + RIGHT_THIRD_BITS => 0.6666666666666666, + _ => (pan as f64 + 1.0) * 0.5, + }; 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()), @@ -801,14 +840,17 @@ impl Resynthesis { pub(crate) fn is_tracking(&self) -> bool { !self.pitch.is_detecting() } - /// Writes the effective ratio and the linear gain of each voice from the - /// last frame, and returns the number of voices. + /// Writes the effective ratio and the controller gain of each voice from + /// the last frame, and returns the number of voices. /// - /// Slot zero is the lead. In Harmony mode, slots 1 to 4 are the harmony - /// voices, and the gain is the envelope of the harmony controller. In - /// Choir mode, the slots after the lead are the secondary voices with a - /// gain of 1. Each ratio includes the correction, the global shift and - /// the ratio of the voice. The entries after the count do not change. + /// Slot zero is the lead, with a reported gain of 1. In Harmony mode, + /// slots 1 to 4 are the harmony voices, and each gain is the envelope of + /// the harmony controller. These reported gains do not include + /// `lead_gain`, `harmony_gain`, `HarmonyConfig::voice_gains`, + /// `HarmonyConfig::voice_pans` or `HarmonyConfig::voice_mutes`. In Choir + /// mode, the slots after the lead are the secondary voices with a gain + /// of 1. Each ratio includes the correction, the global shift and the + /// ratio of the voice. The entries after the count do not change. pub(crate) fn voices(&self, ratios: &mut [f32; 16], gains: &mut [f32; 16]) -> u8 { let lead = (self.voice_ratios[0].to_bits() as f64 / 16384.0) as f32; ratios[0] = lead; @@ -1234,16 +1276,24 @@ impl Resynthesis { 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 - }; + 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_mono[voice]); + for sum in &mut mix { + *sum = *sum + value; + } + } } } if self.config.formant.enabled { diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..2a93186 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,7 +19,13 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. +//! - The optional `resynthesis.leadGain` field defaults to 1. //! - The optional harmony `voices` field defaults to 4. +//! - The optional harmony `voiceGains` field defaults to `[1, 1, 1, 1]`. +//! - The optional harmony `voicePans` field defaults to +//! `[-0.33333334, 0.33333334, -1, 1]`. +//! - The optional harmony `voiceMutes` field 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