diff --git a/README.md b/README.md index a06715f..ce1ae38 100644 --- a/README.md +++ b/README.md @@ -190,21 +190,36 @@ modes keep the stereo dry signal. Set `resynthesis.mode` to `Harmony`. Then select the source of the voices with `resynthesis.harmony.source`: -| Source | The voices follow | -| --------------- | ------------------------------------------------------ | -| `FixedInterval` | A fixed number of semitones from the singer | -| `SmartInterval` | An interval in scale steps, in a key and a scale | -| `ChordByDegree` | A chord on a scale degree | -| `ChordByName` | A named chord, for example `MinorSeventh` | -| `ChordViaMidi` | The active MIDI notes, as a chord | -| `MidiOmni` | MIDI notes from all channels, on the first free voice | -| `MidiChannels` | MIDI channel `n` for voice `n` (channels 0–3), default | +| Source | The voices follow | +| --------------- | ----------------------------------------------------------------- | +| `FixedInterval` | A fixed number of semitones from the singer | +| `SmartInterval` | An interval in scale steps, in a key and a scale | +| `ChordByDegree` | A chord on a scale degree | +| `ChordByName` | A named chord, for example `MinorSeventh` | +| `ChordViaMidi` | The active MIDI notes, as a chord | +| `MidiOmni` | MIDI notes from all channels, on the first free voice | +| `MidiChannels` | MIDI channels from `midi_channel_map` for four voices, default | `resynthesis.harmony.voices` sets the number of interval voices, in `0..=4`. 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. +For `MidiChannels`, `resynthesis.harmony.midi_channel_map` selects `BaseWindow` +(default) or `WrapFour`. `BaseWindow` assigns channels +`midi_base_channel..=midi_base_channel + 3` to the four voices, with +`midi_base_channel` in `0..=12` (default 0). `WrapFour` assigns channel `c` in +`0..=15` to voice `c % 4` and ignores `midi_base_channel`. Other harmony sources +ignore both fields. A 16-channel keybed keeps held notes across live changes +among `MidiOmni`, `ChordViaMidi` and `MidiChannels`. On legato release, a voice +resumes the next newest held note. + +For `ControlEvent::CorrectionMidi`, `resynthesis.correction.midi_mode` selects +`Momentary` (default) or `Latch` across notes `0..=127`. If all keys release in +`Momentary` mode, `resynthesis.correction.notes` loads again. `Latch` keeps the +chord after key release until `MidiEvent::AllNotesOff`, `reset()` or a scale +change. + `resynthesis.harmony_gain` scales the four harmony voices in mono and in stereo. It does not scale the lead voice. @@ -365,8 +380,8 @@ These calls read the state of the processor. They do not change the audio. `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. +control makes no sample change in the active voice mode, harmony source, +channel map or reverb network. The telemetry includes these items: @@ -581,9 +596,12 @@ 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. +`resynthesis.correction.midiMode` defaults to `"momentary"`. +`resynthesis.harmony.voices` defaults to 4, +`resynthesis.harmony.midiChannelMap` defaults to `"baseWindow"` and +`resynthesis.harmony.midiBaseChannel` defaults to 0. 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/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index 0f6a77f..d31d37b 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -73,6 +73,23 @@ const EXACT_REPLACEMENTS = [ ], ["[`crate::HarmonyConfig::portamento_ms`]", "`HarmonyConfig.portamentoMs`"], ["[`crate::HarmonyConfig::voices`]", "`HarmonyConfig.voices`"], + [ + "[`crate::HarmonyConfig::midi_channel_map`]", + "`HarmonyConfig.midiChannelMap`", + ], + ["[`HarmonyConfig::midi_channel_map`]", "`HarmonyConfig.midiChannelMap`"], + [ + "[`crate::HarmonyConfig::midi_base_channel`]", + "`HarmonyConfig.midiBaseChannel`", + ], + ["[`HarmonyConfig::midi_base_channel`]", "`HarmonyConfig.midiBaseChannel`"], + ["[`crate::CorrectionConfig::notes`]", "`CorrectionConfig.notes`"], + ["[`CorrectionConfig::notes`]", "`CorrectionConfig.notes`"], + [ + "[`crate::ControlEvent::CorrectionMidi`]", + '`{ type: "correctionMidi", value }`', + ], + ["[`MidiEvent::AllNotesOff`]", '`{ type: "allNotesOff" }`'], ["[`ReverbConfig::mode`]", "`ReverbConfig.mode`"], ["[`ReverbConfig::mix`]", "`ReverbConfig.mix`"], ["[`ReverbConfig::diffusion`]", "`ReverbConfig.diffusion`"], @@ -85,7 +102,10 @@ const EXACT_REPLACEMENTS = [ ["[`TimedEvent`]", "`TimedEvent`"], ["[`HarmonyScale`]", "`HarmonyScale`"], ["[`Feedback`]", "`Feedback`"], + ["[`crate::HarmonyConfig`]", "`HarmonyConfig`"], ["[`HarmonyConfig`]", "`HarmonyConfig`"], + ["[`MidiChannelMap`]", "`MidiChannelMap`"], + ["[`CorrectionMidiMode`]", "`CorrectionMidiMode`"], [ "[`ControlEvent::Parameter`]", '`{ type: "parameter", value }` in `ControlEvent`', @@ -94,12 +114,20 @@ const EXACT_REPLACEMENTS = [ ["[`Self::I`]", '`"i"`'], ["[`Self::Echo`]", '`"echo"`'], ["[`ReverbMode::Echo`]", '`"echo"`'], + ["[`Self::MidiOmni`]", '`"midiOmni"`'], + ["[`HarmonySource::MidiOmni`]", '`"midiOmni"`'], ["[`Self::MidiChannels`]", '`"midiChannels"`'], ["[`HarmonySource::MidiChannels`]", '`"midiChannels"`'], ["[`HarmonySource::FixedInterval`]", '`"fixedInterval"`'], ["[`HarmonySource::SmartInterval`]", '`"smartInterval"`'], ["[`HarmonySource::ChordByName`]", '`"chordByName"`'], ["[`HarmonySource::ChordByDegree`]", '`"chordByDegree"`'], + ["[`MidiChannelMap::BaseWindow`]", '`"baseWindow"`'], + ["[`MidiChannelMap::WrapFour`]", '`"wrapFour"`'], + ["[`crate::CorrectionMidiMode::Momentary`]", '`"momentary"`'], + ["[`CorrectionMidiMode::Momentary`]", '`"momentary"`'], + ["[`crate::CorrectionMidiMode::Latch`]", '`"latch"`'], + ["[`CorrectionMidiMode::Latch`]", '`"latch"`'], ["[`MultiVoiceMode::Choir`]", '`"choir"`'], ["`None`", "`undefined`"], ["`u64::MAX`", "`2n ** 64n - 1n`"], @@ -108,6 +136,14 @@ const EXACT_REPLACEMENTS = [ ["`min_frequency_hz`", "`minFrequencyHz`"], ["`stereo_output`", "`stereoOutput`"], ["`retune_ms`", "`retuneMs`"], + ["`pitch_ratio`", "`pitchRatio`"], + ["`flex_tune`", "`flexTune`"], + ["`midi_channel_map`", "`midiChannelMap`"], + ["`midi_base_channel..=midi_base_channel + 3`", "`midiBaseChannel..=midiBaseChannel + 3`"], + ["`c - midi_base_channel`", "`c - midiBaseChannel`"], + ["`midi_base_channel + n`", "`midiBaseChannel + n`"], + ["`midi_base_channel`", "`midiBaseChannel`"], + ["`midi_mode`", "`midiMode`"], ["`attack_ms`", "`attackMs`"], ["`gain_db`", "`gainDb`"], ["`ceiling_db`", "`ceilingDb`"], diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..2b2a4d9 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -315,12 +315,18 @@ function verifyRuntimeImport(consumerDir, packageName) { "const initialConfig = rootModule.defaultConfig();", "initialConfig.resynthesis.correction.humanize = undefined;", "initialConfig.resynthesis.correction.flexTune = undefined;", + "initialConfig.resynthesis.correction.midiMode = undefined;", "initialConfig.resynthesis.harmony.voices = undefined;", + "initialConfig.resynthesis.harmony.midiChannelMap = undefined;", + "initialConfig.resynthesis.harmony.midiBaseChannel = undefined;", "const processor = new rootModule.Tunelet(48000, 128, initialConfig);", "try {", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + ' assert.equal(processor.config().resynthesis.correction.midiMode, "momentary");', " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + ' assert.equal(processor.config().resynthesis.harmony.midiChannelMap, "baseWindow");', + " assert.equal(processor.config().resynthesis.harmony.midiBaseChannel, 0);", " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", " const initialTelemetry = processor.telemetry();", " assert.ok(initialTelemetry.voiceRatios instanceof Float32Array);", @@ -354,9 +360,15 @@ function verifyRuntimeImport(consumerDir, packageName) { " const omittedCorrectionConfig = processor.config();", " delete omittedCorrectionConfig.resynthesis.correction.humanize;", " delete omittedCorrectionConfig.resynthesis.correction.flexTune;", + " delete omittedCorrectionConfig.resynthesis.correction.midiMode;", + " delete omittedCorrectionConfig.resynthesis.harmony.midiChannelMap;", + " delete omittedCorrectionConfig.resynthesis.harmony.midiBaseChannel;", " processor.setConfig(omittedCorrectionConfig);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + ' assert.equal(processor.config().resynthesis.correction.midiMode, "momentary");', + ' assert.equal(processor.config().resynthesis.harmony.midiChannelMap, "baseWindow");', + " assert.equal(processor.config().resynthesis.harmony.midiBaseChannel, 0);", "", " const mono = new Int16Array(128);", " const eventResynthesis = processor.config().resynthesis;", @@ -381,6 +393,23 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.dryMix, 0.25);", " assert.equal(processor.config().resynthesis.correction.humanize, 0.5);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", + " assert.equal(processor.controlActivity().harmonyMidiChannelMap, false);", + " assert.equal(processor.controlActivity().harmonyMidiBaseChannel, false);", + " const harmonyActivityConfig = processor.config();", + ' harmonyActivityConfig.resynthesis.mode = "harmony";', + ' harmonyActivityConfig.resynthesis.harmony.source = "midiChannels";', + ' harmonyActivityConfig.resynthesis.harmony.midiChannelMap = "baseWindow";', + " processor.setConfig(harmonyActivityConfig);", + " assert.equal(processor.controlActivity().harmonyMidiChannelMap, true);", + " assert.equal(processor.controlActivity().harmonyMidiBaseChannel, true);", + ' harmonyActivityConfig.resynthesis.harmony.midiChannelMap = "wrapFour";', + " processor.setConfig(harmonyActivityConfig);", + " assert.equal(processor.controlActivity().harmonyMidiChannelMap, true);", + " assert.equal(processor.controlActivity().harmonyMidiBaseChannel, false);", + ' harmonyActivityConfig.resynthesis.harmony.source = "midiOmni";', + " processor.setConfig(harmonyActivityConfig);", + " assert.equal(processor.controlActivity().harmonyMidiChannelMap, false);", + " assert.equal(processor.controlActivity().harmonyMidiBaseChannel, false);", "} finally {", " processor.free();", "}", @@ -738,6 +767,8 @@ function verifyTypeDeclarations(consumerDir, packageName) { " TuneletAudioViews,", " type ControlActivity,", " type ControlEvent,", + " type CorrectionMidiMode,", + " type MidiChannelMap,", " type ParameterControl,", " type ProcessorConfig,", " type ResynthesisConfig,", @@ -778,10 +809,13 @@ function verifyTypeDeclarations(consumerDir, packageName) { " ...baseConfig.resynthesis.correction,", " humanize: optionalVoices,", " flexTune: optionalVoices,", + ' midiMode: optionalVoices === undefined ? undefined : ("latch" satisfies CorrectionMidiMode),', " },", " harmony: {", " ...baseConfig.resynthesis.harmony,", " voices: optionalVoices,", + ' midiChannelMap: optionalVoices === undefined ? undefined : ("wrapFour" satisfies MidiChannelMap),', + " midiBaseChannel: optionalVoices,", " },", " },", " };", @@ -801,6 +835,10 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const processor = new Tunelet(48000, 128, configWithUndefined);", " processor.setConfig(configWithUndefined);", " const activity: ControlActivity = processor.controlActivity();", + " const channelMapFlags: [boolean, boolean] = [", + " activity.harmonyMidiChannelMap,", + " activity.harmonyMidiBaseChannel,", + " ];", " const telemetry: Telemetry = processor.telemetry();", " const voiceSlices: [Float32Array, Float32Array] = [", " telemetry.voiceRatios,", @@ -865,6 +903,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " views.dispose();", " processor.free();", " void activity;", + " void channelMapFlags;", " void voiceSlices;", " void ptrs;", " void stereoOut;", @@ -1156,7 +1195,7 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { ); assert.doesNotMatch( text, - /`(?:max_frequency_hz|min_frequency_hz|stereo_output|retune_ms|attack_ms|gain_db|ceiling_db)`/, + /`(?:max_frequency_hz|min_frequency_hz|stereo_output|retune_ms|midi_channel_map|midi_base_channel|midi_mode|attack_ms|gain_db|ceiling_db)`/, `Unexpected snake_case config field in ${filePath}`, ); } @@ -1211,12 +1250,19 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { )[0].replace(/\s+/g, " "); assert.ok(controlActivityDoc.includes("`ProcessorConfig`")); assert.ok(controlActivityDoc.includes("`Tunelet.controlActivity`")); + assert.ok(controlActivityDoc.includes("channel map")); assert.ok( controlActivityInterfaceMatch[2].includes("`ResynthesisConfig.choirVoices`"), ); assert.ok( controlActivityInterfaceMatch[2].includes("`HarmonyConfig.source`"), ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.midiChannelMap`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.midiBaseChannel`"), + ); assert.ok( controlActivityInterfaceMatch[2].includes("`ReverbConfig.brightnessHz`"), ); diff --git a/src/config.rs b/src/config.rs index 741d08c..e171e0a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -5,7 +5,7 @@ use crate::effects::punch::PunchConfig; use crate::effects::reverb::{ReverbConfig, ReverbMode}; use crate::effects::warm::WarmConfig; use crate::error::{check_range, ConfigProblem}; -use crate::harmony::HarmonySource; +use crate::harmony::{HarmonySource, MidiChannelMap}; use crate::resynthesis::MultiVoiceMode; use crate::Error; use crate::ResynthesisConfig; @@ -210,13 +210,14 @@ 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 mode, harmony source, channel map or reverb network. + /// 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; let harmony = self.resynthesis.mode == MultiVoiceMode::Harmony; let source = self.resynthesis.harmony.source; + let midi_channels = harmony && source == HarmonySource::MidiChannels; let interval = matches!( source, HarmonySource::FixedInterval | HarmonySource::SmartInterval @@ -253,6 +254,9 @@ impl ProcessorConfig { harmony_voicing_spread_percent: harmony && chord, harmony_portamento_ms: harmony && (!interval || interval_voices), harmony_voices: harmony && interval, + harmony_midi_channel_map: midi_channels, + harmony_midi_base_channel: midi_channels + && self.resynthesis.harmony.midi_channel_map == MidiChannelMap::BaseWindow, harmony_gain: harmony && (!interval || interval_voices), reverb_mode: reverb, reverb_mix: reverb, @@ -271,7 +275,7 @@ 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`. +/// source, channel map or reverb network. `Default` sets all flags to `false`. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -312,6 +316,10 @@ pub struct ControlActivity { pub harmony_portamento_ms: bool, /// `true` if [`crate::HarmonyConfig::voices`] is active. pub harmony_voices: bool, + /// `true` if [`crate::HarmonyConfig::midi_channel_map`] is active. + pub harmony_midi_channel_map: bool, + /// `true` if [`crate::HarmonyConfig::midi_base_channel`] is active. + pub harmony_midi_base_channel: bool, /// `true` if [`ResynthesisConfig::harmony_gain`] is active. pub harmony_gain: bool, /// `true` if [`ReverbConfig::mode`] is active. diff --git a/src/events.rs b/src/events.rs index ef07dee..0193370 100644 --- a/src/events.rs +++ b/src/events.rs @@ -235,20 +235,21 @@ pub enum ControlEvent { /// Validation, quantization, state retention and drain cancellation are /// identical to an equivalent stage event. Parameter(ParameterControl), - /// This event sends a note control to the harmony source that - /// [`crate::HarmonyConfig`] selects. + /// This event sends a note control to the MIDI keybed of + /// [`crate::HarmonyConfig`]. /// - /// MIDI-channel mode uses channels 0..=3. Omni mode and MIDI-chord mode - /// combine channels. + /// The keybed records all 16 channels. MIDI-channel mode assigns channels + /// with [`crate::HarmonyConfig::midi_channel_map`]. Omni mode and + /// MIDI-chord mode combine all channels. Midi(MidiEvent), /// This event changes the correction keyboard independently of harmony MIDI. /// - /// While at least one key in 0..=127 is held, the held keys become the - /// active pitch classes. Channels and nonzero velocities do not change the - /// selected classes. When all keys release, or on All Notes Off, the - /// configured mask loads again. If a later change sets new configured - /// notes, or enables or disables correction, the configured mask also - /// loads again. + /// The held keys 0..=127 select the active pitch classes. Channels and + /// nonzero velocities do not change the selected classes. In + /// [`crate::CorrectionMidiMode::Momentary`], when all keys release, the + /// configured [`crate::CorrectionConfig::notes`] load again. In + /// [`crate::CorrectionMidiMode::Latch`], the chord stays active until + /// [`MidiEvent::AllNotesOff`], a reset or a change to `notes` or `enabled`. CorrectionMidi(MidiEvent), /// This event resets immediately before the event frame, with the semantics of /// [`crate::Processor::reset`]. diff --git a/src/harmony.rs b/src/harmony.rs index f2adfe3..3a72e0b 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -37,7 +37,8 @@ const GAIN_RELEASE: Q12 = Q12::from_bits(81); /// sources use the related [`HarmonyConfig`] fields. The MIDI sources use /// [`crate::ControlEvent::Midi`]. The configuration of the sources that are /// not selected is still validated and kept. If the selected source changes, -/// the active MIDI notes release. +/// the keybed projects its held notes onto the new source, and unselected MIDI +/// voices release. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -65,22 +66,41 @@ pub enum HarmonySource { ChordViaMidi, /// A note from any channel goes to the first free voice. If all four /// voices are busy, the note steals the voice with the oldest assignment. - /// The stolen note stays pending until it resumes or until its Note - /// Off. If a Note Off releases a voice, that voice resumes the pending - /// note with the newest assignment. Only a pending note with a positive - /// assignment order can resume. A repeated Note On for an active pitch - /// updates its gain and its assignment order. Note Off matches the pitch - /// on all channels. + /// The stolen note stays in the keybed until it resumes or until its Note + /// Off. If a Note Off releases a voice, that voice resumes the held pitch + /// with the newest assignment. A repeated Note On for an active pitch + /// updates its gain and its assignment order. Note Off releases the note + /// on its channel. MidiOmni, - /// Voice `n` follows MIDI channel `n` for the zero-based channels 0..=3. + /// Voices follow MIDI channels through [`HarmonyConfig::midi_channel_map`] + /// and [`HarmonyConfig::midi_base_channel`]. /// - /// Other valid MIDI channels do not control voices. Each channel has one - /// current note. Note Off releases that note only if the pitch is the - /// same. This is the default. + /// Each voice plays the newest held note across the channels for that + /// voice. If that note stops, the voice resumes the next newest held note + /// on those channels. This is the default. #[default] MidiChannels, } +/// How [`HarmonySource::MidiChannels`] assigns the 16 MIDI channels to the +/// four harmony voices. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum MidiChannelMap { + /// Channel `c` in `midi_base_channel..=midi_base_channel + 3` controls + /// voice `c - midi_base_channel`. Other channels do not control voices. + /// This is the default. + #[default] + BaseWindow, + /// Channel `c` in 0..=15 controls voice `c % 4`. + WrapFour, +} + /// The scale that smart intervals and chords by degree use. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[repr(u8)] @@ -240,6 +260,7 @@ pub enum Inversion { /// - A register of 50%. /// - A closed voicing and zero portamento. /// - Four voices for the interval sources. +/// - [`MidiChannelMap::BaseWindow`] with base channel 0. /// /// These settings configure all sources. Only the fields for the selected /// source change the target notes. Validation always checks all fields. @@ -328,6 +349,31 @@ pub struct HarmonyConfig { tsify(optional, type = "number | undefined") )] pub voices: u8, + /// How [`HarmonySource::MidiChannels`] assigns channels to voices. + /// + /// The default is [`MidiChannelMap::BaseWindow`]. Other harmony sources + /// ignore this field. 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_default"), + tsify(optional, type = "MidiChannelMap | undefined") + )] + pub midi_channel_map: MidiChannelMap, + /// The first MIDI channel of the four-channel window for + /// [`MidiChannelMap::BaseWindow`], 0..=12. + /// + /// The default is 0. In [`HarmonySource::MidiChannels`] with + /// [`MidiChannelMap::BaseWindow`], voice `n` follows + /// `midi_base_channel + n`. Other harmony sources and + /// [`MidiChannelMap::WrapFour`] ignore this field. In JavaScript, the field + /// is optional and an absent or `undefined` value gives 0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default, deserialize_with = "deserialize_default"), + tsify(optional, type = "number | undefined") + )] + pub midi_base_channel: u8, } /// The default count of interval voices: all of them. @@ -343,6 +389,18 @@ fn deserialize_voices<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Resu Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_voices)) } +/// Decodes an optional field and maps an absent or `undefined` value to its +/// default. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +pub(crate) fn deserialize_default<'de, D, T>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, + T: Default + serde::Deserialize<'de>, +{ + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_default()) +} + impl Default for HarmonyConfig { fn default() -> Self { Self { @@ -358,6 +416,8 @@ impl Default for HarmonyConfig { voicing_spread_percent: 0.0, portamento_ms: 0.0, voices: HARMONY_VOICES as u8, + midi_channel_map: MidiChannelMap::BaseWindow, + midi_base_channel: 0, } } } @@ -380,10 +440,135 @@ impl HarmonyConfig { validate_chromatic_intervals(self.chromatic_intervals)?; validate_diatonic_intervals(self.diatonic_intervals)?; validate_voices(self.voices)?; + validate_midi_base_channel(self.midi_base_channel)?; validate_register_percent(self.register_percent)?; validate_voicing_spread_percent(self.voicing_spread_percent)?; validate_portamento_ms(self.portamento_ms) } + + /// If `channel` is in the active window, returns its voice index 0..=3. + fn map_channel(self, channel: u8) -> Option { + match self.midi_channel_map { + MidiChannelMap::WrapFour => Some(usize::from(channel) % HARMONY_VOICES), + MidiChannelMap::BaseWindow => { + let offset = channel.checked_sub(self.midi_base_channel)?; + let voice = usize::from(offset); + (voice < HARMONY_VOICES).then_some(voice) + } + } + } +} + +/// Allocates a 16-channel by 128-note table on the heap and keeps that shape +/// in the boxed-array type. +fn prepare_keybed_table(value: T) -> Box<[[T; 128]; 16]> { + vec![[value; 128]; 16] + .into_boxed_slice() + .try_into() + .unwrap_or_else(|_| unreachable!("prepared MIDI keybed length")) +} + +/// A fixed-size 16-channel by 128-note MIDI keybed. +struct MidiKeybed { + /// Held notes for each channel 0..=15. Bit `n` is note `n` in 0..=127. + held: [u128; 16], + /// Nonzero velocity 1..=127 for each held note on each channel. + velocity: Box<[[u8; 128]; 16]>, + /// Monotonic press order for each held note on each channel. + order: Box<[[u32; 128]; 16]>, + /// Monotonic counter of Note On events. + next_order: u32, +} + +impl MidiKeybed { + /// Returns an empty keybed with heap-allocated velocity and order tables. + fn new() -> Self { + Self { + held: [0; 16], + velocity: prepare_keybed_table(0), + order: prepare_keybed_table(0), + next_order: 0, + } + } + + /// Releases all held notes on all 16 channels. + fn clear(&mut self) { + self.held = [0; 16]; + self.next_order = 0; + } + + /// If `next_order` is `u32::MAX`, renumbers held notes into `1..=count`. + fn compact_orders(&mut self, voice_orders: &mut [u32; HARMONY_VOICES]) { + let mut rank = 0_u32; + let mut floor = 0_u32; + loop { + let mut min_order = u32::MAX; + let mut found = false; + for ch in 0..16 { + let mut bits = self.held[ch]; + while bits != 0 { + let n = bits.trailing_zeros() as usize; + bits &= bits - 1; + let ord = self.order[ch][n]; + if ord > floor && (!found || ord < min_order) { + min_order = ord; + found = true; + } + } + } + if !found { + break; + } + rank += 1; + for ch in 0..16 { + let mut bits = self.held[ch]; + while bits != 0 { + let n = bits.trailing_zeros() as usize; + bits &= bits - 1; + if self.order[ch][n] == min_order { + self.order[ch][n] = rank; + } + } + } + for voice_order in voice_orders.iter_mut() { + if *voice_order == min_order { + *voice_order = rank; + } + } + if min_order == u32::MAX { + break; + } + floor = min_order; + } + self.next_order = rank; + } + + /// Records a MIDI event whose channel, note and velocity are valid. + fn record(&mut self, event: MidiEvent, voice_orders: &mut [u32; HARMONY_VOICES]) { + match event { + MidiEvent::AllNotesOff => self.clear(), + MidiEvent::NoteOn { + channel, + note, + velocity, + } if velocity != 0 => { + if self.next_order == u32::MAX { + self.compact_orders(voice_orders); + } + let ch = usize::from(channel); + let n = usize::from(note); + self.next_order += 1; + self.held[ch] |= 1_u128 << n; + self.velocity[ch][n] = velocity; + self.order[ch][n] = self.next_order; + } + MidiEvent::NoteOn { channel, note, .. } | MidiEvent::NoteOff { channel, note } => { + let ch = usize::from(channel); + let n = usize::from(note); + self.held[ch] &= !(1_u128 << n); + } + } + } } /// Checks the four fixed semitone offsets of harmony. @@ -418,6 +603,16 @@ pub(crate) fn validate_voices(voices: u8) -> Result<(), Error> { ) } +/// Checks the first channel of the four-channel MIDI window. +fn validate_midi_base_channel(midi_base_channel: u8) -> Result<(), Error> { + check_count( + "resynthesis.harmony.midi_base_channel", + i64::from(midi_base_channel), + 0, + 12, + ) +} + /// Checks the range of the chord register. pub(crate) fn validate_register_percent(register_percent: f32) -> Result<(), Error> { check_range( @@ -469,9 +664,8 @@ pub(crate) struct HarmonyState { midi_period: [Q6; HARMONY_VOICES], /// The Q12 velocity gain of each allocated note. midi_gain: [Q12; HARMONY_VOICES], - /// The signed event order of each voice assignment. Voice stealing uses - /// it to find the oldest voice. - midi_order: [i32; HARMONY_VOICES], + /// The monotonic event order of each voice assignment. + midi_order: [u32; HARMONY_VOICES], /// The smoothed Q6 target period. If it is zero, the next active target /// sets it directly. portamento_period: [Q6; HARMONY_VOICES], @@ -512,16 +706,8 @@ pub(crate) struct HarmonyState { /// The Q14 half-life coefficient. The controller applies it one time at /// each voice control step. porta_decay: Q14, - /// The Q12 gain of each stolen note that is still held, by MIDI pitch. - /// - /// Zero marks an inactive entry. - pending_gain: [Q12; 128], - /// The signed assignment order of each pending note. The largest positive - /// value resumes first. - pending_order: [i32; 128], - /// The wrapping i32 counter of Note On and Note Off events. A reset sets - /// it to zero. The note assignment compares its signed values. - event_counter: i32, + /// The 16-channel by 128-note MIDI keybed. + keybed: MidiKeybed, /// The precomputed Q12 velocity gains for all 128 MIDI velocity values. gains: [Q12; 128], } @@ -551,9 +737,7 @@ impl HarmonyState { scale_target: [Q6::ZERO; HARMONY_VOICES], scale_note: [0; HARMONY_VOICES], porta_decay: Q14::ZERO, - pending_gain: [Q12::ZERO; 128], - pending_order: [0; 128], - event_counter: 0, + keybed: MidiKeybed::new(), gains: std::array::from_fn(|i| velocity_gain(i as u8)), }; result.prepare_intervals(); @@ -563,13 +747,21 @@ impl HarmonyState { /// Applies a configuration that validation already accepted. /// - /// If the source changes, the function calls `reset`. It prepares the - /// tables again only for the fields that changed. + /// If the source or the active channel map changes, the function projects + /// the held keybed notes onto the active voices. Unselected voices then + /// decay and held notes stay active. It prepares the tables again only for + /// the fields that changed. pub(crate) fn apply_config(&mut self, config: HarmonyConfig) { let old = self.config; self.config = config; if old.source != config.source { - self.reset(); + self.reproject_keybed(); + } else if config.source == HarmonySource::MidiChannels + && (old.midi_channel_map != config.midi_channel_map + || (config.midi_channel_map == MidiChannelMap::BaseWindow + && old.midi_base_channel != config.midi_base_channel)) + { + self.reproject_channels(); } if old.key != config.key || old.scale != config.scale @@ -628,14 +820,13 @@ impl HarmonyState { pub(crate) fn set_voices(&mut self, voices: u8) { self.config.voices = voices; } - /// Releases all MIDI notes and starts the MIDI assignment order again. + /// Releases all MIDI notes and clears the keybed. /// /// The function clears these items: /// + /// - The 16-channel keybed. /// - The active MIDI periods, which releases the voices. - /// - The pending stolen notes and their assignment orders. /// - The portamento start state. - /// - The MIDI event counter. /// /// It keeps the gain envelopes, the current ratios, the output and target /// periods, the scale tables and the last note numbers, gains and orders. @@ -646,11 +837,9 @@ impl HarmonyState { /// with the gain release. The other chord sources keep their chord /// preparation. pub(crate) fn reset(&mut self) { + self.keybed.clear(); self.midi_period.fill(Q6::ZERO); self.portamento_period.fill(Q6::ZERO); - self.pending_gain.fill(Q12::ZERO); - self.pending_order.fill(0); - self.event_counter = 0; if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); } @@ -775,15 +964,162 @@ impl HarmonyState { index as i32, ) } + /// Projects the held keybed notes onto the voice slots of the active + /// source. + fn reproject_keybed(&mut self) { + match self.config.source { + HarmonySource::MidiOmni | HarmonySource::ChordViaMidi => self.reproject_omni_voices(), + HarmonySource::MidiChannels => self.reproject_channels(), + HarmonySource::FixedInterval + | HarmonySource::SmartInterval + | HarmonySource::ChordByDegree + | HarmonySource::ChordByName => { + self.midi_period.fill(Q6::ZERO); + self.portamento_period.fill(Q6::ZERO); + } + } + } + /// Projects the 16-channel keybed onto up to four omni voices. + fn reproject_omni_voices(&mut self) { + let mut any_held = 0_u128; + for &held in &self.keybed.held { + any_held |= held; + } + let mut selected_note = [0_usize; HARMONY_VOICES]; + let mut selected_gain = [Q12::ZERO; HARMONY_VOICES]; + let mut selected_order = [0_u32; HARMONY_VOICES]; + let mut count = 0_usize; + let mut bits = any_held; + while bits != 0 { + let note = bits.trailing_zeros() as usize; + bits &= bits - 1; + let mut max_order = 0_u32; + let mut max_vel = 0_u8; + for ch in 0..16 { + if (self.keybed.held[ch] & (1_u128 << note)) != 0 { + let order = self.keybed.order[ch][note]; + if order > max_order { + max_order = order; + max_vel = self.keybed.velocity[ch][note]; + } + } + } + let gain = self.gains[usize::from(max_vel)]; + if count < HARMONY_VOICES { + let mut pos = count; + while pos > 0 && selected_order[pos - 1] > max_order { + selected_note[pos] = selected_note[pos - 1]; + selected_gain[pos] = selected_gain[pos - 1]; + selected_order[pos] = selected_order[pos - 1]; + pos -= 1; + } + selected_note[pos] = note; + selected_gain[pos] = gain; + selected_order[pos] = max_order; + count += 1; + } else if max_order > selected_order[0] { + let mut pos = 0; + while pos + 1 < HARMONY_VOICES && selected_order[pos + 1] < max_order { + selected_note[pos] = selected_note[pos + 1]; + selected_gain[pos] = selected_gain[pos + 1]; + selected_order[pos] = selected_order[pos + 1]; + pos += 1; + } + selected_note[pos] = note; + selected_gain[pos] = gain; + selected_order[pos] = max_order; + } + } + let was_active: [bool; HARMONY_VOICES] = + std::array::from_fn(|v| self.midi_period[v] != Q6::ZERO); + let mut voice_kept = [false; HARMONY_VOICES]; + let mut pitch_placed = [false; HARMONY_VOICES]; + for voice in 0..HARMONY_VOICES { + if was_active[voice] { + if let Some(idx) = (0..count) + .find(|&i| !pitch_placed[i] && selected_note[i] as i32 == self.midi_note[voice]) + { + voice_kept[voice] = true; + pitch_placed[idx] = true; + self.midi_gain[voice] = selected_gain[idx]; + self.midi_order[voice] = selected_order[idx]; + } + } + } + for idx in 0..count { + if pitch_placed[idx] { + continue; + } + let voice = if let Some(free) = + (0..HARMONY_VOICES).find(|&v| !voice_kept[v] && !was_active[v]) + { + self.portamento_period[free] = Q6::ZERO; + free + } else { + let mut oldest = None; + for (v, &kept) in voice_kept.iter().enumerate() { + if !kept && oldest.is_none_or(|prev| self.midi_order[v] < self.midi_order[prev]) + { + oldest = Some(v); + } + } + oldest.unwrap_or(0) + }; + self.assign( + voice, + selected_note[idx], + selected_gain[idx], + selected_order[idx], + ); + voice_kept[voice] = true; + } + for (voice, &kept) in voice_kept.iter().enumerate() { + if !kept { + self.midi_period[voice] = Q6::ZERO; + } + } + } + /// Projects the 16-channel keybed onto the four channel-mapped voices. + fn reproject_channels(&mut self) { + let mut best_note = [0_usize; HARMONY_VOICES]; + let mut best_vel = [0_u8; HARMONY_VOICES]; + let mut best_order = [0_u32; HARMONY_VOICES]; + for ch in 0..16 { + let Some(voice) = self.config.map_channel(ch as u8) else { + continue; + }; + let mut bits = self.keybed.held[ch]; + while bits != 0 { + let note = bits.trailing_zeros() as usize; + bits &= bits - 1; + let order = self.keybed.order[ch][note]; + if order > best_order[voice] { + best_order[voice] = order; + best_note[voice] = note; + best_vel[voice] = self.keybed.velocity[ch][note]; + } + } + } + for voice in 0..HARMONY_VOICES { + if best_order[voice] != 0 { + if self.midi_period[voice] == Q6::ZERO { + self.portamento_period[voice] = Q6::ZERO; + } + let gain = self.gains[usize::from(best_vel[voice])]; + self.assign(voice, best_note[voice], gain, best_order[voice]); + } else { + self.midi_period[voice] = Q6::ZERO; + } + } + } /// Applies a MIDI event with channel, note and velocity values that are /// already in range. - /// Returns `true` if resynthesis must make its next control step due. - /// This occurs after a new note assignment and after each Note Off on a - /// channel that the MIDI source uses. The omni sources steal the oldest - /// voice and resume the newest pending note. If two orders are equal, - /// strict comparisons keep the lowest voice index or pitch. Each Note Off - /// clears the pending entry of its pitch. All Notes Off calls `reset` and - /// returns `false`. The gain releases occur at the next control steps. + /// + /// Every event updates the 16-channel keybed. Returns `true` if resynthesis + /// must make its next control step due. This occurs after a new note + /// assignment and after each Note Off on a channel that the MIDI source + /// uses. All Notes Off calls `reset` and returns `false`. The gain releases + /// occur at the next control steps. pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) -> bool { let (channel, note, velocity) = match event { MidiEvent::AllNotesOff => { @@ -794,83 +1130,29 @@ impl HarmonyState { channel, note, velocity, - } => (channel, usize::from(note), i32::from(velocity)), + } => (channel, usize::from(note), velocity), MidiEvent::NoteOff { channel, note } => (channel, usize::from(note), 0), }; - self.event_counter = self.event_counter.wrapping_add(1); - let gain = self.gains[velocity as usize]; - if velocity == 0 { - self.clear_pending(note); - } + self.keybed.record(event, &mut self.midi_order); let control_due = match self.config.source { HarmonySource::MidiOmni | HarmonySource::ChordViaMidi => { - if velocity == 0 { - let mut released = None; - for voice in 0..HARMONY_VOICES { - if self.voice_has_note(voice, note) { - self.midi_period[voice] = Q6::ZERO; - released = Some(voice); - } - } - if let Some(voice) = released { - let mut best_order = 0; - let mut best = None; - for (pending, &order) in self.pending_order.iter().enumerate() { - if order > best_order { - best_order = order; - best = Some(pending); - } - } - if let Some(pending) = best { - let pending_gain = self.pending_gain[pending]; - self.assign(voice, pending, pending_gain, best_order); - self.clear_pending(pending); - } - } - true - } else if let Some(voice) = - (0..HARMONY_VOICES).find(|&v| self.voice_has_note(v, note)) - { - self.midi_gain[voice] = gain; - self.midi_order[voice] = self.event_counter; - false - } else { - let voice = if let Some(free) = - (0..HARMONY_VOICES).find(|&v| self.midi_period[v] == Q6::ZERO) - { - self.portamento_period[free] = Q6::ZERO; - free - } else { - let mut oldest = 0; - for i in 1..HARMONY_VOICES { - if self.midi_order[i] < self.midi_order[oldest] { - oldest = i; - } - } - let stolen = self.midi_note[oldest] as usize; - self.pending_gain[stolen] = self.midi_gain[oldest]; - self.pending_order[stolen] = self.midi_order[oldest]; - oldest - }; - self.assign(voice, note, gain, self.event_counter); - true - } + let already_active = + velocity != 0 && (0..HARMONY_VOICES).any(|v| self.voice_has_note(v, note)); + self.reproject_omni_voices(); + !already_active } - HarmonySource::MidiChannels if channel < 4 => { - let voice = usize::from(channel); - if velocity == 0 { - if self.voice_has_note(voice, note) { - self.midi_period[voice] = Q6::ZERO; - } + HarmonySource::MidiChannels => { + if self.config.map_channel(channel).is_some() { + self.reproject_channels(); + true } else { - if self.midi_period[voice] == Q6::ZERO { - self.portamento_period[voice] = Q6::ZERO; - } - self.assign(voice, note, gain, self.event_counter); + false } - true } - _ => false, + HarmonySource::FixedInterval + | HarmonySource::SmartInterval + | HarmonySource::ChordByDegree + | HarmonySource::ChordByName => false, }; if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); @@ -881,13 +1163,8 @@ impl HarmonyState { fn voice_has_note(&self, voice: usize, note: usize) -> bool { self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 } - /// Clears the stolen-note state of `note`. - fn clear_pending(&mut self, note: usize) { - self.pending_gain[note] = Q12::ZERO; - self.pending_order[note] = 0; - } /// Assigns a validated MIDI pitch, gain and event order to a voice. - fn assign(&mut self, voice: usize, note: usize, gain: Q12, order: i32) { + fn assign(&mut self, voice: usize, note: usize, gain: Q12, order: u32) { self.midi_period[voice] = self.cents_period(f64::from((note as i32 - 60) * 100)); self.midi_note[voice] = note as i32; self.midi_gain[voice] = gain; diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..44d379e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,10 +143,11 @@ pub use error::{ConfigProblem, Error, EventProblem}; pub use events::{ControlEvent, ParameterControl, TimedEvent}; pub use formant::FormantConfig; pub use harmony::{ - ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, + ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, MidiChannelMap, + HARMONY_VOICES, }; pub use midi::MidiEvent; pub use pitch::PitchConfig; pub use processor::{Feedback, Processor, Telemetry}; pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig}; -pub use scale::{CorrectionScale, NoteMask, PitchClass}; +pub use scale::{CorrectionMidiMode, CorrectionScale, NoteMask, PitchClass}; diff --git a/src/midi.rs b/src/midi.rs index 188dec5..45fffee 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -37,12 +37,12 @@ pub enum MidiEvent { }, /// All notes stop (controller 123). /// - /// For harmony, it clears the active MIDI assignments and the stolen notes - /// that are still held, on all channels. In MIDI-chord mode, it also - /// releases the chord voices. The gain envelopes do not change, so the - /// released voices decay. The prepared targets of the named and degree - /// chord sources do not change. For the correction keyboard, it clears - /// keys 0..=127 and loads the configured correction notes again. + /// For harmony, it clears the MIDI keybed on all channels and releases the + /// active MIDI voices. In MIDI-chord mode, it also releases the chord + /// voices. The gain envelopes do not change, so the released voices decay. + /// The prepared targets of the named and degree chord sources do not + /// change. For the correction keyboard, it clears keys 0..=127 and any + /// latched chord, and loads [`crate::CorrectionConfig::notes`] again. AllNotesOff, } diff --git a/src/processor.rs b/src/processor.rs index 9f8ae9b..53148d8 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 mode, harmony source, channel map or reverb network. + /// This method does not allocate memory and does not change state. pub fn control_activity(&self) -> ControlActivity { self.config.control_activity() } @@ -739,9 +739,10 @@ impl Processor { /// /// This method cancels an active drain. It also clears the correction /// ratio, the Punch envelopes, the Warm filters, the Alien recording and - /// the reverb delays. It releases the harmony MIDI notes and, in - /// MIDI-chord mode, the chord voices. It releases correction keys 0..=127 - /// and loads the configured correction notes again. It keeps these items: + /// the reverb delays. It clears the harmony MIDI keybed and releases the + /// active MIDI voices and chord voices. It releases correction keys 0..=127, + /// clears any latched correction chord and loads the configured correction + /// notes again. It keeps these items: /// /// - the configuration /// - the random stream and the arctangent lookup position of Punch diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..bc21558 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -38,7 +38,7 @@ use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; use crate::numeric::{clamp_i32, quadratic, ring, NumericContext, HISTORY}; use crate::pitch::tracker::PitchTracker; use crate::pitch::{PitchConfig, PitchEstimate}; -use crate::scale::{CorrectionTable, NoteMask}; +use crate::scale::{CorrectionMidiMode, CorrectionTable, NoteMask}; use crate::{Error, SampleRate}; use history::{clear_dirty_ring, prepare_history, record_history}; @@ -62,17 +62,19 @@ pub enum MultiVoiceMode { /// period domain. /// /// Correction is enabled by default, with all chromatic notes, a retune time -/// of zero, zero humanize and zero flex-tune. Target selection and the -/// smoothing of the correction ratio occur at each update of the pitch -/// tracking. When a period is tracked, this update usually occurs every five -/// frames. If the active note table is empty or correction is disabled, the -/// ratio moves toward 1.0 with `retune_ms`. +/// of zero, zero humanize, zero flex-tune and momentary MIDI mode. Target +/// selection and the smoothing of the correction ratio occur at each update of +/// the pitch tracking. When a period is tracked, this update usually occurs +/// every five frames. If the active note table is empty or correction is +/// disabled, the ratio moves toward 1.0 with `retune_ms`. /// -/// While at least one key in 0..=127 is held, correction MIDI replaces the -/// active note table. It does not change this configuration. When all keys -/// release, on All Notes Off or on reset, the configured `notes` load again. -/// A change to `notes` or to `enabled` also loads the configured mask again. -/// Reset releases the correction keys 0..=127. +/// Correction MIDI replaces the active note table. It does not change this +/// configuration. In [`CorrectionMidiMode::Momentary`], when all keys in +/// 0..=127 release, the configured `notes` load again. In +/// [`CorrectionMidiMode::Latch`], a chord stays active until +/// [`MidiEvent::AllNotesOff`], a reset or a scale change. A change to `notes` +/// or to `enabled` also loads the configured mask again. Reset releases the +/// correction keys 0..=127 and clears any latched chord. /// /// Construction loads the configured `notes` mask with the periods for the /// prepared sample rate. Later changes to `notes`, to `enabled` or from @@ -94,9 +96,10 @@ pub struct CorrectionConfig { /// The configured target pitch classes. The default is /// [`NoteMask::CHROMATIC`]. /// - /// All boolean masks are valid. Held keys from correction MIDI replace the - /// active table. When all keys release, or if this mask or `enabled` - /// changes, this mask loads again. + /// All boolean masks are valid. Correction MIDI can replace the active + /// table. In [`CorrectionMidiMode::Momentary`], when all keys release, + /// this mask loads again. In [`CorrectionMidiMode::Latch`], All Notes Off, + /// a reset or a change to this mask or `enabled` loads it again. pub notes: NoteMask, /// The half-life of the smoothing in milliseconds, 0..=400. The default /// is 0. @@ -135,6 +138,16 @@ pub struct CorrectionConfig { tsify(optional, type = "number | undefined") )] pub flex_tune: f32, + /// How [`crate::ControlEvent::CorrectionMidi`] keeps or releases notes. + /// + /// The default is [`CorrectionMidiMode::Momentary`]. 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 = "crate::harmony::deserialize_default"), + tsify(optional, type = "CorrectionMidiMode | undefined") + )] + pub midi_mode: CorrectionMidiMode, } /// Decodes an optional correction control and maps an absent value to 0. @@ -154,6 +167,7 @@ impl Default for CorrectionConfig { retune_ms: 0.0, humanize: 0.0, flex_tune: 0.0, + midi_mode: CorrectionMidiMode::default(), } } } @@ -161,10 +175,10 @@ impl Default for CorrectionConfig { impl CorrectionConfig { /// Validates all fields, also if correction is disabled. /// - /// All values of `enabled` and `notes` are valid. `retune_ms`, `humanize` - /// and `flex_tune` must be finite and in their documented inclusive ranges. - /// Validation does not clamp values. It does not change the state of the - /// processor. + /// All values of `enabled`, `notes` and `midi_mode` are valid. `retune_ms`, + /// `humanize` and `flex_tune` must be finite and in their documented + /// inclusive ranges. Validation does not clamp values. It does not change + /// the state of the processor. /// /// # Errors /// @@ -842,7 +856,14 @@ impl Resynthesis { if old.correction.notes != config.correction.notes || old.correction.enabled != config.correction.enabled { - self.scale.set_notes(config.correction.notes); + self.scale.clear_override(config.correction.notes); + self.scale_initialized = false; + self.dwell = Q14::ZERO; + } else if old.correction.midi_mode != config.correction.midi_mode + && self + .scale + .apply_mode(config.correction.midi_mode, config.correction.notes) + { self.scale_initialized = false; self.dwell = Q14::ZERO; } else if config.correction.humanize == 0.0 { @@ -1079,8 +1100,8 @@ impl Resynthesis { } } - /// Releases the correction keys 0..=127, loads the configured correction - /// notes again and resets the audio state. + /// Releases the correction keys 0..=127, clears any latched chord, loads + /// the configured correction notes again and resets the audio state. /// /// The items that `reset_audio` keeps do not change, except the correction /// keyboard and the active note table. @@ -1156,10 +1177,14 @@ impl Resynthesis { /// Applies a correction MIDI event that the API or the block code checked /// before. pub(crate) fn apply_correction_midi(&mut self, event: MidiEvent) { - self.scale - .apply_validated_midi(event, self.config.correction.notes); - self.scale_initialized = false; - self.dwell = Q14::ZERO; + if self.scale.apply_validated_midi( + event, + self.config.correction.midi_mode, + self.config.correction.notes, + ) { + self.scale_initialized = false; + self.dwell = Q14::ZERO; + } } /// Returns the finite number of frames for a drain of resynthesis. diff --git a/src/scale.rs b/src/scale.rs index aa489cc..73c2a58 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -81,6 +81,24 @@ pub enum CorrectionScale { Chromatic, } +/// How [`crate::ControlEvent::CorrectionMidi`] keeps or releases notes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum CorrectionMidiMode { + /// Held MIDI keys replace the configured scale until all keys in 0..=127 + /// release. This is the default. + #[default] + Momentary, + /// A MIDI chord stays active after its keys release until All Notes Off, a + /// reset or a scale change. + Latch, +} + /// The permitted correction pitch classes, in the order C, C♯, D, D♯, E, F, /// F♯, G, G♯, A, A♯, B. /// @@ -140,6 +158,26 @@ impl NoteMask { } } +/// The bits for pitch class C across MIDI notes 0..=127. +const CLASS_C_NOTES: u128 = (1 << 0) + | (1 << 12) + | (1 << 24) + | (1 << 36) + | (1 << 48) + | (1 << 60) + | (1 << 72) + | (1 << 84) + | (1 << 96) + | (1 << 108) + | (1 << 120); + +/// Converts a 128-note bitmask into its twelve pitch-class flags. +fn mask_from_bits(bits: u128) -> NoteMask { + NoteMask(std::array::from_fn(|class| { + (bits & (CLASS_C_NOTES << class)) != 0 + })) +} + /// The prepared correction periods and the arithmetic midpoint boundaries. pub(crate) struct CorrectionTable { /// The number of active targets. @@ -163,7 +201,11 @@ pub(crate) struct CorrectionTable { /// again from these periods. base_periods: [i32; 12], /// The held MIDI keys 0..=127. - pub keyboard: [bool; 128], + keyboard: u128, + /// The latched MIDI keys 0..=127 for [`CorrectionMidiMode::Latch`]. + latched: u128, + /// If `true`, correction MIDI currently replaces the configured notes. + midi_active: bool, } impl CorrectionTable { @@ -175,7 +217,9 @@ impl CorrectionTable { midpoints: [0; 13], notes: [0; 12], base_periods: [0; 12], - keyboard: [false; 128], + keyboard: 0, + latched: 0, + midi_active: false, }; result.set_sample_rate(rate); result.set_notes(mask); @@ -226,33 +270,98 @@ impl CorrectionTable { self.midpoints[0] = self.midpoints[self.count] / 2; } } - /// Releases keys 0..=127 and loads `notes` again. - pub(crate) fn reset(&mut self, notes: NoteMask) { - self.keyboard.fill(false); - self.set_notes(notes); + /// Clears any latched chord and loads the configured `fallback` mask. + pub(crate) fn clear_override(&mut self, fallback: NoteMask) { + self.latched = 0; + self.midi_active = false; + self.set_notes(fallback); + } + /// Updates the active table for a new `mode`, and returns `true` if the + /// active target table changed. + pub(crate) fn apply_mode(&mut self, mode: CorrectionMidiMode, fallback: NoteMask) -> bool { + match mode { + CorrectionMidiMode::Momentary => { + self.latched = 0; + if self.keyboard == 0 { + if self.midi_active { + self.midi_active = false; + self.set_notes(fallback); + return true; + } + } else { + self.midi_active = true; + self.set_notes(mask_from_bits(self.keyboard)); + return true; + } + false + } + CorrectionMidiMode::Latch => { + if self.keyboard != 0 { + self.latched = self.keyboard; + self.midi_active = true; + self.set_notes(mask_from_bits(self.latched)); + return true; + } + false + } + } } - /// Applies an event whose MIDI ranges were already checked. + /// Releases all keys 0..=127 and, if correction MIDI was active, loads + /// `fallback` again. /// - /// If no key in 0..=127 is held, this method loads `notes` again. - pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent, notes: NoteMask) { + /// If correction MIDI was not active, the prepared target table does not + /// load again. + pub(crate) fn reset(&mut self, fallback: NoteMask) { + self.keyboard = 0; + self.latched = 0; + if self.midi_active { + self.midi_active = false; + self.set_notes(fallback); + } + } + /// Applies an event whose MIDI ranges were already checked, and returns + /// `true` if the active target table changed. + pub(crate) fn apply_validated_midi( + &mut self, + event: MidiEvent, + mode: CorrectionMidiMode, + fallback: NoteMask, + ) -> bool { match event { - MidiEvent::NoteOn { note, velocity, .. } => { - self.keyboard[usize::from(note)] = velocity != 0 + MidiEvent::NoteOn { note, velocity, .. } if velocity != 0 => { + let bit = 1_u128 << note; + let was_empty = self.keyboard == 0; + self.keyboard |= bit; + self.latched = if was_empty { bit } else { self.latched | bit }; + self.midi_active = true; + let active = match mode { + CorrectionMidiMode::Momentary => self.keyboard, + CorrectionMidiMode::Latch => self.latched, + }; + self.set_notes(mask_from_bits(active)); + true + } + MidiEvent::NoteOn { note, .. } | MidiEvent::NoteOff { note, .. } => { + self.keyboard &= !(1_u128 << note); + if mode == CorrectionMidiMode::Momentary { + if self.keyboard == 0 { + self.midi_active = false; + self.set_notes(fallback); + } else { + self.midi_active = true; + self.set_notes(mask_from_bits(self.keyboard)); + } + return true; + } + false } - MidiEvent::NoteOff { note, .. } => self.keyboard[usize::from(note)] = false, MidiEvent::AllNotesOff => { - self.reset(notes); - return; + self.keyboard = 0; + self.latched = 0; + self.midi_active = false; + self.set_notes(fallback); + true } } - let mut mask = [false; 12]; - for (i, &held) in self.keyboard.iter().enumerate() { - mask[i % 12] |= held; - } - if mask == [false; 12] { - self.set_notes(notes); - } else { - self.set_notes(NoteMask(mask)); - } } } diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..de5374f 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -21,8 +21,11 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. -//! - The optional correction `humanize` and `flexTune` fields default to 0. -//! - The optional harmony `voices` field defaults to 4. +//! - If an optional field is absent or `undefined`, it gets its default. +//! - The optional correction `humanize` and `flexTune` fields default to 0, +//! and `midiMode` defaults to `"momentary"`. +//! - The optional harmony `voices` field defaults to 4, `midiChannelMap` +//! defaults to `"baseWindow"` and `midiBaseChannel` defaults to 0. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. Scalar parameter @@ -708,8 +711,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 mode, harmony source, channel map or reverb network. + /// The audio state does not change. /// /// # Errors ///