From 57cbbc798603fb66b655bbb629d616af49837fe4 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:04:22 +0000 Subject: [PATCH 1/2] feat(midi): add MIDI keybed, channel map and latch - Set SmartInterval as the default harmony source with two voices - Set musical default intervals for diatonic and chromatic harmony - Record all 16 MIDI channels and 128 notes in a fixed-size keybed - Project held keybed notes across live MIDI source transitions - Add MidiChannelMap and midi_base_channel with legato note fallback - Add ignored_midi_events and correction_midi_active to Telemetry - Use a u128 bitmask for correction MIDI notes 0..=127 - Add CorrectionMidiMode with Momentary and Latch scale control - Export the new types and optional fields to WebAssembly and README --- README.md | 50 +++-- src/events.rs | 20 +- src/harmony.rs | 518 +++++++++++++++++++++++++++++++-------------- src/lib.rs | 5 +- src/midi.rs | 12 +- src/processor.rs | 29 ++- src/resynthesis.rs | 65 ++++-- src/scale.rs | 155 ++++++++++++-- src/wasm.rs | 4 +- 9 files changed, 630 insertions(+), 228 deletions(-) diff --git a/README.md b/README.md index d2993dc..460a25f 100644 --- a/README.md +++ b/README.md @@ -179,20 +179,34 @@ dry path starts after Warm and has a delay of 1,543 frames. 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, default | +| `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 mapped through `midi_channel_map` to four voices | `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. +The default is 2, with diatonic intervals `[2, -2, 4, -4]` and chromatic +intervals `[4, -5, 7, -12]`. `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 `WrapFour` +(default, channel `c` in `0..=15` maps to voice `c % 4`) or `BaseWindow` +(channels `midi_base_channel..midi_base_channel + 4`, where `midi_base_channel` +is in `0..=12` and defaults to 0). A 16-channel keybed keeps held notes across +live switches among `MidiOmni`, `ChordViaMidi` and `MidiChannels`, and resumes +held notes on legato release. + +For `ControlEvent::CorrectionMidi`, `resynthesis.correction.midi_mode` selects +`Momentary` (default) or `Latch` across notes `0..=127`. `Momentary` restores +`resynthesis.correction.notes` when all keys release. `Latch` keeps the last +chord after key release until `MidiEvent::AllNotesOff`, `reset()` or a scale +change. ## Process audio @@ -302,6 +316,8 @@ The telemetry includes these items: signal. - The pitch clarity, which is a confidence score from 0 to 1. - The current gains of Punch and Warm, and the position in the Alien loop. +- The count of ignored harmony MIDI events and whether correction MIDI is + active. The peak windows of the telemetry are independent of the peak window of the feedback. The latency is nominal. Dry mixes, resampled voices and effects @@ -444,10 +460,12 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +JavaScript `Error`. Optional fields use their defaults if absent: +`resynthesis.harmony.voices` (`2`), `resynthesis.harmony.midiChannelMap` +(`"wrapFour"`), `resynthesis.harmony.midiBaseChannel` (`0`) and +`resynthesis.correction.midiMode` (`"momentary"`). The conversion ignores extra +object properties. The generated declarations contain the parameter +documentation from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/src/events.rs b/src/events.rs index e1c975c..3bf8385 100644 --- a/src/events.rs +++ b/src/events.rs @@ -40,19 +40,21 @@ pub enum ControlEvent { /// The quantization and the mute behavior are the same as for /// [`ProcessorConfig::output_gain`]. The value must be finite. OutputGain(f32), - /// 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 maps 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. /// - /// The held notes 0..=126 become pitch classes. Channels and nonzero - /// velocities do not change the selected classes. Key 127 is stored, but - /// the classes do not include it. Each event replaces the active - /// correction table. If a later change sets new configured notes, or - /// enables or disables correction, the configured mask loads again. + /// The held notes 0..=127 become 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 scale change. 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 67b7111..2cf24e4 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -34,7 +34,7 @@ const GAIN_RELEASE: Q12 = Q12::from_bits(81); /// The source of target periods for the four harmony voices. /// -/// The default is [`Self::MidiChannels`]. The static interval and chord +/// The default is [`Self::SmartInterval`]. The static interval and chord /// 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. @@ -49,7 +49,9 @@ pub enum HarmonySource { /// uses `chromatic_intervals`. FixedInterval, /// Each voice follows an interval in scale steps from the singer. This - /// source uses `diatonic_intervals`, `key` and `scale`. + /// source uses `diatonic_intervals`, `key` and `scale`. This is the + /// default. + #[default] SmartInterval, /// The voices sing a chord on a scale degree. This source uses `degree`, /// `key`, `scale` and `inversion`. @@ -65,22 +67,38 @@ 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. - #[default] + /// Each voice plays the newest held note across the channels mapped to it. + /// When that note stops, the voice resumes the next newest held note on + /// its mapped channels. MidiChannels, } +/// How [`HarmonySource::MidiChannels`] maps the 16 MIDI channels to the four +/// harmony voices. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[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 0..=15 maps to voice `c % 4`. This is the default. + #[default] + WrapFour, + /// Channel `c` in `midi_base_channel..midi_base_channel + 4` maps to + /// voice `c - midi_base_channel`. Other channels do not control voices. + BaseWindow, +} + /// The scale that smart intervals and chords by degree use. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[repr(u8)] @@ -233,13 +251,15 @@ pub enum Inversion { /// /// Positive intervals make the pitch higher. The defaults are: /// -/// - MIDI channels 0..=3 as the source. +/// - Smart intervals as the source. /// - The key of C and the major scale. -/// - Unison intervals. +/// - Chromatic intervals `[4, -5, 7, -12]` and diatonic intervals +/// `[2, -2, 4, -4]`. /// - A tonic major chord in root position. /// - A register of 50%. /// - A closed voicing and zero portamento. -/// - Four voices for the interval sources. +/// - Two voices for the interval sources. +/// - [`MidiChannelMap::WrapFour`] 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. @@ -261,7 +281,7 @@ pub enum Inversion { serde(rename_all = "camelCase") )] pub struct HarmonyConfig { - /// The pitch source. The default is [`HarmonySource::MidiChannels`]. + /// The pitch source. The default is [`HarmonySource::SmartInterval`]. pub source: HarmonySource, /// The pitch class of the tonic. The default is C. Smart intervals, named /// chords and degree chords use it. It does not transpose direct MIDI @@ -269,17 +289,17 @@ pub struct HarmonyConfig { pub key: PitchClass, /// The scale for smart intervals and degree chords. The default is major. pub scale: HarmonyScale, - /// Four fixed semitone offsets, each in -24..=24. The default is all - /// zeros. [`HarmonySource::FixedInterval`] uses them. A value of 12 makes - /// the pitch one octave higher. + /// Four fixed semitone offsets, each in -24..=24. The default is + /// `[4, -5, 7, -12]`. [`HarmonySource::FixedInterval`] uses them. A value + /// of 12 makes the pitch one octave higher. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), tsify(type = "[number, number, number, number]") )] pub chromatic_intervals: [i8; HARMONY_VOICES], - /// Four offsets in scale steps, each in -14..=14. The default is all - /// zeros. [`HarmonySource::SmartInterval`] uses them. Seven steps make - /// the pitch one octave higher. + /// Four offsets in scale steps, each in -14..=14. The default is + /// `[2, -2, 4, -4]`. [`HarmonySource::SmartInterval`] uses them. Seven + /// steps make the pitch one octave higher. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), tsify(type = "[number, number, number, number]") @@ -317,7 +337,7 @@ pub struct HarmonyConfig { pub portamento_ms: f32, /// The number of voices that sound in the interval sources, 0..=4. /// - /// The default is 4. [`HarmonySource::FixedInterval`] and + /// The default is 2. [`HarmonySource::FixedInterval`] and /// [`HarmonySource::SmartInterval`] use the first `voices` voices. The /// other voices release with the usual gain envelope. The chord and MIDI /// sources ignore this field. In JavaScript, the field is optional and @@ -328,29 +348,54 @@ pub struct HarmonyConfig { tsify(optional) )] pub voices: u8, + /// How [`HarmonySource::MidiChannels`] maps channels to voices. + /// + /// The default is [`MidiChannelMap::WrapFour`]. Other harmony sources + /// ignore this field. In JavaScript, the field is optional and an absent + /// value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub midi_channel_map: MidiChannelMap, + /// The first MIDI channel of the four-channel window for + /// [`MidiChannelMap::BaseWindow`], 0..=12. + /// + /// The default is 0. Voice `n` follows `midi_base_channel + n`. Validation + /// checks this range for all sources and channel maps. In JavaScript, the + /// field is optional and an absent value gives 0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub midi_base_channel: u8, } -/// The default count of interval voices: all of them. +/// The default count of interval voices: two. #[cfg(all(feature = "wasm", target_arch = "wasm32"))] fn default_voices() -> u8 { - HARMONY_VOICES as u8 + 2 } impl Default for HarmonyConfig { fn default() -> Self { Self { - source: HarmonySource::MidiChannels, + source: HarmonySource::SmartInterval, key: PitchClass::C, scale: HarmonyScale::Major, - chromatic_intervals: [0; HARMONY_VOICES], - diatonic_intervals: [0; HARMONY_VOICES], + chromatic_intervals: [4, -5, 7, -12], + diatonic_intervals: [2, -2, 4, -4], chord: ChordName::Major, degree: ChordDegree::I, inversion: Inversion::Root, register_percent: 50.0, voicing_spread_percent: 0.0, portamento_ms: 0.0, - voices: HARMONY_VOICES as u8, + voices: 2, + midi_channel_map: MidiChannelMap::WrapFour, + midi_base_channel: 0, } } } @@ -380,6 +425,8 @@ impl HarmonyConfig { } let field = "resynthesis.harmony.voices"; check_count(field, i64::from(self.voices), 0, HARMONY_VOICES as i64)?; + let field = "resynthesis.harmony.midi_base_channel"; + check_count(field, i64::from(self.midi_base_channel), 0, 12)?; let field = "resynthesis.harmony.register_percent"; check_range(field, self.register_percent, 0.0, 100.0)?; let field = "resynthesis.harmony.voicing_spread_percent"; @@ -391,6 +438,73 @@ impl HarmonyConfig { 10_000.0, ) } + + /// Maps a zero-based MIDI channel 0..=15 to a voice index 0..=3, or + /// returns `None` if the channel is outside the active window. + 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) + } + } + } +} + +/// 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: [[u8; 128]; 16], + /// Monotonic press order for each held note on each channel. + order: [[u64; 128]; 16], + /// Monotonic counter of Note On events. + next_order: u64, +} + +impl MidiKeybed { + /// Returns an empty keybed with no held notes. + fn new() -> Self { + Self { + held: [0; 16], + velocity: [[0; 128]; 16], + order: [[0; 128]; 16], + next_order: 0, + } + } + + /// Releases all held notes on all 16 channels. + fn clear(&mut self) { + self.held = [0; 16]; + self.next_order = 0; + } + + /// Records a MIDI event whose channel, note and velocity are valid. + fn record(&mut self, event: MidiEvent) { + match event { + MidiEvent::AllNotesOff => self.clear(), + MidiEvent::NoteOn { + channel, + note, + velocity, + } if velocity != 0 => { + 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); + } + } + } } /// The prepared controller of periods and gains, and the MIDI allocator, for @@ -414,9 +528,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: [u64; HARMONY_VOICES], /// The smoothed Q6 target period. If it is zero, the next active target /// sets it directly. portamento_period: [Q6; HARMONY_VOICES], @@ -457,16 +570,11 @@ 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 count of validated harmony MIDI events ignored by the active source + /// or channel map. + ignored_midi_events: u32, /// The precomputed Q12 velocity gains for all 128 MIDI velocity values. gains: [Q12; 128], } @@ -496,9 +604,8 @@ 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(), + ignored_midi_events: 0, gains: std::array::from_fn(|i| velocity_gain(i as u8)), }; result.prepare_intervals(); @@ -506,24 +613,30 @@ impl HarmonyState { result } + /// Returns the count of ignored harmony MIDI events since reset. + pub(crate) fn ignored_midi_events(&self) -> u32 { + self.ignored_midi_events + } + + /// Clears the count of ignored harmony MIDI events on a processor reset. + pub(crate) fn reset_ignored_midi_events(&mut self) { + self.ignored_midi_events = 0; + } + /// Applies a configuration that validation already accepted. /// - /// If the source changes to an interval source or to a named or degree - /// chord source, the function calls `reset`. It prepares the tables - /// again only for the fields that changed. + /// If the source or the channel map changes, the function projects the + /// held keybed notes onto the new source so unselected voices 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 - && matches!( - config.source, - HarmonySource::FixedInterval - | HarmonySource::SmartInterval - | HarmonySource::ChordByDegree - | HarmonySource::ChordByName - ) + || old.midi_channel_map != config.midi_channel_map + || old.midi_base_channel != config.midi_base_channel { - self.reset(); + self.reproject_keybed(); } if old.key != config.key || old.scale != config.scale @@ -543,14 +656,13 @@ impl HarmonyState { self.setup_chord(); } } - /// 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. @@ -561,11 +673,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(); } @@ -694,125 +804,225 @@ impl HarmonyState { index as i32, ) } - /// 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 in - /// the omni sources. 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. - pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) -> bool { - let (channel, note, velocity) = match event { - MidiEvent::AllNotesOff => { - self.reset(); - return false; + /// 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); } - MidiEvent::NoteOn { - channel, - note, - velocity, - } => (channel, usize::from(note), i32::from(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.pending_gain[note] = Q12::ZERO; - self.pending_order[note] = 0; - } - if matches!( - self.config.source, - HarmonySource::MidiOmni | HarmonySource::ChordViaMidi - ) { - if velocity == 0 { - let mut released = None; - for voice in 0..HARMONY_VOICES { - if self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 { - self.midi_period[voice] = Q6::ZERO; - released = Some(voice); + } + } + /// Projects the 16-channel keybed onto up to four omni voices. + fn reproject_omni_voices(&mut self) { + let mut any_held = 0_u128; + for ch in 0..16 { + any_held |= self.keybed.held[ch]; + } + let mut selected_note = [0_usize; HARMONY_VOICES]; + let mut selected_gain = [Q12::ZERO; HARMONY_VOICES]; + let mut selected_order = [0_u64; 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_u64; + 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]; } } - if let Some(voice) = released { - let mut best_order = 0; - let mut best = None; - for pending in 0..128 { - if self.pending_order[pending] > best_order { - best_order = self.pending_order[pending]; - best = Some(pending); - } - } - if let Some(pending) = best { - self.midi_period[voice] = note_period(self.rate, pending as i32); - self.midi_note[voice] = pending as i32; - self.midi_gain[voice] = self.pending_gain[pending]; - self.midi_order[voice] = self.pending_order[pending]; - self.pending_gain[pending] = Q12::ZERO; - self.pending_order[pending] = 0; - } + } + 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; } - if self.config.source == HarmonySource::ChordViaMidi { - self.setup_chord(); + 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; } - return true; + selected_note[pos] = note; + selected_gain[pos] = gain; + selected_order[pos] = max_order; } - for voice in 0..HARMONY_VOICES { - if self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 { - self.midi_gain[voice] = gain; - self.midi_order[voice] = self.event_counter; - if self.config.source == HarmonySource::ChordViaMidi { - self.setup_chord(); - } - return false; + } + 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| self.midi_period[v] == Q6::ZERO) + (0..HARMONY_VOICES).find(|&v| !voice_kept[v] && !was_active[v]) { self.portamento_period[free] = Q6::ZERO; free } else { - let mut oldest = 0; - for i in 1..4 { - if self.midi_order[i] < self.midi_order[oldest] { - oldest = i; + 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); } } - 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 + oldest.unwrap_or(0) }; - self.assign(voice, note, gain); - if self.config.source == HarmonySource::ChordViaMidi { - self.setup_chord(); + 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; } - return true; } - if self.config.source == HarmonySource::MidiChannels && channel < 4 { - let voice = usize::from(channel); - if velocity == 0 { - if self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 { - 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_u64; 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]; } - } else { + } + } + for voice in 0..HARMONY_VOICES { + if best_order[voice] != 0 { if self.midi_period[voice] == Q6::ZERO { self.portamento_period[voice] = Q6::ZERO; } - self.assign(voice, note, gain); - return true; + 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. + /// + /// Every event updates the 16-channel keybed. Returns `true` if resynthesis + /// must make its next control step due. If the active harmony source or + /// channel map does not use the event, the function increases the ignored + /// event count. All Notes Off calls `reset` and returns `false`. + pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) -> bool { + let (channel, note, velocity) = match event { + MidiEvent::AllNotesOff => { + self.reset(); + if !matches!( + self.config.source, + HarmonySource::ChordViaMidi + | HarmonySource::MidiOmni + | HarmonySource::MidiChannels + ) { + self.ignored_midi_events = self.ignored_midi_events.saturating_add(1); + } + return false; + } + MidiEvent::NoteOn { + channel, + note, + velocity, + } => (channel, usize::from(note), velocity), + MidiEvent::NoteOff { channel, note } => (channel, usize::from(note), 0), + }; + self.keybed.record(event); + match self.config.source { + HarmonySource::MidiOmni | HarmonySource::ChordViaMidi => { + let already_active = velocity != 0 + && (0..HARMONY_VOICES).any(|v| { + self.midi_period[v] != Q6::ZERO && self.midi_note[v] == note as i32 + }); + self.reproject_omni_voices(); + if self.config.source == HarmonySource::ChordViaMidi { + self.setup_chord(); + } + !already_active + } + HarmonySource::MidiChannels => { + let Some(voice) = self.config.map_channel(channel) else { + self.ignored_midi_events = self.ignored_midi_events.saturating_add(1); + return false; + }; + let old_period = self.midi_period[voice]; + let old_note = self.midi_note[voice]; + self.reproject_channels(); + if velocity != 0 { + true + } else { + self.midi_period[voice] != Q6::ZERO + && (old_period == Q6::ZERO || self.midi_note[voice] != old_note) + } + } + HarmonySource::FixedInterval + | HarmonySource::SmartInterval + | HarmonySource::ChordByDegree + | HarmonySource::ChordByName => { + self.ignored_midi_events = self.ignored_midi_events.saturating_add(1); + false } } - false } - /// Assigns a validated MIDI pitch and gain to a voice and records the - /// current event order. - fn assign(&mut self, voice: usize, note: usize, gain: Q12) { + /// Assigns a validated MIDI pitch, gain and event order to a voice. + fn assign(&mut self, voice: usize, note: usize, gain: Q12, order: u64) { self.midi_period[voice] = note_period(self.rate, note as i32); self.midi_note[voice] = note as i32; self.midi_gain[voice] = gain; - self.midi_order[voice] = self.event_counter; + self.midi_order[voice] = order; } /// Advances one voice from the Q6 tracked input period to a Q14 ratio and /// a Q12 gain. diff --git a/src/lib.rs b/src/lib.rs index 0e29119..42dd987 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -130,10 +130,11 @@ pub use error::{ConfigProblem, Error, EventProblem}; pub use events::{ControlEvent, 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 63f8660..9e502c2 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..=126 and keeps key 127. + /// 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 restores [`crate::CorrectionConfig::notes`]. AllNotesOff, } diff --git a/src/processor.rs b/src/processor.rs index cc910f4..59dc5ca 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -390,6 +390,8 @@ impl Processor { alien_loop_frames: alien_loop as u32, alien_phase_frames: alien_phase as u32, formant_generation: self.resynthesis.formant_generation(), + ignored_midi_events: self.resynthesis.ignored_midi_events(), + correction_midi_active: self.resynthesis.correction_midi_active(), } } @@ -517,13 +519,15 @@ 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 keeps these items: + /// the reverb delays. It releases the harmony MIDI keybed, the correction + /// MIDI keys 0..=127, any latched correction chord and the ignored MIDI + /// event count. If correction MIDI was active, the configured + /// [`crate::CorrectionConfig::notes`] load again. It keeps these items: /// /// - the configuration /// - the random stream and the arctangent lookup position of Punch /// - the reverb low-pass memories and the reverb write position - /// - correction key 127 and the active correction note table + /// - the prepared correction note table, if correction MIDI was not active /// - the last usable period of the pitch tracker, which fills unvoiced /// gaps /// - the harmony gain envelopes and the last voice ratios of the harmony @@ -533,8 +537,7 @@ impl Processor { /// - the control-step counter of Choir and Harmony /// - the phase of the harmonic modulation. /// - /// When the method clears the held keys, it does not load the configured - /// scale again. For a fully new state, make a new processor. + /// For a fully new state, make a new processor. pub fn reset(&mut self) { self.punch.reset(); self.warm.reset(); @@ -878,4 +881,20 @@ pub struct Telemetry { /// enabled. Compare two values to find if /// [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, + /// The count of validated [`crate::ControlEvent::Midi`] events that the + /// active harmony source or channel map ignored since construction or the + /// last reset. + /// + /// The count saturates at `u32::MAX`. [`Processor::take_telemetry`] does + /// not clear it. + pub ignored_midi_events: u32, + /// This field is `true` while [`crate::ControlEvent::CorrectionMidi`] + /// overrides [`crate::CorrectionConfig::notes`]. + /// + /// In [`crate::CorrectionMidiMode::Momentary`], the field returns to + /// `false` when all keys in 0..=127 release. In + /// [`crate::CorrectionMidiMode::Latch`], it stays `true` after key release + /// until [`crate::MidiEvent::AllNotesOff`], [`Processor::reset`] or a + /// scale change. + pub correction_midi_active: bool, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..51aa443 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -38,7 +38,7 @@ use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; use crate::numeric::{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::prepare_history; @@ -69,9 +69,11 @@ pub enum MultiVoiceMode { /// rate. /// /// Correction MIDI replaces the active note table. It does not change this -/// configuration. A change to `notes` or to `enabled` loads the configured -/// mask again. Reset releases the correction keys 0..=126. It keeps key 127 -/// and the active note table. Key 127 has no effect on the note table. +/// configuration. In [`CorrectionMidiMode::Momentary`], when all keys in +/// 0..=127 release, the configured mask loads again. In +/// [`CorrectionMidiMode::Latch`], a chord stays active until +/// [`MidiEvent::AllNotesOff`], a reset or a scale change. A change to `notes` +/// or to `enabled` loads the configured mask again. /// /// At construction, the chromatic table uses 44.1 kHz periods, also for a /// 48 kHz processor. Each of these events loads the periods for the prepared @@ -96,8 +98,10 @@ pub struct CorrectionConfig { /// The configured target pitch classes. The default is /// [`NoteMask::CHROMATIC`]. /// - /// All boolean masks are valid. MIDI can replace the active table. This - /// replacement stays until this mask or `enabled` changes. + /// All boolean masks are valid. MIDI can replace the active table. In + /// [`CorrectionMidiMode::Momentary`], key release restores this mask. In + /// [`CorrectionMidiMode::Latch`], All Notes Off, a reset or a change to + /// this mask or `enabled` restores it. pub notes: NoteMask, /// The half-life of the smoothing in milliseconds, 0..=400. The default /// is 0. @@ -106,6 +110,16 @@ pub struct CorrectionConfig { /// tracking update. A value that is not zero is a half-life. It is not a /// fixed time to get exactly to the target. pub retune_ms: f32, + /// How [`crate::ControlEvent::CorrectionMidi`] keeps or releases notes. + /// + /// The default is [`CorrectionMidiMode::Momentary`]. In JavaScript, the + /// field is optional and an absent value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub midi_mode: CorrectionMidiMode, } impl Default for CorrectionConfig { @@ -114,6 +128,7 @@ impl Default for CorrectionConfig { enabled: true, notes: NoteMask::default(), retune_ms: 0.0, + midi_mode: CorrectionMidiMode::default(), } } } @@ -217,8 +232,8 @@ pub struct ResynthesisConfig { /// A change to this value resets some audio histories and the feedback. /// [`crate::Processor::set_config`] gives the details. pub stereo_output: bool, - /// The controls for the four harmony voices. The default is MIDI-channel - /// allocation. + /// The controls for the four harmony voices. The default is smart + /// intervals with two voices. /// /// Validation applies to these controls, and they can receive MIDI, also /// while Choir is selected. @@ -647,7 +662,13 @@ 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; + } 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; } if old.pitch_ratio != config.pitch_ratio { @@ -669,12 +690,11 @@ impl Resynthesis { } } - /// Releases the correction keys 0..=126 and resets the audio state. - /// - /// The active correction table, key 127 and the items that - /// `reset_audio` keeps do not change. + /// Releases the correction keys 0..=127, clears any MIDI scale override + /// and resets the audio state. pub(crate) fn reset(&mut self) { - self.scale.reset(); + self.scale.reset(self.config.correction.notes); + self.harmony.reset_ignored_midi_events(); self.reset_audio(); } @@ -729,10 +749,25 @@ 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.scale.apply_validated_midi( + event, + self.config.correction.midi_mode, + self.config.correction.notes, + ); self.scale_initialized = false; } + /// Returns the count of ignored harmony MIDI events since reset. + pub(crate) fn ignored_midi_events(&self) -> u32 { + self.harmony.ignored_midi_events() + } + + /// Returns `true` if correction MIDI currently overrides the configured + /// notes. + pub(crate) fn correction_midi_active(&self) -> bool { + self.scale.is_midi_active() + } + /// Returns the finite number of frames for a drain of resynthesis. /// /// The number is the sum of these items: diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..58824b0 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -81,6 +81,23 @@ pub enum CorrectionScale { Chromatic, } +/// How [`crate::ControlEvent::CorrectionMidi`] keeps or releases notes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[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 override 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 +157,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. @@ -161,10 +198,12 @@ pub(crate) struct CorrectionTable { /// /// If these periods change, the active targets do not reload. base_periods: [i32; 12], - /// The held MIDI keys. - /// - /// A reset keeps key 127, and mask creation excludes it. - pub keyboard: [bool; 128], + /// The held MIDI keys 0..=127. + keyboard: u128, + /// The latched MIDI keys 0..=127 for [`CorrectionMidiMode::Latch`]. + latched: u128, + /// If `true`, correction MIDI currently overrides the configured notes. + midi_active: bool, } impl CorrectionTable { @@ -176,13 +215,21 @@ 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); result } + /// Returns `true` if correction MIDI currently overrides the configured + /// notes. + pub(crate) fn is_midi_active(&self) -> bool { + self.midi_active + } + /// Calculates the period table again for `rate`, but does not reload the /// active scale. /// @@ -219,26 +266,94 @@ impl CorrectionTable { self.midpoints[0] = self.midpoints[self.count] / 2; } } - /// Releases keys 0..=126, and keeps key 127 and the active target table. + /// 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 override state 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 + } + } + } + /// Releases all keys 0..=127 and, if a MIDI override was active, restores + /// `fallback`. /// - /// A later MIDI event builds the table again from the new keyboard state. - pub(crate) fn reset(&mut self) { - self.keyboard[..127].fill(false); + /// If no MIDI override was active, the prepared target table does not + /// reload. + 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. - pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) { + pub(crate) fn apply_validated_midi( + &mut self, + event: MidiEvent, + mode: CorrectionMidiMode, + fallback: NoteMask, + ) { match event { - MidiEvent::NoteOn { note, velocity, .. } => { - self.keyboard[note as usize] = velocity != 0 + MidiEvent::NoteOn { note, velocity, .. } if velocity != 0 => { + self.keyboard |= 1_u128 << note; + self.latched = self.keyboard; + self.midi_active = true; + self.set_notes(mask_from_bits(self.keyboard)); + } + MidiEvent::NoteOn { note, .. } | MidiEvent::NoteOff { note, .. } => { + self.keyboard &= !(1_u128 << note); + match 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)); + } + } + CorrectionMidiMode::Latch => { + if !self.midi_active { + self.set_notes(fallback); + } + } + } + } + MidiEvent::AllNotesOff => { + self.keyboard = 0; + self.latched = 0; + self.midi_active = false; + self.set_notes(fallback); } - MidiEvent::NoteOff { note, .. } => self.keyboard[note as usize] = false, - MidiEvent::AllNotesOff => self.reset(), - } - let mut mask = [false; 12]; - // Correction excludes key 127, and a reset keeps that key. - for i in 0..127 { - mask[i % 12] |= self.keyboard[i]; } - self.set_notes(NoteMask(mask)); } } diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..5de162e 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,7 +19,9 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - Optional fields use their defaults if omitted: harmony `voices` (2), +//! `midiChannelMap` (`"wrapFour"`), `midiBaseChannel` (0) and correction +//! `midiMode` (`"momentary"`). //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use From 5d16e7ab4688e635300b90306aaa88f88fff6191 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:17:12 +0000 Subject: [PATCH 2/2] refactor(midi): restore defaults and box u32 keybed tables - Keep HarmonyConfig::default() and default_voices() at four voices. - Remove ignored_midi_events and correction_midi_active from Telemetry. - Set MidiChannelMap::BaseWindow with base channel 0 as the default. - Store MidiKeybed velocity and u32 order tables on the heap. - Compact held note orders at u32::MAX. - Accumulate rolled chords in CorrectionMidiMode::Latch. - Update the rustdoc and README.md for the default settings. --- README.md | 50 ++++++------- src/harmony.rs | 181 ++++++++++++++++++++++++++------------------- src/processor.rs | 24 +----- src/resynthesis.rs | 16 +--- src/scale.rs | 39 ++++------ src/wasm.rs | 4 +- 6 files changed, 152 insertions(+), 162 deletions(-) diff --git a/README.md b/README.md index 4c3596e..b61ffc5 100644 --- a/README.md +++ b/README.md @@ -184,32 +184,32 @@ 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, default | -| `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 mapped through `midi_channel_map` to four voices | +| 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 2, with diatonic intervals `[2, -2, 4, -4]` and chromatic -intervals `[4, -5, 7, -12]`. `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 `WrapFour` -(default, channel `c` in `0..=15` maps to voice `c % 4`) or `BaseWindow` -(channels `midi_base_channel..midi_base_channel + 4`, where `midi_base_channel` -is in `0..=12` and defaults to 0). A 16-channel keybed keeps held notes across -live switches among `MidiOmni`, `ChordViaMidi` and `MidiChannels`, and resumes -held notes on legato release. +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` maps channels +`midi_base_channel..midi_base_channel + 4` to the four voices, with +`midi_base_channel` in `0..=12` (default 0). `WrapFour` maps channel `c` in +`0..=15` to voice `c % 4`. 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`. `Momentary` restores -`resynthesis.correction.notes` when all keys release. `Latch` keeps the last +`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. @@ -324,8 +324,6 @@ The telemetry includes these items: signal. - The pitch clarity, which is a confidence score from 0 to 1. - The current gains of Punch and Warm, and the position in the Alien loop. -- The count of ignored harmony MIDI events and whether correction MIDI is - active. The peak windows of the telemetry are independent of the peak window of the feedback. In mono calls, the output and reverb wet peaks measure the audio @@ -470,8 +468,8 @@ 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`. Optional fields use their defaults if absent: -`resynthesis.harmony.voices` (`2`), `resynthesis.harmony.midiChannelMap` -(`"wrapFour"`), `resynthesis.harmony.midiBaseChannel` (`0`) and +`resynthesis.harmony.voices` (`4`), `resynthesis.harmony.midiChannelMap` +(`"baseWindow"`), `resynthesis.harmony.midiBaseChannel` (`0`) and `resynthesis.correction.midiMode` (`"momentary"`). The conversion ignores extra object properties. The generated declarations contain the parameter documentation from the Rust types. diff --git a/src/harmony.rs b/src/harmony.rs index 10e1d7d..c2658dd 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -33,7 +33,7 @@ const GAIN_RELEASE: Q12 = Q12::from_bits(81); /// The source of target periods for the four harmony voices. /// -/// The default is [`Self::SmartInterval`]. The static interval and chord +/// The default is [`Self::MidiChannels`]. The static interval and chord /// 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. @@ -48,9 +48,7 @@ pub enum HarmonySource { /// uses `chromatic_intervals`. FixedInterval, /// Each voice follows an interval in scale steps from the singer. This - /// source uses `diatonic_intervals`, `key` and `scale`. This is the - /// default. - #[default] + /// source uses `diatonic_intervals`, `key` and `scale`. SmartInterval, /// The voices sing a chord on a scale degree. This source uses `degree`, /// `key`, `scale` and `inversion`. @@ -76,8 +74,9 @@ pub enum HarmonySource { /// and [`HarmonyConfig::midi_base_channel`]. /// /// Each voice plays the newest held note across the channels mapped to it. - /// When that note stops, the voice resumes the next newest held note on - /// its mapped channels. + /// If that note stops, the voice resumes the next newest held note on its + /// mapped channels. This is the default. + #[default] MidiChannels, } @@ -90,12 +89,13 @@ pub enum HarmonySource { serde(rename_all = "camelCase") )] pub enum MidiChannelMap { - /// Channel `c` in 0..=15 maps to voice `c % 4`. This is the default. - #[default] - WrapFour, /// Channel `c` in `midi_base_channel..midi_base_channel + 4` maps to /// voice `c - midi_base_channel`. Other channels do not control voices. + /// This is the default. + #[default] BaseWindow, + /// Channel `c` in 0..=15 maps to voice `c % 4`. + WrapFour, } /// The scale that smart intervals and chords by degree use. @@ -250,15 +250,14 @@ pub enum Inversion { /// /// Positive intervals make the pitch higher. The defaults are: /// -/// - Smart intervals as the source. +/// - MIDI channels 0..=3 as the source. /// - The key of C and the major scale. -/// - Chromatic intervals `[4, -5, 7, -12]` and diatonic intervals -/// `[2, -2, 4, -4]`. +/// - Unison intervals. /// - A tonic major chord in root position. /// - A register of 50%. /// - A closed voicing and zero portamento. -/// - Two voices for the interval sources. -/// - [`MidiChannelMap::WrapFour`] with base channel 0. +/// - 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. @@ -280,7 +279,7 @@ pub enum Inversion { serde(rename_all = "camelCase") )] pub struct HarmonyConfig { - /// The pitch source. The default is [`HarmonySource::SmartInterval`]. + /// The pitch source. The default is [`HarmonySource::MidiChannels`]. pub source: HarmonySource, /// The pitch class of the tonic. The default is C. Smart intervals, named /// chords and degree chords use it. It does not transpose direct MIDI @@ -288,17 +287,17 @@ pub struct HarmonyConfig { pub key: PitchClass, /// The scale for smart intervals and degree chords. The default is major. pub scale: HarmonyScale, - /// Four fixed semitone offsets, each in -24..=24. The default is - /// `[4, -5, 7, -12]`. [`HarmonySource::FixedInterval`] uses them. A value - /// of 12 makes the pitch one octave higher. + /// Four fixed semitone offsets, each in -24..=24. The default is all + /// zeros. [`HarmonySource::FixedInterval`] uses them. A value of 12 makes + /// the pitch one octave higher. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), tsify(type = "[number, number, number, number]") )] pub chromatic_intervals: [i8; HARMONY_VOICES], - /// Four offsets in scale steps, each in -14..=14. The default is - /// `[2, -2, 4, -4]`. [`HarmonySource::SmartInterval`] uses them. Seven - /// steps make the pitch one octave higher. + /// Four offsets in scale steps, each in -14..=14. The default is all + /// zeros. [`HarmonySource::SmartInterval`] uses them. Seven steps make + /// the pitch one octave higher. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), tsify(type = "[number, number, number, number]") @@ -336,7 +335,7 @@ pub struct HarmonyConfig { pub portamento_ms: f32, /// The number of voices that sound in the interval sources, 0..=4. /// - /// The default is 2. [`HarmonySource::FixedInterval`] and + /// The default is 4. [`HarmonySource::FixedInterval`] and /// [`HarmonySource::SmartInterval`] use the first `voices` voices. The /// other voices release with the usual gain envelope. The chord and MIDI /// sources ignore this field. In JavaScript, the field is optional and @@ -349,7 +348,7 @@ pub struct HarmonyConfig { pub voices: u8, /// How [`HarmonySource::MidiChannels`] maps channels to voices. /// - /// The default is [`MidiChannelMap::WrapFour`]. Other harmony sources + /// The default is [`MidiChannelMap::BaseWindow`]. Other harmony sources /// ignore this field. In JavaScript, the field is optional and an absent /// value gives the default. #[cfg_attr( @@ -372,28 +371,28 @@ pub struct HarmonyConfig { pub midi_base_channel: u8, } -/// The default count of interval voices: two. +/// The default count of interval voices: all of them. #[cfg(all(feature = "wasm", target_arch = "wasm32"))] fn default_voices() -> u8 { - 2 + HARMONY_VOICES as u8 } impl Default for HarmonyConfig { fn default() -> Self { Self { - source: HarmonySource::SmartInterval, + source: HarmonySource::MidiChannels, key: PitchClass::C, scale: HarmonyScale::Major, - chromatic_intervals: [4, -5, 7, -12], - diatonic_intervals: [2, -2, 4, -4], + chromatic_intervals: [0; HARMONY_VOICES], + diatonic_intervals: [0; HARMONY_VOICES], chord: ChordName::Major, degree: ChordDegree::I, inversion: Inversion::Root, register_percent: 50.0, voicing_spread_percent: 0.0, portamento_ms: 0.0, - voices: 2, - midi_channel_map: MidiChannelMap::WrapFour, + voices: HARMONY_VOICES as u8, + midi_channel_map: MidiChannelMap::BaseWindow, midi_base_channel: 0, } } @@ -438,8 +437,7 @@ impl HarmonyConfig { ) } - /// Maps a zero-based MIDI channel 0..=15 to a voice index 0..=3, or - /// returns `None` if the channel is outside the active window. + /// 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), @@ -452,25 +450,34 @@ impl HarmonyConfig { } } +/// 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: [[u8; 128]; 16], + velocity: Box<[[u8; 128]; 16]>, /// Monotonic press order for each held note on each channel. - order: [[u64; 128]; 16], + order: Box<[[u32; 128]; 16]>, /// Monotonic counter of Note On events. - next_order: u64, + next_order: u32, } impl MidiKeybed { - /// Returns an empty keybed with no held notes. + /// Returns an empty keybed with heap-allocated velocity and order tables. fn new() -> Self { Self { held: [0; 16], - velocity: [[0; 128]; 16], - order: [[0; 128]; 16], + velocity: prepare_keybed_table(0), + order: prepare_keybed_table(0), next_order: 0, } } @@ -481,8 +488,54 @@ impl MidiKeybed { 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) { + fn record(&mut self, event: MidiEvent, voice_orders: &mut [u32; HARMONY_VOICES]) { match event { MidiEvent::AllNotesOff => self.clear(), MidiEvent::NoteOn { @@ -490,6 +543,9 @@ impl MidiKeybed { 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; @@ -528,7 +584,7 @@ pub(crate) struct HarmonyState { /// The Q12 velocity gain of each allocated note. midi_gain: [Q12; HARMONY_VOICES], /// The monotonic event order of each voice assignment. - midi_order: [u64; HARMONY_VOICES], + 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], @@ -571,9 +627,6 @@ pub(crate) struct HarmonyState { porta_decay: Q14, /// The 16-channel by 128-note MIDI keybed. keybed: MidiKeybed, - /// The count of validated harmony MIDI events ignored by the active source - /// or channel map. - ignored_midi_events: u32, /// The precomputed Q12 velocity gains for all 128 MIDI velocity values. gains: [Q12; 128], } @@ -604,7 +657,6 @@ impl HarmonyState { scale_note: [0; HARMONY_VOICES], porta_decay: Q14::ZERO, keybed: MidiKeybed::new(), - ignored_midi_events: 0, gains: std::array::from_fn(|i| velocity_gain(i as u8)), }; result.prepare_intervals(); @@ -612,20 +664,10 @@ impl HarmonyState { result } - /// Returns the count of ignored harmony MIDI events since reset. - pub(crate) fn ignored_midi_events(&self) -> u32 { - self.ignored_midi_events - } - - /// Clears the count of ignored harmony MIDI events on a processor reset. - pub(crate) fn reset_ignored_midi_events(&mut self) { - self.ignored_midi_events = 0; - } - /// Applies a configuration that validation already accepted. /// /// If the source or the channel map changes, the function projects the - /// held keybed notes onto the new source so unselected voices decay and + /// held keybed notes onto the new source. 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) { @@ -822,13 +864,13 @@ impl HarmonyState { } let mut selected_note = [0_usize; HARMONY_VOICES]; let mut selected_gain = [Q12::ZERO; HARMONY_VOICES]; - let mut selected_order = [0_u64; 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_u64; + 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 { @@ -918,7 +960,7 @@ impl HarmonyState { 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_u64; 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; @@ -951,21 +993,12 @@ impl HarmonyState { /// already in range. /// /// Every event updates the 16-channel keybed. Returns `true` if resynthesis - /// must make its next control step due. If the active harmony source or - /// channel map does not use the event, the function increases the ignored - /// event count. All Notes Off calls `reset` and returns `false`. + /// must make its next control step due. All Notes Off calls `reset` and + /// returns `false`. pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) -> bool { let (channel, note, velocity) = match event { MidiEvent::AllNotesOff => { self.reset(); - if !matches!( - self.config.source, - HarmonySource::ChordViaMidi - | HarmonySource::MidiOmni - | HarmonySource::MidiChannels - ) { - self.ignored_midi_events = self.ignored_midi_events.saturating_add(1); - } return false; } MidiEvent::NoteOn { @@ -975,7 +1008,7 @@ impl HarmonyState { } => (channel, usize::from(note), velocity), MidiEvent::NoteOff { channel, note } => (channel, usize::from(note), 0), }; - self.keybed.record(event); + self.keybed.record(event, &mut self.midi_order); let control_due = match self.config.source { HarmonySource::MidiOmni | HarmonySource::ChordViaMidi => { let already_active = @@ -985,7 +1018,6 @@ impl HarmonyState { } HarmonySource::MidiChannels => { let Some(voice) = self.config.map_channel(channel) else { - self.ignored_midi_events = self.ignored_midi_events.saturating_add(1); return false; }; let old_period = self.midi_period[voice]; @@ -1001,10 +1033,7 @@ impl HarmonyState { HarmonySource::FixedInterval | HarmonySource::SmartInterval | HarmonySource::ChordByDegree - | HarmonySource::ChordByName => { - self.ignored_midi_events = self.ignored_midi_events.saturating_add(1); - false - } + | HarmonySource::ChordByName => false, }; if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); @@ -1016,7 +1045,7 @@ impl HarmonyState { self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 } /// Assigns a validated MIDI pitch, gain and event order to a voice. - fn assign(&mut self, voice: usize, note: usize, gain: Q12, order: u64) { + 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/processor.rs b/src/processor.rs index 7eb1732..4836999 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -396,8 +396,6 @@ impl Processor { alien_loop_frames: alien_loop as u32, alien_phase_frames: alien_phase as u32, formant_generation: self.resynthesis.formant_generation(), - ignored_midi_events: self.resynthesis.ignored_midi_events(), - correction_midi_active: self.resynthesis.correction_midi_active(), } } @@ -522,9 +520,9 @@ 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 keybed, the correction - /// MIDI keys 0..=127, any latched correction chord and the ignored MIDI - /// event count. If correction MIDI was active, the configured - /// [`crate::CorrectionConfig::notes`] load again. It keeps these items: + /// MIDI keys 0..=127 and any latched correction chord. If correction MIDI + /// was active, the configured [`crate::CorrectionConfig::notes`] load + /// again. It keeps these items: /// /// - the configuration /// - the random stream and the arctangent lookup position of Punch @@ -903,20 +901,4 @@ pub struct Telemetry { /// enabled. Compare two values to find if /// [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, - /// The count of validated [`crate::ControlEvent::Midi`] events that the - /// active harmony source or channel map ignored since construction or the - /// last reset. - /// - /// The count saturates at `u32::MAX`. [`Processor::take_telemetry`] does - /// not clear it. - pub ignored_midi_events: u32, - /// This field is `true` while [`crate::ControlEvent::CorrectionMidi`] - /// overrides [`crate::CorrectionConfig::notes`]. - /// - /// In [`crate::CorrectionMidiMode::Momentary`], the field returns to - /// `false` when all keys in 0..=127 release. In - /// [`crate::CorrectionMidiMode::Latch`], it stays `true` after key release - /// until [`crate::MidiEvent::AllNotesOff`], [`Processor::reset`] or a - /// scale change. - pub correction_midi_active: bool, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index a71a3c8..3bd0385 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -230,8 +230,8 @@ pub struct ResynthesisConfig { /// A change to this value resets some audio histories and the feedback. /// [`crate::Processor::set_config`] gives the details. pub stereo_output: bool, - /// The controls for the four harmony voices. The default is smart - /// intervals with two voices. + /// The controls for the four harmony voices. The default is MIDI-channel + /// allocation. /// /// Validation applies to these controls, and they can receive MIDI, also /// while Choir is selected. @@ -690,7 +690,6 @@ impl Resynthesis { /// and resets the audio state. pub(crate) fn reset(&mut self) { self.scale.reset(self.config.correction.notes); - self.harmony.reset_ignored_midi_events(); self.reset_audio(); } @@ -778,17 +777,6 @@ impl Resynthesis { self.scale_initialized = false; } - /// Returns the count of ignored harmony MIDI events since reset. - pub(crate) fn ignored_midi_events(&self) -> u32 { - self.harmony.ignored_midi_events() - } - - /// Returns `true` if correction MIDI currently overrides the configured - /// notes. - pub(crate) fn correction_midi_active(&self) -> bool { - self.scale.is_midi_active() - } - /// Returns the finite number of frames for a drain of resynthesis. /// /// The number is the sum of these items: diff --git a/src/scale.rs b/src/scale.rs index e98a3eb..be08207 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -225,12 +225,6 @@ impl CorrectionTable { result } - /// Returns `true` if correction MIDI currently overrides the configured - /// notes. - pub(crate) fn is_midi_active(&self) -> bool { - self.midi_active - } - /// Calculates the period table again for `rate` and builds the active /// targets again. /// @@ -333,27 +327,26 @@ impl CorrectionTable { ) { match event { MidiEvent::NoteOn { note, velocity, .. } if velocity != 0 => { - self.keyboard |= 1_u128 << note; - self.latched = self.keyboard; + 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; - self.set_notes(mask_from_bits(self.keyboard)); + let active = match mode { + CorrectionMidiMode::Momentary => self.keyboard, + CorrectionMidiMode::Latch => self.latched, + }; + self.set_notes(mask_from_bits(active)); } MidiEvent::NoteOn { note, .. } | MidiEvent::NoteOff { note, .. } => { self.keyboard &= !(1_u128 << note); - match 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)); - } - } - CorrectionMidiMode::Latch => { - if !self.midi_active { - self.set_notes(fallback); - } + 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)); } } } diff --git a/src/wasm.rs b/src/wasm.rs index b7ae15f..8480f91 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,8 +19,8 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. -//! - Optional fields use their defaults if omitted: harmony `voices` (2), -//! `midiChannelMap` (`"wrapFour"`), `midiBaseChannel` (0) and correction +//! - Optional fields use their defaults if omitted: harmony `voices` (4), +//! `midiChannelMap` (`"baseWindow"`), `midiBaseChannel` (0) and correction //! `midiMode` (`"momentary"`). //! //! [`default_config`] gives a configuration to start from. Control events use