diff --git a/README.md b/README.md index a06715f..83aebd6 100644 --- a/README.md +++ b/README.md @@ -205,8 +205,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 @@ -364,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: @@ -386,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 | | ----------- | ---------------------------------------------------------------- | @@ -579,11 +590,19 @@ and show enums as string literals. To change the configuration, do these steps: If a required field is absent or a value is not valid, the call throws a JavaScript `Error`. If an optional field is absent or `undefined`, it gets its -default. `resynthesis.correction.humanize` and -`resynthesis.correction.flexTune` default to 0, and -`resynthesis.harmony.voices` defaults to 4. The conversion ignores extra object -properties. The generated declarations contain the parameter documentation from -the Rust types. +default: + +- `resynthesis.correction.humanize` and `resynthesis.correction.flexTune` + default to `0`. +- `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 @@ -631,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 0f6a77f..2550388 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -48,7 +48,20 @@ const EXACT_REPLACEMENTS = [ "[`ResynthesisConfig::choir_spread_percent`]", "`ResynthesisConfig.choirSpreadPercent`", ], + ["[`crate::ResynthesisConfig::lead_gain`]", "`ResynthesisConfig.leadGain`"], + ["[`ResynthesisConfig::lead_gain`]", "`ResynthesisConfig.leadGain`"], + [ + "[`crate::ResynthesisConfig::harmony_gain`]", + "`ResynthesisConfig.harmonyGain`", + ], ["[`ResynthesisConfig::harmony_gain`]", "`ResynthesisConfig.harmonyGain`"], + [ + "[`crate::ResynthesisConfig::stereo_output`]", + "`ResynthesisConfig.stereoOutput`", + ], + ["[`crate::FormantConfig::enabled`]", "`FormantConfig.enabled`"], + ["[`crate::FormantConfig::stretch`]", "`FormantConfig.stretch`"], + ["[`crate::FormantConfig::width`]", "`FormantConfig.width`"], ["[`crate::HarmonyConfig::source`]", "`HarmonyConfig.source`"], ["[`crate::HarmonyConfig::key`]", "`HarmonyConfig.key`"], ["[`crate::HarmonyConfig::scale`]", "`HarmonyConfig.scale`"], @@ -73,6 +86,18 @@ const EXACT_REPLACEMENTS = [ ], ["[`crate::HarmonyConfig::portamento_ms`]", "`HarmonyConfig.portamentoMs`"], ["[`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`"], @@ -104,6 +129,9 @@ const EXACT_REPLACEMENTS = [ ["`None`", "`undefined`"], ["`u64::MAX`", "`2n ** 64n - 1n`"], ["`0x1234_abcd`", "`0x1234abcdn`"], + ["`[1.0; 4]`", "`[1, 1, 1, 1]`"], + ["`[false; 4]`", "`[false, false, false, false]`"], + ["`[-1.0 / 3.0, 1.0 / 3.0, -1.0, 1.0]`", "`[-1/3, 1/3, -1, 1]`"], ["`max_frequency_hz`", "`maxFrequencyHz`"], ["`min_frequency_hz`", "`minFrequencyHz`"], ["`stereo_output`", "`stereoOutput`"], 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/formant.rs b/src/formant.rs index b4ea383..8ca1b09 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::{ @@ -146,6 +149,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. /// @@ -235,12 +241,17 @@ impl 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 /// stage runs. config: FormantConfig, + /// The validated vocal-tract width multipliers of the four harmony voices. + voice_width: [f32; HARMONY_VOICES], + /// The validated vocal-tract length multipliers of the four harmony + /// voices. + voice_stretch: [f32; HARMONY_VOICES], /// The sample rate for analysis windows, glottal decay and the aspiration /// filter. rate: SampleRate, @@ -252,12 +263,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 active pair of coefficient banks and the Q14 weight of the blend. @@ -266,15 +277,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 rings of the synthesis, each with two copies - /// of `MAX_ORDER` entries. Choir uses channel zero, and mono harmony - /// copies to channel one. - history: [[i32; MAX_ORDER * 2]; 2], - /// If `true`, the two channels of `history` hold equal samples. - histories_match: bool, - /// The start slot in the synthesis history. The two channels use the same - /// slot. - history_index: usize, + /// The separate Q14 feedback rings for the lead voice and the four + /// harmony voices. Each ring holds two copies of `MAX_ORDER` entries. + history: [[i32; MAX_ORDER * 2]; VOICE_BANKS], + /// The start 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], @@ -291,20 +300,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], @@ -346,17 +356,24 @@ 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 { config, + voice_width, + voice_stretch, rate, input: vec![0; HISTORY + ORDER], 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], stamp: Stamp { current: 1, @@ -364,9 +381,9 @@ impl Formant { blend: 0, }, design_counter: 0, - history: [[0; MAX_ORDER * 2]; 2], - histories_match: true, - history_index: 0, + history: [[0; MAX_ORDER * 2]; VOICE_BANKS], + history_index: [0; VOICE_BANKS], + history_dirty: [false; VOICE_BANKS], correlation_history: [[0; 111]; 2], correlation_sum: [0; 111], smooth_index: 0, @@ -374,11 +391,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(), @@ -396,27 +413,46 @@ impl Formant { pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { self.aspiration_muted = muted; } - /// Quantizes the vocal-tract width and its square unconditionally. - fn configure_width(&mut self) { - let width = self.config.width as f64; - self.width = (width * 16384.0) as i32; - self.width_squared = (width * width * 16384.0) as i32; + /// Quantizes the vocal-tract width and its square for one voice slot. + fn configure_slot_width(&mut self, slot: usize, width: f64) { + self.width[slot] = (width * 16384.0) as i32; + self.width_squared[slot] = (width * width * 16384.0) as i32; } - /// Quantizes the stretch factor and prepares the Q7 interpolation map - /// unconditionally. + /// Quantizes the stretch factor and builds the Q7 area map for one voice + /// slot. /// /// A valid stretch gives a model with 25 to 99 entries. Thus, the last - /// point of the map and the denominators of the interpolation are always + /// point of each map and the denominators of the interpolation are always /// defined. + fn configure_slot_stretch(&mut self, slot: usize, stretch: f64) { + 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 vocal-tract width and its square for all five voice slots + /// unconditionally. + fn configure_width(&mut self) { + let lead_width = f64::from(self.config.width); + self.configure_slot_width(0, lead_width); + for voice in 0..HARMONY_VOICES { + let width = (lead_width * f64::from(self.voice_width[voice])).clamp(0.5, 2.0); + self.configure_slot_width(voice + 1, width); + } + } + /// Quantizes the stretch factor and prepares the Q7 interpolation maps for + /// all five voice slots unconditionally. fn configure_stretch(&mut self) { - let stretch = self.config.stretch as f64; - self.stretch = (stretch * 16384.0) as i32; - self.stretch_count = (((ORDER - 1) as f64 * stretch + 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_stretch = f64::from(self.config.stretch); + self.configure_slot_stretch(0, lead_stretch); + for voice in 0..HARMONY_VOICES { + let stretch = (lead_stretch * f64::from(self.voice_stretch[voice])).clamp(0.5, 2.0); + self.configure_slot_stretch(voice + 1, stretch); } - self.stretch_map[self.stretch_count - 1] = ((ORDER - 1) * 128) as i32; } /// Quantizes the aspiration wet mix unconditionally. fn configure_aspiration_mix(&mut self) { @@ -440,17 +476,26 @@ impl Formant { self.configure_aspiration_mix(); self.configure_aspiration_cutoff_hz(); } - /// Updates the quantized controls, the Q7 area map and the aspiration + /// Updates the quantized controls, the Q7 area maps and the aspiration /// filter for the fields that changed. /// /// The histories do not change. - 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], + ) { let old = self.config; + let old_voice_width = self.voice_width; + let old_voice_stretch = self.voice_stretch; self.config = config; - if old.width != config.width { + self.voice_width = voice_width; + self.voice_stretch = voice_stretch; + if old.width != config.width || old_voice_width != voice_width { self.configure_width(); } - if old.stretch != config.stretch { + if old.stretch != config.stretch || old_voice_stretch != voice_stretch { self.configure_stretch(); } if old.aspiration_mix != config.aspiration_mix { @@ -460,7 +505,8 @@ impl Formant { self.configure_aspiration_cutoff_hz(); } } - /// Stores the vocal-tract width. If the value changed, quantizes it again. + /// Stores the vocal-tract width. If the value changed, quantizes all five + /// voice slots again. pub(crate) fn set_width(&mut self, width: f32) { let changed = self.config.width != width; self.config.width = width; @@ -469,7 +515,7 @@ impl Formant { } } /// Stores the vocal-tract stretch. If the value changed, prepares the area - /// map again. + /// maps for all five voice slots again. pub(crate) fn set_stretch(&mut self, stretch: f32) { let changed = self.config.stretch != stretch; self.config.stretch = stretch; @@ -494,8 +540,8 @@ impl Formant { self.configure_aspiration_cutoff_hz(); } } - /// 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 @@ -509,9 +555,9 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER * 2]; 2]; - self.histories_match = true; - self.history_index = 0; + self.history = [[0; MAX_ORDER * 2]; VOICE_BANKS]; + self.history_index = [0; VOICE_BANKS]; + self.history_dirty = [false; VOICE_BANKS]; self.stamp.current = (BANKS - 1) as u8; self.next_filter(); self.next_filter(); @@ -540,7 +586,7 @@ impl Formant { /// output. /// /// The caller keeps the history of previous outputs, separately for each - /// channel. + /// voice slot. #[inline] pub(crate) fn model_glottal(&self, sample: i32, previous: i32) -> i32 { sample.saturating_add(round_q14(i64::from(previous) * i64::from(self.glottal))) @@ -584,9 +630,10 @@ impl Formant { self.stamp.blend = 0; let current = usize::from(self.stamp.current); self.inverse[current].fill(0_i32); - - self.models[current].fill(0_i32); - self.orders[current] = 0; + for slot in 0..VOICE_BANKS { + self.models[slot][current].fill(0_i32); + self.orders[slot][current] = 0; + } } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. @@ -777,37 +824,57 @@ 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][current][..ORDER].copy_from_slice(&self.inverse[current]); + self.orders[slot][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][current]; + let (head, tail) = self.models.split_at_mut(slot); + tail[0][current][..order].copy_from_slice(&head[prev][current][..order]); + self.orders[slot][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[current], + &voice_parcor[..count], + &mut self.models[slot][current], &mut scratch, ); - self.orders[current] = self.stretch_count; + self.orders[slot][current] = count; } } - } else { - self.models[current][..ORDER].copy_from_slice(&self.inverse[current]); - self.orders[current] = ORDER; } } else { self.smooth_reset = true; @@ -870,7 +937,7 @@ impl Formant { self.generation } /// Returns the bank epoch, the stamp at a signed history frame and the Q14 - /// width. + /// lead width. pub(crate) fn envelope_stamp(&self, position: i32) -> (u64, u8, u8, u16, i32) { let stamp = self.stamps[ring(position)]; ( @@ -878,7 +945,7 @@ impl Formant { stamp.current, stamp.previous, stamp.blend, - self.width, + self.width[0], ) } /// Returns the analysis coefficients of the stamp at a signed history @@ -921,11 +988,12 @@ impl Formant { ) -> bool { let stamp = self.stamps[ring(position)]; let mut blended; - let synthesis = if let Some(slice) = stamp.synthesis_bank(&self.models, &self.orders) { + let synthesis = if let Some(slice) = stamp.synthesis_bank(&self.models[0], &self.orders[0]) + { slice } else { blended = [0; MAX_ORDER]; - stamp.blend_synthesis(&self.models, &self.orders, &mut blended) + stamp.blend_synthesis(&self.models[0], &self.orders[0], &mut blended) }; if synthesis.is_empty() { input.fill(0.0); @@ -948,7 +1016,7 @@ impl Formant { }; const SCALE: f64 = 1.0 / 16384.0; let glottal = self.glottal as f64 * SCALE; - let width = self.width as f64 * SCALE; + let width = self.width[0] as f64 * SCALE; let mut analysis_taps = [0.0; ORDER]; for (tap, &coefficient) in analysis_taps.iter_mut().zip(analysis) { *tap = coefficient as f64 * SCALE; @@ -1084,50 +1152,34 @@ impl Formant { } true } - /// Applies the stamped synthesis model and the width gain to `samples`. - /// - /// Each channel uses its own feedback history. After all active channels - /// update their two slots, `self.history_index` moves to the previous slot. + /// Applies the stamped synthesis model and the width gain of `slot` to + /// `sample`, and updates the feedback history of `slot`. #[inline] - fn synthesize(&mut self, samples: &mut [i32; CHANNELS], position: i32) { + fn synthesize_slot(&mut self, slot: usize, sample: i32, position: i32) -> i32 { + self.history_dirty[slot] = true; let stamp = self.stamps[ring(position)]; let mut blended; - let coefficients = if let Some(slice) = stamp.synthesis_bank(&self.models, &self.orders) { - slice - } else { - blended = [0; MAX_ORDER]; - stamp.blend_synthesis(&self.models, &self.orders, &mut blended) - }; - let next = if self.history_index == 0 { - MAX_ORDER - 1 - } else { - self.history_index - 1 - }; - for (channel, sample) in samples.iter_mut().enumerate() { - let sum = tap_sum(&self.history[channel][self.history_index..], coefficients); - *sample = sample.saturating_add(round_q14(sum)); - self.history[channel][next] = *sample; - self.history[channel][next + MAX_ORDER] = *sample; - *sample = round_q14(i64::from(*sample) * i64::from(self.width)); - } - self.history_index = next; - } - /// Updates `self.histories_match` from the latest feedback slot in the two - /// channels. - #[inline] - fn update_histories_match(&mut self) { - let index = self.history_index; - if self.histories_match { - self.histories_match = self.history[0][index] == self.history[1][index]; - } else if self.history[0][index] == self.history[1][index] { - self.histories_match = self.history[0][..MAX_ORDER] == self.history[1][..MAX_ORDER]; - } + let coefficients = + if let Some(slice) = stamp.synthesis_bank(&self.models[slot], &self.orders[slot]) { + slice + } else { + blended = [0; MAX_ORDER]; + stamp.blend_synthesis(&self.models[slot], &self.orders[slot], &mut blended) + }; + let index = self.history_index[slot]; + let sum = tap_sum(&self.history[slot][index..], coefficients); + let sample = sample.saturating_add(round_q14(sum)); + let next = if index == 0 { MAX_ORDER - 1 } else { index - 1 }; + self.history[slot][next] = sample; + self.history[slot][next + MAX_ORDER] = sample; + self.history_index[slot] = next; + round_q14(i64::from(sample) * i64::from(self.width[slot])) } /// Applies the optional aspiration and the stamped synthesis model to one - /// Q14 excitation, then scales the result by the width. + /// Q14 excitation, then scales the result by the lead width. /// - /// The function uses the feedback history of channel zero. `position` is - /// an integer frame of the input history. Resynthesis aligns this frame. + /// The function uses the feedback history of slot zero. `position` is an + /// integer frame of the input history. Resynthesis aligns this frame. pub(crate) fn forward( &mut self, sample: i32, @@ -1135,61 +1187,54 @@ impl Formant { context: &mut NumericContext, ) -> i32 { self.dirty = true; - let mut samples = [self.add_noise(sample, context)]; - self.synthesize(&mut samples, position); - self.update_histories_match(); - samples[0] + let sample = self.add_noise(sample, context); + self.synthesize_slot(0, sample, position) } - /// Returns `true` if the two channels of `history` hold equal samples. - #[inline] - pub(crate) fn histories_match(&self) -> bool { - self.histories_match - } - /// Synthesizes one Q14 channel and copies the new feedback sample to - /// channel one. The two channels of `history` must be equal before this - /// call. + /// Reads at most one random value for the current Harmony frame and + /// advances the aspiration filter one time. /// - /// If aspiration is active, the function reads one random value for each - /// frame. It adds the saturated excitation change before the feedback sum. - /// The history cursor moves one time. - pub(crate) fn forward_mono( - &mut self, - sample: i32, - position: i32, - context: &mut NumericContext, - ) -> i32 { + /// If the stage mutes aspiration or the 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.aspiration_muted || self.config.aspiration_mix <= 0.01 { + return None; + } self.dirty = true; - let noise = self.add_noise(sample, context).saturating_sub(sample); - let mut samples = [sample.saturating_add(noise)]; - self.synthesize(&mut samples, position); - let index = self.history_index; - let feedback = self.history[0][index]; - self.history[1][index] = feedback; - self.history[1][index + MAX_ORDER] = feedback; - samples[0] + let random = (context.random.next_u31() >> 17) - 8192; + Some( + self.noise_filter + .process_sample(Q14::from_bits(random)) + .to_bits(), + ) } - /// Synthesizes two Q14 channels with one stamped model for the two - /// channels. Each channel has its own feedback history. - /// - /// 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 moves - /// only after the two channels. - pub(crate) fn forward_stereo( + /// Clears the synthesis feedback history of an inactive or muted voice + /// slot. + 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.synthesize(&mut samples, position); - self.update_histories_match(); - samples + 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 + }; + self.synthesize_slot(slot, sample, position) } } diff --git a/src/harmony.rs b/src/harmony.rs index f2adfe3..fc4d658 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,8 +331,88 @@ pub struct HarmonyConfig { tsify(optional, type = "number | undefined") )] 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 or `undefined` value + /// gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_voice_unity", + deserialize_with = "deserialize_voice_unity" + ), + tsify(optional, type = "[number, number, number, number] | undefined") + )] + 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 or `undefined` value + /// gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_voice_pans", + deserialize_with = "deserialize_voice_pans" + ), + tsify(optional, type = "[number, number, number, number] | undefined") + )] + 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 or `undefined` value + /// gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default, deserialize_with = "deserialize_voice_mutes"), + tsify(optional, type = "[boolean, boolean, boolean, boolean] | undefined") + )] + 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 or `undefined` value + /// gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_voice_unity", + deserialize_with = "deserialize_voice_unity" + ), + tsify(optional, type = "[number, number, number, number] | undefined") + )] + 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 or `undefined` value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_voice_unity", + deserialize_with = "deserialize_voice_unity" + ), + tsify(optional, type = "[number, number, number, number] | undefined") + )] + 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 { @@ -343,6 +426,47 @@ fn deserialize_voices<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Resu Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_voices)) } +/// 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] +} + +/// Decodes optional unity multipliers and maps `undefined` to `[1.0; 4]`. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_voice_unity<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result<[f32; HARMONY_VOICES], D::Error> { + use serde::Deserialize; + Ok(Option::<[f32; HARMONY_VOICES]>::deserialize(deserializer)? + .unwrap_or_else(default_voice_unity)) +} + +/// 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 +} + +/// Decodes optional stereo voice pans and maps `undefined` to the defaults. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_voice_pans<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result<[f32; HARMONY_VOICES], D::Error> { + use serde::Deserialize; + Ok(Option::<[f32; HARMONY_VOICES]>::deserialize(deserializer)? + .unwrap_or_else(default_voice_pans)) +} + +/// Decodes optional voice mutes and maps `undefined` to `[false; 4]`. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_voice_mutes<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result<[bool; HARMONY_VOICES], D::Error> { + use serde::Deserialize; + Ok(Option::<[bool; HARMONY_VOICES]>::deserialize(deserializer)?.unwrap_or_default()) +} + impl Default for HarmonyConfig { fn default() -> Self { Self { @@ -358,6 +482,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], } } } @@ -382,8 +511,48 @@ impl HarmonyConfig { validate_voices(self.voices)?; validate_register_percent(self.register_percent)?; validate_voicing_spread_percent(self.voicing_spread_percent)?; - validate_portamento_ms(self.portamento_ms) + validate_portamento_ms(self.portamento_ms)?; + validate_voice_gains(self.voice_gains)?; + validate_voice_pans(self.voice_pans)?; + validate_voice_formant_stretch(self.voice_formant_stretch)?; + validate_voice_formant_width(self.voice_formant_width) + } +} + +/// Checks the four linear voice gains of harmony. +fn validate_voice_gains(voice_gains: [f32; HARMONY_VOICES]) -> Result<(), Error> { + for gain in voice_gains { + check_range("resynthesis.harmony.voice_gains", gain, 0.0, 1.0)?; } + Ok(()) +} + +/// Checks the four stereo voice pan positions of harmony. +fn validate_voice_pans(voice_pans: [f32; HARMONY_VOICES]) -> Result<(), Error> { + for pan in voice_pans { + check_range("resynthesis.harmony.voice_pans", pan, -1.0, 1.0)?; + } + Ok(()) +} + +/// Checks the four vocal-tract length factors of harmony. +fn validate_voice_formant_stretch( + voice_formant_stretch: [f32; HARMONY_VOICES], +) -> Result<(), Error> { + for stretch in voice_formant_stretch { + let field = "resynthesis.harmony.voice_formant_stretch"; + check_range(field, stretch, 0.5, 2.0)?; + } + Ok(()) +} + +/// Checks the four vocal-tract width factors of harmony. +fn validate_voice_formant_width(voice_formant_width: [f32; HARMONY_VOICES]) -> Result<(), Error> { + for width in voice_formant_width { + let field = "resynthesis.harmony.voice_formant_width"; + check_range(field, width, 0.5, 2.0)?; + } + Ok(()) } /// Checks the four fixed semitone offsets of harmony. 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 9f8ae9b..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. @@ -1267,12 +1271,16 @@ 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. In JavaScript, this field is a `Float32Array` of length - /// `voiceCount`. + /// 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. The harmony controller updates its envelopes every 101 frames. + /// + /// These values are before [`crate::ResynthesisConfig::lead_gain`], + /// [`crate::ResynthesisConfig::harmony_gain`], + /// [`crate::HarmonyConfig::voice_gains`], + /// [`crate::HarmonyConfig::voice_mutes`] and the stereo pan. In JavaScript, + /// this field is a `Float32Array` of length `voiceCount`. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), serde(deserialize_with = "crate::wasm::deserialize_voice_array"), diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..1033248 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 @@ -277,11 +277,29 @@ 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 or `undefined` value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_lead_gain", + deserialize_with = "deserialize_lead_gain" + ), + tsify(optional, type = "number | undefined") + )] + 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). /// @@ -307,6 +325,21 @@ 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 +} + +/// Decodes an optional lead gain and maps `undefined` to 1.0. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_lead_gain<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_lead_gain)) +} + impl Default for ResynthesisConfig { fn default() -> Self { Self { @@ -321,6 +354,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, @@ -351,6 +385,7 @@ impl ResynthesisConfig { validate_choir_detune(self.choir_detune)?; validate_choir_delay(self.choir_delay)?; validate_choir_spread_percent(self.choir_spread_percent)?; + validate_lead_gain(self.lead_gain)?; validate_harmony_gain(self.harmony_gain)?; validate_harmonic_modulation(self.harmonic_modulation)?; validate_dry_mix(self.dry_mix)?; @@ -358,6 +393,11 @@ impl ResynthesisConfig { } } +/// Checks the range of the linear gain of the lead voice in Harmony mode. +fn validate_lead_gain(lead_gain: f32) -> Result<(), Error> { + check_range("resynthesis.lead_gain", lead_gain, 0.0, 1.0) +} + /// Checks the range of the global pitch multiplier. pub(crate) fn validate_pitch_ratio(pitch_ratio: f32) -> Result<(), Error> { check_range("resynthesis.pitch_ratio", pitch_ratio, 0.25, 4.0) @@ -515,10 +555,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], @@ -598,9 +640,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 { @@ -620,7 +662,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: CorrectionTable::new(rate, config.correction.notes), filtered: prepare_history(Q14::ZERO), @@ -635,7 +682,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], @@ -667,7 +715,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_all(); result.configure_shift_filters(); @@ -755,23 +803,34 @@ impl Resynthesis { } } - /// Quantizes the harmony gain and calculates the stereo pan gains for the + /// Quantizes the linear gain of the lead voice in Harmony mode + /// unconditionally. + fn configure_lead_gain(&mut self) { + self.lead_gain = Q14::from_f64(f64::from(self.config.lead_gain)); + } + + /// Quantizes the voice gains and calculates the stereo pan gains for the /// harmony voices unconditionally. /// - /// The stereo pan gains include the harmony gain. The mono harmony path - /// uses a separate Q14 gain. + /// Each stereo pan gain includes the master harmony gain, the voice gain + /// and the mute. The mono harmony path uses a separate Q14 gain for each + /// voice. fn configure_harmony_gain(&mut self) { - self.harmony_gain = Q14::from_f64(self.config.harmony_gain as f64); - for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] - .into_iter() - .enumerate() - { - let angle: f64 = 1.57079632713 * fraction; - let gain = self.config.harmony_gain as f64; - self.harmony_pan[voice] = [ - Q14::from_f64(gain * angle.cos()), - Q14::from_f64(gain * angle.sin()), - ]; + for voice in 0..HARMONY_VOICES { + if self.config.harmony.voice_mutes[voice] { + self.harmony_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()), + ]; + } } } @@ -787,6 +846,7 @@ impl Resynthesis { self.configure_flex_tune(); self.configure_choir_drift(); self.configure_choir_pan(); + self.configure_lead_gain(); self.configure_harmony_gain(); } @@ -833,8 +893,15 @@ impl Resynthesis { if old.pitch.threshold != config.pitch.threshold { self.pitch.set_config(config.pitch); } - if old.formant != config.formant { - self.formant.set_config(config.formant); + 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, + ); } if old.harmony != config.harmony { self.harmony.apply_config(config.harmony); @@ -865,6 +932,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]; @@ -878,7 +951,14 @@ impl Resynthesis { if old.choir_detune != config.choir_detune { self.configure_choir_drift(); } - if old.harmony_gain != config.harmony_gain { + if old.lead_gain != config.lead_gain { + self.configure_lead_gain(); + } + if old.harmony_gain != config.harmony_gain + || old.harmony.voice_gains != config.harmony.voice_gains + || old.harmony.voice_pans != config.harmony.voice_pans + || old.harmony.voice_mutes != config.harmony.voice_mutes + { self.configure_harmony_gain(); } if old.harmonic_modulation != config.harmonic_modulation { @@ -1127,7 +1207,7 @@ impl Resynthesis { self.harmony.reset(); clear_dirty_ring(self.overlap.as_mut_slice(), written, 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(); } @@ -1546,16 +1626,16 @@ impl Resynthesis { } /// Applies the glottal envelope to `sample` and updates `previous_output` - /// for `channel`. + /// for `slot`. /// - /// `channel` must be `0` or `1`. + /// `slot` must be less than `HARMONY_VOICES + 1`. #[inline] - fn apply_glottal(&mut self, channel: usize, sample: Q14) -> Q14 { + fn apply_glottal(&mut self, slot: usize, sample: Q14) -> Q14 { let output = Q14::from_bits( self.formant - .model_glottal(sample.to_bits(), self.previous_output[channel].to_bits()), + .model_glottal(sample.to_bits(), self.previous_output[slot].to_bits()), ); - self.previous_output[channel] = output; + self.previous_output[slot] = output; output } @@ -1703,7 +1783,7 @@ impl Resynthesis { let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); let dry = self.raw[ring(write as i32 - LATENCY_FRAMES as i32)]; let mut mix = [Q14::ZERO; 2]; - let mut mono = !self.config.stereo_output; + let mono = !self.config.stereo_output; let mut final_ratio = Q14::ONE; if self.config.mode == MultiVoiceMode::Choir { let voice_count = self.config.choir_voices as usize; @@ -1779,6 +1859,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 { @@ -1793,66 +1878,61 @@ 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 { + if slot == 0 && self.config.formant.enabled { + self.formant_position = history::center_of(position) - FORMANT_OFFSET_FRAMES; + } + // 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 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; + 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; } - 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); - } + 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 = self.apply_glottal(slot, value); } - if self.config.stereo_output { - for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if slot > 0 { - value.mul(self.harmony_pan[slot - 1][channel]) - } else { - value - }; + if slot == 0 { + value = value.mul(self.lead_gain); + if self.config.stereo_output { + for sum in &mut mix { + *sum = *sum + value; + } + } else { + mix[0] = mix[0] + value; } } else { - mix[0] = mix[0] + value; - } - } - if self.config.formant.enabled { - self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; - // If Choir changed only channel zero before a switch to - // Harmony, synthesize the two channels until their histories - // are equal. - if mono - && self.formant.histories_match() - && self.previous_output[0] == self.previous_output[1] - { - let value = Q14::from_bits(self.formant.forward_mono( - mix[0].to_bits(), - self.formant_position, - numeric, - )); - let value = self.apply_glottal(0, value); - self.previous_output[1] = value; - mix[0] = value; - } else { - if mono { - mix[1] = mix[0]; - } - 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 = self.apply_glottal(channel, *value); + 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]); + mix[0] = mix[0] + value; } - mono = mono && mix[0] == mix[1]; } } } diff --git a/src/resynthesis/history.rs b/src/resynthesis/history.rs index 6f3cda2..902c4b1 100644 --- a/src/resynthesis/history.rs +++ b/src/resynthesis/history.rs @@ -82,24 +82,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); (quadratic(left, middle, right, fraction), center) diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..a15ba63 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -22,7 +22,13 @@ //! - Enum values are strings. //! - Each object must contain all required fields. //! - The optional correction `humanize` and `flexTune` fields default to 0. +//! - The optional `resynthesis.leadGain` field defaults to 1. //! - The optional harmony `voices` field defaults to 4. +//! - The optional harmony `voiceGains`, `voiceFormantStretch` and +//! `voiceFormantWidth` fields default to `[1, 1, 1, 1]`. +//! - The optional harmony `voicePans` field defaults to `[-1/3, 1/3, -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`. Scalar parameter @@ -708,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 /// @@ -751,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.