From a920b4aaf160c136509e70f5043469042f91ad60 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:51:28 +0000 Subject: [PATCH] feat(midi): add pitch bend and sustain support - Add PitchBend and SustainPedal variants and byte decode to MIDI - Validate MIDI channel and 14-bit pitch-bend value ranges - Add pitch_bend_semitones to HarmonyConfig and CorrectionConfig - Apply Q14 pitch-bend ratios and sustain latches to harmony - Apply Q14 pitch-bend ratios and sustain latches to pitch correction - Clear sustain and pitch-bend state on All Notes Off and on reset - Document the new MIDI controls and bend ranges in the README --- README.md | 14 ++- src/harmony.rs | 269 +++++++++++++++++++++++++++++++++++++++------ src/midi.rs | 98 +++++++++++++---- src/resynthesis.rs | 59 ++++++++-- src/scale.rs | 74 +++++++++++-- src/wasm.rs | 10 +- 6 files changed, 447 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index d2993dc..def5bf2 100644 --- a/README.md +++ b/README.md @@ -445,7 +445,9 @@ 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`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The +to 4 if it is absent. The optional `resynthesis.correction.pitchBendSemitones` +and `resynthesis.harmony.pitchBendSemitones` fields are in `0..=24` and default +to 2 if they are absent. The conversion ignores extra object properties. The generated declarations contain the parameter documentation from the Rust types. @@ -469,6 +471,16 @@ A harmony Note On event has this form: { offset: 0, event: { type: "midi", value: { type: "noteOn", channel: 0, note: 60, velocity: 100 } } } ``` +MIDI events also accept `"noteOff"`, `"pitchBend"` (`channel` in `0..=15`, +`value` in `-8192..=8191`), `"sustainPedal"` (`channel` in `0..=15`, `held` as +a `boolean`) and `"allNotesOff"`. For example, these events hold the sustain +pedal and bend the pitch upward: + +```ts +{ offset: 0, event: { type: "midi", value: { type: "sustainPedal", channel: 0, held: true } } } +{ offset: 0, event: { type: "midi", value: { type: "pitchBend", channel: 0, value: 4096 } } } +``` + Use `correctionMidi` for the separate correction keyboard. The native rules for event order and for the validation of the whole block also apply to these bindings. diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..4e8feea 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -7,7 +7,7 @@ mod chords; use crate::error::{check_count, check_range}; -use crate::midi::{note_period, velocity_gain, MidiEvent}; +use crate::midi::{bend_ratio, note_period, velocity_gain, MidiEvent}; use crate::numeric::fixed::{Q12, Q14, Q6}; use crate::scale::PitchClass; use crate::{Error, SampleRate}; @@ -240,6 +240,7 @@ pub enum Inversion { /// - A register of 50%. /// - A closed voicing and zero portamento. /// - Four voices for the interval sources. +/// - A pitch-bend range of two semitones. /// /// These settings configure all sources. Only the fields for the selected /// source change the target notes. Validation always checks all fields. @@ -328,6 +329,18 @@ pub struct HarmonyConfig { tsify(optional) )] pub voices: u8, + /// The maximum pitch bend in semitones, 0..=24. + /// + /// The default is 2. A [`MidiEvent::PitchBend`] value of -8192 lowers the + /// pitch by this range, and 8191 raises the pitch by this range. Zero + /// disables pitch bend. In JavaScript, the field is optional and an absent + /// value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_pitch_bend_semitones"), + tsify(optional) + )] + pub pitch_bend_semitones: f32, } /// The default count of interval voices: all of them. @@ -336,6 +349,12 @@ fn default_voices() -> u8 { HARMONY_VOICES as u8 } +/// The default pitch-bend range in semitones. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_pitch_bend_semitones() -> f32 { + 2.0 +} + impl Default for HarmonyConfig { fn default() -> Self { Self { @@ -351,6 +370,7 @@ impl Default for HarmonyConfig { voicing_spread_percent: 0.0, portamento_ms: 0.0, voices: HARMONY_VOICES as u8, + pitch_bend_semitones: 2.0, } } } @@ -389,6 +409,12 @@ impl HarmonyConfig { self.portamento_ms, 0.0, 10_000.0, + )?; + check_range( + "resynthesis.harmony.pitch_bend_semitones", + self.pitch_bend_semitones, + 0.0, + 24.0, ) } } @@ -464,6 +490,20 @@ pub(crate) struct HarmonyState { /// The signed assignment order of each pending note. The largest positive /// value resumes first. pending_order: [i32; 128], + /// The sustain latches for notes that Note Off released during sustain. + sustained: [bool; 128], + /// The sustain latches for the four allocated voice slots. + voice_sustained: [bool; HARMONY_VOICES], + /// The sustain-pedal state (controller 64) for each MIDI channel. + sustain_held: [bool; 16], + /// The centered 14-bit pitch bend on each MIDI channel. + pitch_bend: [i16; 16], + /// The Q14 pitch-bend ratio on each MIDI channel. + bend_ratio: [Q14; 16], + /// The latest centered 14-bit pitch bend across all channels. + omni_pitch_bend: i16, + /// The Q14 pitch-bend ratio from `omni_pitch_bend`. + omni_bend_ratio: Q14, /// 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, @@ -498,6 +538,13 @@ impl HarmonyState { porta_decay: Q14::ZERO, pending_gain: [Q12::ZERO; 128], pending_order: [0; 128], + sustained: [false; 128], + voice_sustained: [false; HARMONY_VOICES], + sustain_held: [false; 16], + pitch_bend: [0; 16], + bend_ratio: [Q14::ONE; 16], + omni_pitch_bend: 0, + omni_bend_ratio: Q14::ONE, event_counter: 0, gains: std::array::from_fn(|i| velocity_gain(i as u8)), }; @@ -539,6 +586,13 @@ impl HarmonyState { if old.portamento_ms != config.portamento_ms { self.prepare_portamento(); } + if old.pitch_bend_semitones != config.pitch_bend_semitones { + for channel in 0..16 { + self.bend_ratio[channel] = + bend_ratio(self.pitch_bend[channel], config.pitch_bend_semitones); + } + self.omni_bend_ratio = bend_ratio(self.omni_pitch_bend, config.pitch_bend_semitones); + } if old != config { self.setup_chord(); } @@ -549,6 +603,7 @@ impl HarmonyState { /// /// - The active MIDI periods, which releases the voices. /// - The pending stolen notes and their assignment orders. + /// - The sustained notes, the sustain pedals and the pitch-bend state. /// - The portamento start state. /// - The MIDI event counter. /// @@ -565,6 +620,13 @@ impl HarmonyState { self.portamento_period.fill(Q6::ZERO); self.pending_gain.fill(Q12::ZERO); self.pending_order.fill(0); + self.sustained.fill(false); + self.voice_sustained.fill(false); + self.sustain_held.fill(false); + self.pitch_bend.fill(0); + self.bend_ratio.fill(Q14::ONE); + self.omni_pitch_bend = 0; + self.omni_bend_ratio = Q14::ONE; self.event_counter = 0; if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); @@ -694,21 +756,33 @@ impl HarmonyState { index as i32, ) } - /// Applies a MIDI event with channel, note and velocity values that are - /// already in range. + /// Applies a MIDI event with channel, note, velocity and bend 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. + /// This occurs after a new note assignment, after an unheld Note Off or + /// pedal release in the omni sources, and after an active Pitch Bend. The + /// omni sources steal the oldest voice and resume the newest pending note. + /// While sustain is active, Note Off latches active notes until the pedal + /// releases. 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; } + MidiEvent::PitchBend { channel, value } => { + let idx = usize::from(channel); + let ratio = bend_ratio(value, self.config.pitch_bend_semitones); + self.pitch_bend[idx] = value; + self.bend_ratio[idx] = ratio; + self.omni_pitch_bend = value; + self.omni_bend_ratio = ratio; + return self.config.source != HarmonySource::MidiChannels || channel < 4; + } + MidiEvent::SustainPedal { channel, held } => { + return self.apply_sustain_pedal(usize::from(channel), held); + } MidiEvent::NoteOn { channel, note, @@ -718,47 +792,49 @@ impl HarmonyState { }; 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 { + if self.sustain_held.contains(&true) { + let mut active = self.pending_order[note] != 0; + for voice in 0..HARMONY_VOICES { + if self.midi_period[voice] != Q6::ZERO + && self.midi_note[voice] == note as i32 + { + self.voice_sustained[voice] = true; + active = true; + } + } + if active { + self.sustained[note] = true; + } + return false; + } + self.sustained[note] = false; + self.pending_gain[note] = Q12::ZERO; + self.pending_order[note] = 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; + self.voice_sustained[voice] = false; released = Some(voice); } } 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; - } + self.resume_pending(voice); } if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); } return true; } + self.sustained[note] = false; for voice in 0..HARMONY_VOICES { if self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 { + self.voice_sustained[voice] = false; self.midi_gain[voice] = gain; self.midi_order[voice] = self.event_counter; if self.config.source == HarmonySource::ChordViaMidi { @@ -767,6 +843,8 @@ impl HarmonyState { return false; } } + self.pending_gain[note] = Q12::ZERO; + self.pending_order[note] = 0; let voice = if let Some(free) = (0..HARMONY_VOICES).find(|&v| self.midi_period[v] == Q6::ZERO) { @@ -784,6 +862,7 @@ impl HarmonyState { self.pending_order[stolen] = self.midi_order[oldest]; oldest }; + self.voice_sustained[voice] = false; self.assign(voice, note, gain); if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); @@ -794,18 +873,133 @@ impl HarmonyState { 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; + if self.sustain_held[voice] { + self.voice_sustained[voice] = true; + self.sustained[note] = true; + } else { + self.midi_period[voice] = Q6::ZERO; + self.voice_sustained[voice] = false; + self.pending_gain[note] = Q12::ZERO; + self.pending_order[note] = 0; + } + } else if !self.sustain_held[voice] { + self.pending_gain[note] = Q12::ZERO; + self.pending_order[note] = 0; } } else { + if self.voice_sustained[voice] && self.midi_period[voice] != Q6::ZERO { + let old_note = self.midi_note[voice] as usize; + self.voice_sustained[voice] = false; + self.clear_sustained_if_unused(old_note); + } + self.sustained[note] = false; + self.voice_sustained[voice] = false; if self.midi_period[voice] == Q6::ZERO { self.portamento_period[voice] = Q6::ZERO; } self.assign(voice, note, gain); return true; } + return false; + } + if velocity == 0 && !self.sustain_held[usize::from(channel)] { + self.pending_gain[note] = Q12::ZERO; + self.pending_order[note] = 0; + } + false + } + /// Updates the sustain-pedal state for `channel` and releases unheld notes + /// when sustain ends. + fn apply_sustain_pedal(&mut self, channel: usize, held: bool) -> bool { + self.sustain_held[channel] = held; + if held { + return false; + } + if matches!( + self.config.source, + HarmonySource::MidiOmni | HarmonySource::ChordViaMidi + ) { + if self.sustain_held.contains(&true) { + return false; + } + for pending in 0..128 { + if self.sustained[pending] { + self.pending_gain[pending] = Q12::ZERO; + self.pending_order[pending] = 0; + } + } + let mut released = false; + for voice in 0..HARMONY_VOICES { + let note = self.midi_note[voice] as usize; + if self.midi_period[voice] != Q6::ZERO + && (self.sustained[note] || self.voice_sustained[voice]) + { + self.midi_period[voice] = Q6::ZERO; + self.voice_sustained[voice] = false; + released = true; + self.resume_pending(voice); + } + } + self.sustained.fill(false); + self.voice_sustained.fill(false); + if released { + if self.config.source == HarmonySource::ChordViaMidi { + self.setup_chord(); + } + return true; + } + return false; + } + if self.config.source == HarmonySource::MidiChannels && channel < HARMONY_VOICES { + if self.voice_sustained[channel] { + self.voice_sustained[channel] = false; + if self.midi_period[channel] != Q6::ZERO { + let note = self.midi_note[channel] as usize; + self.midi_period[channel] = Q6::ZERO; + self.clear_sustained_if_unused(note); + } + } + if !self.sustain_held.contains(&true) { + self.sustained.fill(false); + } + } else if !self.sustain_held.contains(&true) { + self.sustained.fill(false); + self.voice_sustained.fill(false); } false } + /// Clears `sustained[note]` if no sustained voice slot holds `note`. + fn clear_sustained_if_unused(&mut self, note: usize) { + let used = (0..HARMONY_VOICES).any(|voice| { + self.voice_sustained[voice] + && self.midi_period[voice] != Q6::ZERO + && self.midi_note[voice] == note as i32 + }); + if !used { + self.sustained[note] = false; + } + } + /// Resumes the pending note with the newest positive assignment order onto + /// `voice`. + fn resume_pending(&mut self, voice: usize) { + 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.voice_sustained[voice] = self.sustained[pending]; + self.pending_gain[pending] = Q12::ZERO; + self.pending_order[pending] = 0; + } + } /// 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) { @@ -821,7 +1015,8 @@ impl HarmonyState { /// also clears the portamento start state and keeps the gain envelope. /// If the input is voiced, the function advances the gain envelope. It /// keeps the target of a released voice until the gain is zero. Then, in - /// the same step, it applies portamento in the period domain. + /// the same step, it applies portamento in the period domain and scales + /// the ratio by any active pitch bend. pub(crate) fn advance_voice(&mut self, period: Q6, voice: usize) -> (Q14, Q12) { if period == Q6::ZERO { self.portamento_period[voice] = Q6::ZERO; @@ -847,7 +1042,17 @@ impl HarmonyState { + (Q14::ONE - self.porta_decay).mul(self.period_output[voice]) }; if self.portamento_period[voice] > Q6::ZERO { - self.current_ratio[voice] = period.div(self.portamento_period[voice]); + let ratio = period.div(self.portamento_period[voice]); + let bend = if self.config.source == HarmonySource::MidiChannels { + self.bend_ratio[voice] + } else { + self.omni_bend_ratio + }; + self.current_ratio[voice] = if bend == Q14::ONE { + ratio + } else { + ratio.mul(bend) + }; } } (self.current_ratio[voice], self.smoothed_gain[voice]) diff --git a/src/midi.rs b/src/midi.rs index 63f8660..03cafd2 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -1,15 +1,15 @@ -//! MIDI note messages, pitch periods and the conversion of velocity to gain. +//! MIDI messages, pitch periods, pitch-bend ratios and velocity gains. -use crate::numeric::fixed::{Q12, Q6}; +use crate::numeric::fixed::{Q12, Q14, Q6}; use crate::Error; -/// The supported MIDI note controls, with zero-based channel numbers. +/// The supported MIDI controls, with zero-based channel numbers. /// /// Use [`crate::ControlEvent::Midi`] for harmony. Use /// [`crate::ControlEvent::CorrectionMidi`] for the independent correction -/// keyboard. The typed representation can contain `u8` values that are not -/// valid. [`Self::validate`] and the event preflight of the processor check -/// the MIDI ranges. Note numbers use A4 = 69 at 440 Hz. +/// keyboard. The typed representation can contain `u8` and `i16` values that +/// are not valid. [`Self::validate`] and the event preflight of the processor +/// check the MIDI ranges. Note numbers use A4 = 69 at 440 Hz. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -35,26 +35,55 @@ pub enum MidiEvent { /// The MIDI note, 0..=127. note: u8, }, + /// The pitch wheel moves on a channel. + /// + /// A value of `0` gives no bend. `-8192` lowers the pitch by the + /// configured bend range, and `8191` raises it by that range. In + /// [`crate::HarmonySource::MidiChannels`], channels `0..=3` bend voices + /// `0..=3`. Other harmony sources and the correction keyboard use the + /// latest bend from any channel. + PitchBend { + /// The MIDI channel, 0..=15. + channel: u8, + /// The centered 14-bit bend value, -8192..=8191. + value: i16, + }, + /// The sustain pedal changes state (controller 64). + /// + /// While sustain is active, [`Self::NoteOff`] holds active notes until the + /// pedal releases. [`crate::HarmonySource::MidiChannels`] tracks channels + /// `0..=3` separately. [`crate::HarmonySource::MidiOmni`], + /// [`crate::HarmonySource::ChordViaMidi`] and the correction keyboard + /// combine all channels. When all 16 channels release the pedal, the + /// sustained notes release. + SustainPedal { + /// The MIDI channel, 0..=15. + channel: u8, + /// `true` holds the pedal, and `false` releases it. + held: bool, + }, /// 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 active MIDI assignments, the stolen notes, + /// the sustained notes, the sustain pedals and the pitch bend 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, sustained notes, + /// sustain pedals and pitch bend, and keeps key 127. AllNotesOff, } impl MidiEvent { /// Decodes one complete MIDI message of three bytes. /// - /// This function accepts Note On, Note Off and controller 123 (All Notes - /// Off). A Note On with velocity zero becomes Note Off. The function - /// ignores the release velocity of Note Off and the value of controller - /// 123. All Notes Off does not keep the source channel. Thus, for harmony, - /// it acts on all channels. Refer to [`Self::AllNotesOff`] for the envelope - /// and chord state that it keeps. + /// This function accepts Note On, Note Off, Pitch Bend (`0xE0`), + /// controller 64 (Sustain Pedal) and controller 123 (All Notes Off). A + /// Note On with velocity zero becomes Note Off. Pitch Bend combines the + /// 7-bit LSB in `bytes[1]` and the 7-bit MSB in `bytes[2]` into + /// `-8192..=8191`. Controller 64 sets `held` to `true` when `bytes[2]` is + /// at least 64. The function ignores the release velocity of Note Off and + /// the value of controller 123. All Notes Off acts on all channels. /// /// For other messages with valid ranges of status and data bytes, the /// function returns `Ok(None)`. This function is not a parser for a MIDI @@ -80,7 +109,15 @@ impl MidiEvent { channel, note: bytes[1], }), + 0xb0 if bytes[1] == 64 => Some(Self::SustainPedal { + channel, + held: bytes[2] >= 64, + }), 0xb0 if bytes[1] == 123 => Some(Self::AllNotesOff), + 0xe0 => Some(Self::PitchBend { + channel, + value: ((i16::from(bytes[2]) << 7) | i16::from(bytes[1])) - 8192, + }), _ => None, }) } @@ -89,9 +126,9 @@ impl MidiEvent { /// /// # Errors /// - /// Returns [`Error::InvalidMidi`] if a channel is more than 15, or if a - /// note or a velocity is more than 127. Zero velocity and All Notes Off - /// are valid. + /// Returns [`Error::InvalidMidi`] if a channel is more than 15, if a note + /// or a velocity is more than 127, or if a pitch-bend value is outside + /// `-8192..=8191`. Zero velocity and All Notes Off are valid. pub fn validate(&self) -> Result<(), Error> { match *self { Self::NoteOn { @@ -102,11 +139,30 @@ impl MidiEvent { Self::NoteOff { channel, note } if channel > 15 || note > 127 => { Err(Error::InvalidMidi) } + Self::PitchBend { channel, value } + if channel > 15 || !(-8192..=8191).contains(&value) => + { + Err(Error::InvalidMidi) + } + Self::SustainPedal { channel, .. } if channel > 15 => Err(Error::InvalidMidi), _ => Ok(()), } } } +/// Returns the Q14 frequency multiplier for `value` and `semitones`. +/// +/// If `value` is zero or `semitones` is zero, this function returns unity. +/// Negative values divide by 8192, and positive values divide by 8191. +pub(crate) fn bend_ratio(value: i16, semitones: f32) -> Q14 { + if value == 0 || semitones == 0.0 { + return Q14::ONE; + } + let scale = if value < 0 { 8192.0 } else { 8191.0 }; + let offset = (f64::from(value) / scale) * f64::from(semitones); + Q14::from_f64((offset * std::f64::consts::LN_2 / 12.0).exp()) +} + /// Returns the period of MIDI `note` at `rate`, as a Q6 count of samples. pub(crate) fn note_period(rate: f32, note: i32) -> Q6 { let period = ((f64::from(rate) / 440.0) diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..ac426bf 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -68,17 +68,19 @@ pub enum MultiVoiceMode { /// empty or correction is disabled, the ratio moves toward 1.0 at the same /// 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. +/// Note events for correction MIDI replace the active note table. They do not +/// change this configuration. Pitch bend scales the target ratio, and the +/// sustain pedal holds released keys. A change to `notes` or to `enabled` +/// loads the configured mask again. Reset releases the correction keys 0..=126 +/// and clears sustain and pitch bend. It keeps key 127 and the active note +/// table. Key 127 has no effect on the note table. /// /// 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 /// rate: /// - An initial mask that is not chromatic. /// - A later change to the mask or to `enabled`. -/// - A correction MIDI event. +/// - A correction MIDI event that reloads the note table. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -106,6 +108,24 @@ 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, + /// The maximum pitch bend in semitones, 0..=24. The default is 2. + /// + /// A [`MidiEvent::PitchBend`] value of -8192 lowers the target pitch by + /// this range, and 8191 raises it by this range. Zero disables pitch bend. + /// In JavaScript, the field is optional and an absent value gives the + /// default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_pitch_bend_semitones"), + tsify(optional) + )] + pub pitch_bend_semitones: f32, +} + +/// The default pitch-bend range in semitones. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_pitch_bend_semitones() -> f32 { + 2.0 } impl Default for CorrectionConfig { @@ -114,6 +134,7 @@ impl Default for CorrectionConfig { enabled: true, notes: NoteMask::default(), retune_ms: 0.0, + pitch_bend_semitones: 2.0, } } } @@ -121,20 +142,27 @@ impl Default for CorrectionConfig { impl CorrectionConfig { /// Validates all fields, also if correction is disabled. /// - /// All values of `enabled` and `notes` are valid. `retune_ms` must be - /// finite and in its documented inclusive range. Validation does not - /// clamp values. It does not change the state of the processor. + /// All values of `enabled` and `notes` are valid. `retune_ms` and + /// `pitch_bend_semitones` must be finite and in their documented inclusive + /// ranges. Validation does not clamp values. It does not change the state + /// of the processor. /// /// # Errors /// /// Returns [`Error::InvalidConfig`], with the dotted path of the field and - /// the problem, if `retune_ms` is not valid. + /// the problem, if `retune_ms` or `pitch_bend_semitones` is not valid. pub fn validate(self) -> Result<(), Error> { check_range( "resynthesis.correction.retune_ms", self.retune_ms, 0.0, 400.0, + )?; + check_range( + "resynthesis.correction.pitch_bend_semitones", + self.pitch_bend_semitones, + 0.0, + 24.0, ) } } @@ -509,6 +537,7 @@ impl Resynthesis { // configured rate become active. let mut scale = CorrectionTable::new(SampleRate::Hz44100, NoteMask::default()); scale.set_sample_rate(rate); + scale.set_pitch_bend_semitones(config.correction.pitch_bend_semitones); if config.correction.notes != NoteMask::default() { scale.set_notes(config.correction.notes); } @@ -650,6 +679,10 @@ impl Resynthesis { self.scale.set_notes(config.correction.notes); self.scale_initialized = false; } + if old.correction.pitch_bend_semitones != config.correction.pitch_bend_semitones { + self.scale + .set_pitch_bend_semitones(config.correction.pitch_bend_semitones); + } if old.pitch_ratio != config.pitch_ratio { self.configure_shift_filters(); } @@ -729,8 +762,9 @@ 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_initialized = false; + if self.scale.apply_validated_midi(event) { + self.scale_initialized = false; + } } /// Returns the finite number of frames for a drain of resynthesis. @@ -916,6 +950,9 @@ impl Resynthesis { if denominator != Q6::ZERO { target_ratio = target.div(denominator); } + if self.scale.bend_ratio != Q14::ONE { + target_ratio = target_ratio.mul(self.scale.bend_ratio); + } } self.correction = self.correction_decay.mul(self.correction - target_ratio) + target_ratio; } diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..c78deab 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -1,6 +1,7 @@ //! Pitch classes and correction tables, made from scales or held MIDI notes. -use crate::midi::MidiEvent; +use crate::midi::{bend_ratio, MidiEvent}; +use crate::numeric::fixed::Q14; use crate::SampleRate; /// One of the twelve notes in an octave. @@ -165,6 +166,17 @@ pub(crate) struct CorrectionTable { /// /// A reset keeps key 127, and mask creation excludes it. pub keyboard: [bool; 128], + /// The keys that Note Off released while sustain was active. + sustained: [bool; 128], + /// The sustain-pedal state (controller 64) for each MIDI channel. + sustain_held: [bool; 16], + /// The centered 14-bit pitch bend across all channels of correction MIDI. + pitch_bend: i16, + /// The configured maximum pitch bend in semitones. + pitch_bend_semitones: f32, + /// The Q14 frequency multiplier from `pitch_bend` and + /// `pitch_bend_semitones`. + pub bend_ratio: Q14, } impl CorrectionTable { @@ -177,6 +189,11 @@ impl CorrectionTable { notes: [0; 12], base_periods: [0; 12], keyboard: [false; 128], + sustained: [false; 128], + sustain_held: [false; 16], + pitch_bend: 0, + pitch_bend_semitones: 2.0, + bend_ratio: Q14::ONE, }; result.set_sample_rate(rate); result.set_notes(mask); @@ -219,26 +236,65 @@ impl CorrectionTable { self.midpoints[0] = self.midpoints[self.count] / 2; } } - /// Releases keys 0..=126, and keeps key 127 and the active target table. + /// Updates the pitch-bend range and calculates `bend_ratio` again. + pub(crate) fn set_pitch_bend_semitones(&mut self, semitones: f32) { + self.pitch_bend_semitones = semitones; + self.bend_ratio = bend_ratio(self.pitch_bend, semitones); + } + /// Releases keys 0..=126, clears sustain and pitch bend, and keeps key 127 + /// and the active target table. /// - /// A later MIDI event builds the table again from the new keyboard state. + /// A later note or All Notes Off event builds the table again from the new + /// keyboard state. pub(crate) fn reset(&mut self) { self.keyboard[..127].fill(false); + self.sustained.fill(false); + self.sustain_held.fill(false); + self.pitch_bend = 0; + self.bend_ratio = Q14::ONE; } - /// Applies an event whose MIDI ranges were already checked. - pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) { + /// Applies an event whose MIDI ranges were already checked, and returns + /// `true` if the active note table reloaded. + pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) -> bool { match event { - MidiEvent::NoteOn { note, velocity, .. } => { - self.keyboard[note as usize] = velocity != 0 + MidiEvent::NoteOn { note, velocity, .. } if velocity != 0 => { + let idx = usize::from(note); + self.keyboard[idx] = true; + self.sustained[idx] = false; + } + MidiEvent::NoteOn { note, .. } | MidiEvent::NoteOff { note, .. } => { + let idx = usize::from(note); + if self.keyboard[idx] { + self.keyboard[idx] = false; + if self.sustain_held.contains(&true) { + self.sustained[idx] = true; + } + } + } + MidiEvent::PitchBend { value, .. } => { + self.pitch_bend = value; + self.bend_ratio = bend_ratio(value, self.pitch_bend_semitones); + return false; + } + MidiEvent::SustainPedal { channel, held } => { + self.sustain_held[usize::from(channel)] = held; + if held || self.sustain_held.contains(&true) { + return false; + } + let had_sustained = self.sustained[..127].contains(&true); + self.sustained.fill(false); + if !had_sustained { + return false; + } } - 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]; + mask[i % 12] |= self.keyboard[i] || self.sustained[i]; } self.set_notes(NoteMask(mask)); + true } } diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..a904892 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -20,12 +20,16 @@ //! - Enum values are strings. //! - Each object must contain all required fields. //! - The optional harmony `voices` field defaults to 4. +//! - The optional correction and harmony `pitchBendSemitones` fields are in +//! 0..=24 and default to 2. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use -//! `{ type, channel, note, velocity }`, with the fields that apply to the -//! selected variant. The TypeScript declarations come from the same Rust types -//! that validation uses. +//! a `type` tag (`"noteOn"`, `"noteOff"`, `"pitchBend"`, `"sustainPedal"` or +//! `"allNotesOff"`) and the fields for that variant: `channel` (0..=15), +//! `note` (0..=127), `velocity` (0..=127), `value` (-8192..=8191) or `held`. +//! The TypeScript declarations come from the same Rust types that validation +//! uses. //! //! The class allocates the PCM storage at construction and uses it again for //! each block. These operations can allocate: