diff --git a/README.md b/README.md index a06715f..10b350f 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,8 @@ multi-voice mixes. `0..=1`. The default is 0. `resynthesis.correction.flex_tune` sets the outer fraction of each half-bin where pull toward the target decreases, in `0..=1`. The default is 0, which applies full pull across the whole bin. +`resynthesis.correction.pitch_bend_semitones` sets the maximum correction pitch +bend, in `0..=24`. The default is 2. `resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The dry path starts after Warm and has a delay of 1,593 frames. All six reverb @@ -203,7 +205,8 @@ with `resynthesis.harmony.source`: `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. +and MIDI sources ignore this field. `resynthesis.harmony.pitch_bend_semitones` +sets the maximum harmony pitch bend, in `0..=24`. The default is 2. `resynthesis.harmony_gain` scales the four harmony voices in mono and in stereo. It does not scale the lead voice. @@ -580,7 +583,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`. If an optional field is absent or `undefined`, it gets its default. `resynthesis.correction.humanize` and -`resynthesis.correction.flexTune` default to 0, and +`resynthesis.correction.flexTune` default to 0, +`resynthesis.correction.pitchBendSemitones` and +`resynthesis.harmony.pitchBendSemitones` default to 2 (in `0..=24`), and `resynthesis.harmony.voices` defaults to 4. The conversion ignores extra object properties. The generated declarations contain the parameter documentation from the Rust types. @@ -611,6 +616,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/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index 0f6a77f..2df01e1 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -73,6 +73,10 @@ const EXACT_REPLACEMENTS = [ ], ["[`crate::HarmonyConfig::portamento_ms`]", "`HarmonyConfig.portamentoMs`"], ["[`crate::HarmonyConfig::voices`]", "`HarmonyConfig.voices`"], + [ + "[`crate::HarmonyConfig::pitch_bend_semitones`]", + "`HarmonyConfig.pitchBendSemitones`", + ], ["[`ReverbConfig::mode`]", "`ReverbConfig.mode`"], ["[`ReverbConfig::mix`]", "`ReverbConfig.mix`"], ["[`ReverbConfig::diffusion`]", "`ReverbConfig.diffusion`"], @@ -95,12 +99,17 @@ const EXACT_REPLACEMENTS = [ ["[`Self::Echo`]", '`"echo"`'], ["[`ReverbMode::Echo`]", '`"echo"`'], ["[`Self::MidiChannels`]", '`"midiChannels"`'], + ["[`crate::HarmonySource::MidiChannels`]", '`"midiChannels"`'], + ["[`crate::HarmonySource::MidiOmni`]", '`"midiOmni"`'], + ["[`crate::HarmonySource::ChordViaMidi`]", '`"chordViaMidi"`'], ["[`HarmonySource::MidiChannels`]", '`"midiChannels"`'], ["[`HarmonySource::FixedInterval`]", '`"fixedInterval"`'], ["[`HarmonySource::SmartInterval`]", '`"smartInterval"`'], ["[`HarmonySource::ChordByName`]", '`"chordByName"`'], ["[`HarmonySource::ChordByDegree`]", '`"chordByDegree"`'], ["[`MultiVoiceMode::Choir`]", '`"choir"`'], + ["[`MidiEvent::PitchBend`]", '`"pitchBend"`'], + ["[`Self::NoteOff`]", '`"noteOff"`'], ["`None`", "`undefined`"], ["`u64::MAX`", "`2n ** 64n - 1n`"], ["`0x1234_abcd`", "`0x1234abcdn`"], @@ -157,7 +166,7 @@ const PROSE_REPLACEMENTS = [ "The default enables all twelve pitch classes (`true` in every slot). All\ncombinations of flags are valid, which includes all `false` values.", ], [ - /Use\s+\[`crate::ControlEvent::Midi`\]\s+for\s+harmony\.\s+Use\s+\[`crate::ControlEvent::CorrectionMidi`\]\s+for\s+the\s+independent\s+correction\s+keyboard\.\s+The\s+typed\s+representation\s+can\s+contain\s+`u8`\s+values\s+that\s+are\s+not\s+valid\.\s+\[`Self::validate`\]\s+and\s+the\s+event\s+preflight\s+of\s+the\s+processor\s+check\s+the\s+MIDI\s+ranges\./g, + /Use\s+\[`crate::ControlEvent::Midi`\]\s+for\s+harmony\.\s+Use\s+\[`crate::ControlEvent::CorrectionMidi`\]\s+for\s+the\s+independent\s+correction\s+keyboard\.\s+The\s+typed\s+representation\s+can\s+contain\s+`u8`\s+and\s+`i16`\s+values\s+that\s+are\s+not\s+valid\.\s+\[`Self::validate`\]\s+and\s+the\s+event\s+preflight\s+of\s+the\s+processor\s+check\s+the\s+MIDI\s+ranges\./g, 'Use `{ type: "midi", value }` in `ControlEvent` for harmony. Use\n`{ type: "correctionMidi", value }` for the independent correction\nkeyboard. Number fields can hold values outside the MIDI ranges, and\n`Tunelet` checks the ranges before it processes a block.', ], [ diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..397f7c7 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -315,13 +315,18 @@ function verifyRuntimeImport(consumerDir, packageName) { "const initialConfig = rootModule.defaultConfig();", "initialConfig.resynthesis.correction.humanize = undefined;", "initialConfig.resynthesis.correction.flexTune = undefined;", + "initialConfig.resynthesis.correction.pitchBendSemitones = undefined;", "initialConfig.resynthesis.harmony.voices = undefined;", + "initialConfig.resynthesis.harmony.pitchBendSemitones = undefined;", "const processor = new rootModule.Tunelet(48000, 128, initialConfig);", "try {", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + " assert.equal(processor.config().resynthesis.correction.pitchBendSemitones, 2);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + " assert.equal(processor.config().resynthesis.harmony.pitchBendSemitones, 2);", " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", + " assert.equal(typeof processor.controlActivity().harmonyPitchBendSemitones, \"boolean\");", " const initialTelemetry = processor.telemetry();", " assert.ok(initialTelemetry.voiceRatios instanceof Float32Array);", " assert.ok(initialTelemetry.voiceGains instanceof Float32Array);", @@ -354,21 +359,44 @@ function verifyRuntimeImport(consumerDir, packageName) { " const omittedCorrectionConfig = processor.config();", " delete omittedCorrectionConfig.resynthesis.correction.humanize;", " delete omittedCorrectionConfig.resynthesis.correction.flexTune;", + " delete omittedCorrectionConfig.resynthesis.correction.pitchBendSemitones;", + " delete omittedCorrectionConfig.resynthesis.harmony.pitchBendSemitones;", " processor.setConfig(omittedCorrectionConfig);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + " assert.equal(processor.config().resynthesis.correction.pitchBendSemitones, 2);", + " assert.equal(processor.config().resynthesis.harmony.pitchBendSemitones, 2);", "", " const mono = new Int16Array(128);", " const eventResynthesis = processor.config().resynthesis;", " eventResynthesis.correction.humanize = undefined;", " eventResynthesis.correction.flexTune = undefined;", + " eventResynthesis.correction.pitchBendSemitones = undefined;", " eventResynthesis.harmony.voices = undefined;", + " eventResynthesis.harmony.pitchBendSemitones = undefined;", " processor.processMono(mono, [", ' { offset: 0, event: { type: "resynthesis", value: eventResynthesis } },', " ]);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", + " assert.equal(processor.config().resynthesis.correction.pitchBendSemitones, 2);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + " assert.equal(processor.config().resynthesis.harmony.pitchBendSemitones, 2);", + " processor.processMono(mono, [", + ' { offset: 0, event: { type: "midi", value: { type: "sustainPedal", channel: 0, held: true } } },', + ' { offset: 0, event: { type: "midi", value: { type: "noteOn", channel: 0, note: 60, velocity: 100 } } },', + ' { offset: 16, event: { type: "midi", value: { type: "pitchBend", channel: 0, value: 4096 } } },', + ' { offset: 32, event: { type: "midi", value: { type: "noteOff", channel: 0, note: 60 } } },', + ' { offset: 48, event: { type: "correctionMidi", value: { type: "sustainPedal", channel: 0, held: true } } },', + ' { offset: 48, event: { type: "correctionMidi", value: { type: "noteOn", channel: 0, note: 69, velocity: 100 } } },', + ' { offset: 64, event: { type: "correctionMidi", value: { type: "pitchBend", channel: 0, value: -4096 } } },', + ' { offset: 80, event: { type: "correctionMidi", value: { type: "noteOff", channel: 0, note: 69 } } },', + ' { offset: 96, event: { type: "midi", value: { type: "sustainPedal", channel: 0, held: false } } },', + ' { offset: 96, event: { type: "correctionMidi", value: { type: "sustainPedal", channel: 0, held: false } } },', + ' { offset: 112, event: { type: "midi", value: { type: "pitchBend", channel: 0, value: 0 } } },', + ' { offset: 112, event: { type: "correctionMidi", value: { type: "pitchBend", channel: 0, value: 0 } } },', + " ]);", + " assert.equal(processor.feedback().processedFrames, 256n);", "", " const input = new Int16Array(128);", " const left = new Int16Array(128);", @@ -738,6 +766,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " TuneletAudioViews,", " type ControlActivity,", " type ControlEvent,", + " type MidiEvent,", " type ParameterControl,", " type ProcessorConfig,", " type ResynthesisConfig,", @@ -748,6 +777,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " initSync as wasmInitSync,", " type InitInput,", " type InitOutput,", + " type MidiEvent as WasmMidiEvent,", " type ParameterControl as WasmParameterControl,", " type SyncInitInput,", `} from ${wasmLiteral};`, @@ -778,10 +808,12 @@ function verifyTypeDeclarations(consumerDir, packageName) { " ...baseConfig.resynthesis.correction,", " humanize: optionalVoices,", " flexTune: optionalVoices,", + " pitchBendSemitones: optionalVoices,", " },", " harmony: {", " ...baseConfig.resynthesis.harmony,", " voices: optionalVoices,", + " pitchBendSemitones: optionalVoices,", " },", " },", " };", @@ -835,8 +867,12 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", + ' const bendEvent: MidiEvent & WasmMidiEvent = { type: "pitchBend", channel: 0, value: 4096 };', + ' const sustainEvent: MidiEvent & WasmMidiEvent = { type: "sustainPedal", channel: 0, held: true };', " processor.processMono(input, [", ' { offset: 0, event: { type: "resynthesis", value: resynthesisUpdate } },', + ' { offset: 0, event: { type: "midi", value: sustainEvent } },', + ' { offset: 0, event: { type: "correctionMidi", value: bendEvent } },', " ]);", ' const dryMixParameter: ParameterControl & WasmParameterControl = { type: "dryMix", value: 0.25 };', ' const humanizeParameter: ParameterControl & WasmParameterControl = { type: "humanize", value: 0.5 };', diff --git a/src/config.rs b/src/config.rs index 741d08c..1ccb35b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -253,6 +253,7 @@ impl ProcessorConfig { harmony_voicing_spread_percent: harmony && chord, harmony_portamento_ms: harmony && (!interval || interval_voices), harmony_voices: harmony && interval, + harmony_pitch_bend_semitones: harmony && (!interval || interval_voices), harmony_gain: harmony && (!interval || interval_voices), reverb_mode: reverb, reverb_mix: reverb, @@ -312,6 +313,8 @@ pub struct ControlActivity { pub harmony_portamento_ms: bool, /// `true` if [`crate::HarmonyConfig::voices`] is active. pub harmony_voices: bool, + /// `true` if [`crate::HarmonyConfig::pitch_bend_semitones`] is active. + pub harmony_pitch_bend_semitones: bool, /// `true` if [`ResynthesisConfig::harmony_gain`] is active. pub harmony_gain: bool, /// `true` if [`ReverbConfig::mode`] is active. diff --git a/src/harmony.rs b/src/harmony.rs index f2adfe3..653cc0a 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::{velocity_gain, MidiEvent}; +use crate::midi::{bend_ratio, 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,21 @@ pub struct HarmonyConfig { tsify(optional, type = "number | undefined") )] 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 + /// or `undefined` value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_pitch_bend_semitones", + deserialize_with = "deserialize_pitch_bend_semitones" + ), + tsify(optional, type = "number | undefined") + )] + pub pitch_bend_semitones: f32, } /// The default count of interval voices: all of them. @@ -343,6 +359,21 @@ fn deserialize_voices<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Resu Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_voices)) } +/// The default pitch-bend range in semitones. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_pitch_bend_semitones() -> f32 { + 2.0 +} + +/// Decodes an optional pitch-bend range and maps an absent value to 2. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_pitch_bend_semitones<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_pitch_bend_semitones)) +} + impl Default for HarmonyConfig { fn default() -> Self { Self { @@ -358,6 +389,7 @@ impl Default for HarmonyConfig { voicing_spread_percent: 0.0, portamento_ms: 0.0, voices: HARMONY_VOICES as u8, + pitch_bend_semitones: 2.0, } } } @@ -382,7 +414,8 @@ impl HarmonyConfig { validate_voices(self.voices)?; validate_register_percent(self.register_percent)?; validate_voicing_spread_percent(self.voicing_spread_percent)?; - validate_portamento_ms(self.portamento_ms) + validate_portamento_ms(self.portamento_ms)?; + validate_pitch_bend_semitones(self.pitch_bend_semitones) } } @@ -448,6 +481,16 @@ pub(crate) fn validate_portamento_ms(portamento_ms: f32) -> Result<(), Error> { ) } +/// Checks the range of the harmony pitch-bend limit. +fn validate_pitch_bend_semitones(pitch_bend_semitones: f32) -> Result<(), Error> { + check_range( + "resynthesis.harmony.pitch_bend_semitones", + pitch_bend_semitones, + 0.0, + 24.0, + ) +} + /// The prepared controller of periods and gains, and the MIDI allocator, for /// four voices. /// @@ -519,6 +562,21 @@ 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 while sustain was + /// active. + 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, @@ -553,6 +611,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)), }; @@ -585,6 +650,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.source != config.source || old.key != config.key || old.scale != config.scale @@ -634,6 +706,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. /// @@ -650,6 +723,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(); @@ -775,21 +855,35 @@ 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 on a - /// channel that the MIDI source uses. The omni sources steal the oldest - /// voice and resume the newest pending note. If two orders are equal, - /// strict comparisons keep the lowest voice index or pitch. Each Note Off - /// clears the pending entry of its pitch. All Notes Off calls `reset` and - /// returns `false`. The gain releases occur at the next control steps. + /// This occurs after a new note assignment, after an unheld Note Off or + /// pedal release on a channel that the MIDI source uses, and after an + /// active Pitch Bend. 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. 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, @@ -799,84 +893,204 @@ impl HarmonyState { }; self.event_counter = self.event_counter.wrapping_add(1); let gain = self.gains[velocity as usize]; - if velocity == 0 { - self.clear_pending(note); - } let control_due = match 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.voice_has_note(voice, note) { + self.voice_sustained[voice] = true; + active = true; + } + } + if active { + self.sustained[note] = true; + } + return false; + } + self.sustained[note] = false; + self.clear_pending(note); let mut released = None; for voice in 0..HARMONY_VOICES { if self.voice_has_note(voice, note) { 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, &order) in self.pending_order.iter().enumerate() { - if order > best_order { - best_order = order; - best = Some(pending); - } - } - if let Some(pending) = best { - let pending_gain = self.pending_gain[pending]; - self.assign(voice, pending, pending_gain, best_order); - self.clear_pending(pending); - } + self.resume_pending(voice); } true - } else if let Some(voice) = - (0..HARMONY_VOICES).find(|&v| self.voice_has_note(v, note)) - { - self.midi_gain[voice] = gain; - self.midi_order[voice] = self.event_counter; - false } else { - let voice = if let Some(free) = - (0..HARMONY_VOICES).find(|&v| self.midi_period[v] == Q6::ZERO) + self.sustained[note] = false; + if let Some(voice) = (0..HARMONY_VOICES).find(|&v| self.voice_has_note(v, note)) { - self.portamento_period[free] = Q6::ZERO; - free + self.voice_sustained[voice] = false; + self.midi_gain[voice] = gain; + self.midi_order[voice] = self.event_counter; + false } else { - let mut oldest = 0; - for i in 1..HARMONY_VOICES { - if self.midi_order[i] < self.midi_order[oldest] { - oldest = i; + self.clear_pending(note); + let voice = if let Some(free) = + (0..HARMONY_VOICES).find(|&v| self.midi_period[v] == Q6::ZERO) + { + self.portamento_period[free] = Q6::ZERO; + free + } else { + let mut oldest = 0; + for i in 1..HARMONY_VOICES { + if self.midi_order[i] < self.midi_order[oldest] { + oldest = i; + } } - } - let stolen = self.midi_note[oldest] as usize; - self.pending_gain[stolen] = self.midi_gain[oldest]; - self.pending_order[stolen] = self.midi_order[oldest]; - oldest - }; - self.assign(voice, note, gain, self.event_counter); - true + let stolen = self.midi_note[oldest] as usize; + self.pending_gain[stolen] = self.midi_gain[oldest]; + self.pending_order[stolen] = self.midi_order[oldest]; + oldest + }; + self.voice_sustained[voice] = false; + self.assign(voice, note, gain, self.event_counter); + true + } } } HarmonySource::MidiChannels if channel < 4 => { let voice = usize::from(channel); if velocity == 0 { if self.voice_has_note(voice, note) { - self.midi_period[voice] = Q6::ZERO; + if self.sustain_held[voice] { + self.voice_sustained[voice] = true; + self.sustained[note] = true; + false + } else { + self.midi_period[voice] = Q6::ZERO; + self.voice_sustained[voice] = false; + self.clear_pending(note); + true + } + } else { + if !self.sustain_held[voice] { + self.clear_pending(note); + } + true } } 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, self.event_counter); + true + } + } + _ => { + if velocity == 0 && !self.sustain_held[usize::from(channel)] { + self.clear_pending(note); } - true + false } - _ => false, }; if self.config.source == HarmonySource::ChordViaMidi { self.setup_chord(); } control_due } + /// Sets the sustain-pedal state for `channel`. If sustain ends, releases + /// the sustained notes. + 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.clear_pending(pending); + } + } + 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 { + let mut released = false; + 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); + released = true; + } + } + if !self.sustain_held.contains(&true) { + self.sustained.fill(false); + } + return released; + } else if !self.sustain_held.contains(&true) { + self.sustained.fill(false); + self.voice_sustained.fill(false); + } + false + } + /// If no sustained voice slot holds `note`, clears `sustained[note]`. + fn clear_sustained_if_unused(&mut self, note: usize) { + let used = (0..HARMONY_VOICES) + .any(|voice| self.voice_sustained[voice] && self.voice_has_note(voice, note)); + if !used { + self.sustained[note] = false; + } + } + /// Resumes the pending note with the newest positive assignment order on + /// `voice`. + fn resume_pending(&mut self, voice: usize) { + let mut best_order = 0; + let mut best = None; + for (pending, &order) in self.pending_order.iter().enumerate() { + if order > best_order { + best_order = order; + best = Some(pending); + } + } + if let Some(pending) = best { + let pending_gain = self.pending_gain[pending]; + self.assign(voice, pending, pending_gain, best_order); + self.voice_sustained[voice] = self.sustained[pending]; + self.clear_pending(pending); + } + } /// If `voice` has an active MIDI assignment for `note`, returns `true`. fn voice_has_note(&self, voice: usize, note: usize) -> bool { self.midi_period[voice] != Q6::ZERO && self.midi_note[voice] == note as i32 @@ -900,7 +1114,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; @@ -926,7 +1141,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 188dec5..183286a 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -1,16 +1,17 @@ -//! MIDI note messages and the conversion of velocity to gain. +//! MIDI messages, pitch-bend ratios and the conversion of velocity to gain. -use crate::numeric::fixed::Q12; +use crate::numeric::fixed::{Q12, Q14}; 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)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), @@ -35,26 +36,56 @@ 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..=127 and loads the configured correction notes again. + /// 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..=127, sustained notes, + /// sustain pedals and pitch bend, and loads the configured correction + /// notes again. 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 +111,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 +128,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 +141,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 MIDI gain for `velocity`, quantized to Q12. /// /// For velocities 1..=127, the gain is `36 * velocity / 127 - 24` dB. diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..66a3710 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -62,17 +62,19 @@ pub enum MultiVoiceMode { /// period domain. /// /// Correction is enabled by default, with all chromatic notes, a retune time -/// of zero, zero humanize and zero flex-tune. Target selection and the -/// smoothing of the correction ratio occur at each update of the pitch -/// tracking. When a period is tracked, this update usually occurs every five -/// frames. If the active note table is empty or correction is disabled, the -/// ratio moves toward 1.0 with `retune_ms`. +/// of zero, zero humanize, zero flex-tune and a pitch-bend range of two +/// semitones. Target selection and the smoothing of the correction ratio occur +/// at each update of the pitch tracking. When a period is tracked, this update +/// usually occurs every five frames. If the active note table is empty or +/// correction is disabled, the ratio moves toward 1.0 with `retune_ms`. /// -/// While at least one key in 0..=127 is held, correction MIDI replaces the -/// active note table. It does not change this configuration. When all keys -/// release, on All Notes Off or on reset, the configured `notes` load again. -/// A change to `notes` or to `enabled` also loads the configured mask again. -/// Reset releases the correction keys 0..=127. +/// While at least one key in 0..=127 is held or sustained, correction MIDI +/// replaces the active note table. It does not change this configuration. +/// Pitch bend scales the target ratio, and the sustain pedal holds released +/// keys. When all keys release, on All Notes Off or on reset, the configured +/// `notes` load again. A change to `notes` or to `enabled` also loads the +/// configured mask again. Reset releases keys 0..=127 and clears sustain and +/// pitch bend. /// /// Construction loads the configured `notes` mask with the periods for the /// prepared sample rate. Later changes to `notes`, to `enabled` or from @@ -135,6 +137,21 @@ pub struct CorrectionConfig { tsify(optional, type = "number | undefined") )] pub flex_tune: 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 or `undefined` value + /// gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "default_pitch_bend_semitones", + deserialize_with = "deserialize_pitch_bend_semitones" + ), + tsify(optional, type = "number | undefined") + )] + pub pitch_bend_semitones: f32, } /// Decodes an optional correction control and maps an absent value to 0. @@ -146,6 +163,21 @@ fn deserialize_zero_f32<'de, D: serde::Deserializer<'de>>( Ok(Option::::deserialize(deserializer)?.unwrap_or(0.0)) } +/// The default pitch-bend range in semitones. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_pitch_bend_semitones() -> f32 { + 2.0 +} + +/// Decodes an optional pitch-bend range and maps an absent value to 2. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_pitch_bend_semitones<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_pitch_bend_semitones)) +} + impl Default for CorrectionConfig { fn default() -> Self { Self { @@ -154,6 +186,7 @@ impl Default for CorrectionConfig { retune_ms: 0.0, humanize: 0.0, flex_tune: 0.0, + pitch_bend_semitones: 2.0, } } } @@ -161,10 +194,10 @@ impl Default for CorrectionConfig { impl CorrectionConfig { /// Validates all fields, also if correction is disabled. /// - /// All values of `enabled` and `notes` are valid. `retune_ms`, `humanize` - /// and `flex_tune` must be finite and in their documented inclusive ranges. - /// Validation does not clamp values. It does not change the state of the - /// processor. + /// All values of `enabled` and `notes` are valid. `retune_ms`, `humanize`, + /// `flex_tune` 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 /// @@ -173,7 +206,8 @@ impl CorrectionConfig { pub fn validate(self) -> Result<(), Error> { validate_retune_ms(self.retune_ms)?; validate_humanize(self.humanize)?; - validate_flex_tune(self.flex_tune) + validate_flex_tune(self.flex_tune)?; + validate_pitch_bend_semitones(self.pitch_bend_semitones) } } @@ -192,6 +226,16 @@ pub(crate) fn validate_flex_tune(flex_tune: f32) -> Result<(), Error> { check_range("resynthesis.correction.flex_tune", flex_tune, 0.0, 1.0) } +/// Checks the range of the correction pitch-bend limit. +fn validate_pitch_bend_semitones(pitch_bend_semitones: f32) -> Result<(), Error> { + check_range( + "resynthesis.correction.pitch_bend_semitones", + pitch_bend_semitones, + 0.0, + 24.0, + ) +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -669,6 +713,9 @@ impl Resynthesis { drift_amount: Q14::ZERO, previous_output: [Q14::ZERO; 2], }; + result + .scale + .set_pitch_bend_semitones(config.correction.pitch_bend_semitones); result.configure_all(); result.configure_shift_filters(); result.create_delays(); @@ -856,6 +903,10 @@ impl Resynthesis { if old.correction.flex_tune != config.correction.flex_tune { self.configure_flex_tune(); } + 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_pitch_ratio(); self.configure_shift_filters(); @@ -1156,10 +1207,13 @@ impl Resynthesis { /// Applies a correction MIDI event that the API or the block code checked /// before. pub(crate) fn apply_correction_midi(&mut self, event: MidiEvent) { - self.scale - .apply_validated_midi(event, self.config.correction.notes); - self.scale_initialized = false; - self.dwell = Q14::ZERO; + if self + .scale + .apply_validated_midi(event, self.config.correction.notes) + { + self.scale_initialized = false; + self.dwell = Q14::ZERO; + } } /// Returns the finite number of frames for a drain of resynthesis. @@ -1427,6 +1481,9 @@ impl Resynthesis { } } } + if self.scale.bend_ratio != Q14::ONE { + target_ratio = target_ratio.mul(self.scale.bend_ratio); + } } else { self.dwell = Q14::ZERO; } diff --git a/src/scale.rs b/src/scale.rs index aa489cc..031cd49 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. @@ -164,6 +165,17 @@ pub(crate) struct CorrectionTable { base_periods: [i32; 12], /// The held MIDI keys 0..=127. 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 { @@ -176,6 +188,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); @@ -226,33 +243,76 @@ impl CorrectionTable { self.midpoints[0] = self.midpoints[self.count] / 2; } } - /// Releases keys 0..=127 and loads `notes` again. + /// 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..=127, clears sustain and pitch bend, and loads `notes` + /// again. pub(crate) fn reset(&mut self, notes: NoteMask) { self.keyboard.fill(false); + self.sustained.fill(false); + self.sustain_held.fill(false); + self.pitch_bend = 0; + self.bend_ratio = Q14::ONE; self.set_notes(notes); } - /// Applies an event whose MIDI ranges were already checked. + /// Applies an event whose MIDI ranges were already checked, and returns + /// `true` if the active note table reloaded. /// - /// If no key in 0..=127 is held, this method loads `notes` again. - pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent, notes: NoteMask) { + /// If sustain holds a released key, this method keeps the active note table + /// and returns `false`. If no key in 0..=127 is held or sustained, this + /// method loads `notes` again. + pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent, notes: NoteMask) -> bool { match event { - MidiEvent::NoteOn { note, velocity, .. } => { - self.keyboard[usize::from(note)] = 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; + return false; + } + } else if self.sustained[idx] { + return false; + } + } + 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.contains(&true); + self.sustained.fill(false); + if !had_sustained { + return false; + } } - MidiEvent::NoteOff { note, .. } => self.keyboard[usize::from(note)] = false, MidiEvent::AllNotesOff => { self.reset(notes); - return; + return true; } } let mut mask = [false; 12]; - for (i, &held) in self.keyboard.iter().enumerate() { - mask[i % 12] |= held; + for i in 0..128 { + mask[i % 12] |= self.keyboard[i] || self.sustained[i]; } if mask == [false; 12] { self.set_notes(notes); } else { self.set_notes(NoteMask(mask)); } + true } } diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..d2df62e 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -23,13 +23,17 @@ //! - Each object must contain all required fields. //! - The optional correction `humanize` and `flexTune` fields default to 0. //! - The optional harmony `voices` field defaults to 4. +//! - 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`. Scalar parameter //! events nest `{ type, value }` inside `{ type: "parameter", 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. +//! messages use a `type` tag (`"noteOn"`, `"noteOff"`, `"pitchBend"`, +//! `"sustainPedal"` or `"allNotesOff"`) and the fields for that variant. The +//! variant fields are `channel` (0..=15), `note` (0..=127), `velocity` +//! (0..=127), `value` (-8192..=8191) and `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. It also keeps an event buffer and uses that capacity again @@ -855,6 +859,7 @@ struct EventKeys { channel: JsValue, note: JsValue, velocity: JsValue, + held: JsValue, midi: JsValue, correction_midi: JsValue, output_gain: JsValue, @@ -868,6 +873,8 @@ struct EventKeys { reverb: JsValue, note_on: JsValue, note_off: JsValue, + pitch_bend: JsValue, + sustain_pedal: JsValue, all_notes_off: JsValue, f32_parameters: [ParameterKey; 27], u8_parameters: [ParameterKey; 2], @@ -884,6 +891,7 @@ impl EventKeys { channel: JsValue::from_str("channel"), note: JsValue::from_str("note"), velocity: JsValue::from_str("velocity"), + held: JsValue::from_str("held"), midi: JsValue::from_str("midi"), correction_midi: JsValue::from_str("correctionMidi"), output_gain: JsValue::from_str("outputGain"), @@ -897,6 +905,8 @@ impl EventKeys { reverb: JsValue::from_str("reverb"), note_on: JsValue::from_str("noteOn"), note_off: JsValue::from_str("noteOff"), + pitch_bend: JsValue::from_str("pitchBend"), + sustain_pedal: JsValue::from_str("sustainPedal"), all_notes_off: JsValue::from_str("allNotesOff"), f32_parameters: [ ParameterKey::new( @@ -1143,6 +1153,17 @@ fn decode_midi_event(value: &JsValue, keys: &EventKeys) -> Result Result { Ok(number as u8) } +/// Converts a JavaScript number into an `i16` integer. +fn decode_i16(value: &JsValue, field: &str) -> Result { + let Some(number) = value.as_f64() else { + return Err(JsError::new(&format!( + "{field} must be an integer in -32768..=32767" + ))); + }; + if !(-32768.0..=32767.0).contains(&number) || number.fract() != 0.0 { + return Err(JsError::new(&format!( + "{field} must be an integer in -32768..=32767" + ))); + } + Ok(number as i16) +} + +/// Converts a JavaScript value into a `bool`. +fn decode_bool(value: &JsValue, field: &str) -> Result { + value + .as_bool() + .ok_or_else(|| JsError::new(&format!("{field} must be a boolean"))) +} + /// Returns the first `points` entries of a reusable envelope buffer. If the /// buffer is shorter, it becomes `points` long first. ///