diff --git a/README.md b/README.md index a06715f..89634ec 100644 --- a/README.md +++ b/README.md @@ -223,14 +223,14 @@ processor. Select the process function for your output layout: -| Output layout | Function for input | Function for the tail | -| ------------------------------------ | --------------------------- | --------------------- | -| `[[i16; 2]]` stereo frames | `process` | `drain` | -| `[[f32; 2]]` stereo frames | `process_f32` | `drain_f32` | -| Separate `i16` left and right slices | `process_planar` | `drain_planar` | -| Separate `f32` left and right slices | `process_planar_f32` | `drain_planar_f32` | -| Mono `i16` slice | `process_mono_in_place` | `drain_mono` | -| Mono `f32` slice | `process_mono_in_place_f32` | `drain_mono_f32` | +| Output layout | Function for input | Function for packed MIDI | Function for the tail | +| ------------------------------------ | --------------------------- | --------------------------------- | --------------------- | +| `[[i16; 2]]` stereo frames | `process` | `process_with_midi` | `drain` | +| `[[f32; 2]]` stereo frames | `process_f32` | — | `drain_f32` | +| Separate `i16` left and right slices | `process_planar` | `process_planar_with_midi` | `drain_planar` | +| Separate `f32` left and right slices | `process_planar_f32` | — | `drain_planar_f32` | +| Mono `i16` slice | `process_mono_in_place` | `process_mono_in_place_with_midi` | `drain_mono` | +| Mono `f32` slice | `process_mono_in_place_f32` | — | `drain_mono_f32` | The `f32` methods convert `NaN` input samples to `0`. They clamp other input values to `-1.0..=1.0`, multiply by `32767.0` in `f64` and round to `i16`. They @@ -284,6 +284,14 @@ let events = [ processor.process(&input, &mut output, &events)?; ``` +For blocks that carry only three-byte MIDI messages, give `PackedMidiEvent` +records to `process_with_midi`, `process_planar_with_midi` or +`process_mono_in_place_with_midi`. Each record pairs `offset` with `bus` (`0` +for harmony MIDI, `1` for correction MIDI) and three MIDI bytes in +`[status, data1, data2]`. `MidiEvent::from_bytes` decodes the bytes without +heap allocation. If `MidiEvent::from_bytes` returns `Ok(None)`, the processor +ignores that message after the offset checks succeed. + ### Scalar parameters `ControlEvent::Parameter` accepts these `ParameterControl` variants. All ranges @@ -491,8 +499,10 @@ page that opens the JavaScript. | --------------------------------- | ------------------------------------------------------------------------ | | Shared initialization | `loadTunelet(source?)` | | Mono `Int16Array` to stereo | `process(input, left, right, events?)` | +| Stereo `Int16Array` with MIDI | `processWithMidi(input, left, right, midi)` | | Mono `Float32Array` to stereo | `processF32(input, left, right, events?)` | | In-place `Int16Array` mono | `processMono(audio, events?)` | +| In-place `Int16Array` with MIDI | `processMonoWithMidi(audio, midi)` | | In-place `Float32Array` mono | `processMonoF32(audio, events?)` | | Fixed `Float32` buffer offsets | `inputF32Ptr`, `leftF32Ptr`, `rightF32Ptr` | | Cached `Float32` memory views | `new TuneletAudioViews(memory, processor)` | @@ -517,9 +527,9 @@ in-place `Float32` calls. All blocks must fit in `maxBlockFrames`. This package does not install an AudioWorklet or an integration with an audio device. -For `process`, `processMono`, `drain`, `drainMono`, `processF32`, -`processMonoF32`, `drainF32` and `drainMonoF32`, pass `Int16Array` or -`Float32Array` buffers. These rules apply: +For `process`, `processWithMidi`, `processMono`, `processMonoWithMidi`, +`drain`, `drainMono`, `processF32`, `processMonoF32`, `drainF32` and +`drainMonoF32`, pass `Int16Array` or `Float32Array` buffers. These rules apply: - Stereo output arrays must not overlap. - The input can overlap an output, because the binding copies the input @@ -557,8 +567,8 @@ and `views.right`. These lifetime rules apply to `Float32` views: -- A new `Tunelet`, `setConfig`, `events`, `controlActivity`, feedback, - telemetry or `formantEnvelope` can grow Wasm memory and detach +- A new `Tunelet`, `setConfig`, `events`, packed MIDI, `controlActivity`, + feedback, telemetry or `formantEnvelope` can grow Wasm memory and detach `memory.buffer`. - Read `views.input` before each input write so `TuneletAudioViews` checks `memory.buffer` and refreshes detached views. @@ -615,6 +625,35 @@ 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. +For Web MIDI and `AudioWorklet` hosts, `processWithMidi` and +`processMonoWithMidi` accept packed three-byte MIDI messages in a +`Uint32Array`. The array contains `(offset, packedMessage)` word pairs, so +`midi.length` must be even. Word `2 * i` is the zero-based frame `offset` in +`0..frames`, and offsets must not decrease. + +Word `2 * i + 1` packs the bus and the three MIDI bytes as +`(bus << 24) | (status << 16) | (data1 << 8) | data2`: + +| Bits | Field | Valid range | Description | +| --------- | -------- | ------------- | --------------------------------------------- | +| `24..=31` | `bus` | `0..=1` | `0` for harmony MIDI, `1` for correction MIDI | +| `16..=23` | `status` | `0x80..=0xff` | MIDI status byte with channel `status & 0x0f` | +| `8..=15` | `data1` | `0..=127` | Note number or controller number | +| `0..=7` | `data2` | `0..=127` | Velocity or controller value | + +```ts +const midi = new Uint32Array(2); +midi[0] = 0; +midi[1] = (0 << 24) | (0x90 << 16) | (60 << 8) | 100; +processor.processWithMidi(input, left, right, midi); +``` + +The supported messages are Note On, Note On with zero velocity, Note Off and +controller 123 (All Notes Off). The processor ignores other three-byte +messages with valid byte ranges after the offset checks succeed. If +`midi.length` is odd, a bus is unknown or an offset or MIDI byte is not valid, +the call rejects the full block. The state and the output then do not change. + ### Feedback, telemetry and formant envelopes `controlActivity()` returns a `ControlActivity` object with camelCase boolean @@ -641,8 +680,10 @@ call with more points than before reserve memory. ### Memory allocation The constructor allocates reusable `i16` and `f32` buffers of length -`maxBlockFrames`. The processor also keeps an event buffer and uses its -capacity again across calls. `processF32InPlace`, `processMonoF32InPlace`, +`maxBlockFrames`. The processor also keeps event and `u32` MIDI buffers and +uses their capacity again across calls. `processWithMidi` and +`processMonoWithMidi` copy the `Uint32Array` in one pass and make no event +objects in JavaScript. `processF32InPlace`, `processMonoF32InPlace`, `drainF32InPlace` and `drainMonoF32InPlace` without `events` do not allocate Rust storage, make JavaScript views or call JavaScript imports. If Wasm memory does not grow, `TuneletAudioViews` also allocates no new `Float32Array` views @@ -656,6 +697,7 @@ allocate and grow Wasm memory: - Configuration conversion. - Supplied events when a call gives more events than before, or when an event converts a stage configuration. +- Packed MIDI words when a call gives more words than before. - Errors. - Control activity, feedback and telemetry. - The formant envelopes. diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..0a41c28 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -373,6 +373,7 @@ function verifyRuntimeImport(consumerDir, packageName) { " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", + " const midi = new Uint32Array([0, (0 << 24) | (0x90 << 16) | (60 << 8) | 100]);", ' processor.process(input, left, right, [', ' { offset: 0, event: { type: "parameter", value: { type: "dryMix", value: 0.25 } } },', ' { offset: 0, event: { type: "parameter", value: { type: "humanize", value: 0.5 } } },', @@ -381,6 +382,8 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.dryMix, 0.25);", " assert.equal(processor.config().resynthesis.correction.humanize, 0.5);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", + " processor.processWithMidi(input, left, right, midi);", + " processor.processMonoWithMidi(input, midi);", "} finally {", " processor.free();", "}", @@ -835,6 +838,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", + " const midi = new Uint32Array([0, (0 << 24) | (0x90 << 16) | (60 << 8) | 100]);", " processor.processMono(input, [", ' { offset: 0, event: { type: "resynthesis", value: resynthesisUpdate } },', " ]);", @@ -847,6 +851,8 @@ function verifyTypeDeclarations(consumerDir, packageName) { ' { offset: 0, event: { type: "parameter", value: humanizeParameter } },', ' { offset: 0, event: { type: "parameter", value: flexTuneParameter } },', " ]);", + " processor.processWithMidi(input, left, right, midi);", + " processor.processMonoWithMidi(input, midi);", " processor.beginDrain();", " const drained: number = processor.drain(left, right);", " const drainedMono: number = processor.drainMono(input);", @@ -1188,7 +1194,9 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { ["feedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+feedback\(\): Feedback;/], ["formantEnvelope", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+formantEnvelope\([^)]*\): boolean;/], ["constructor", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+constructor\([^)]*\);/], + ["processMonoWithMidi", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processMonoWithMidi\([^)]*\): void;/], ["processMono", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processMono\([^)]*\): void;/], + ["processWithMidi", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processWithMidi\([^)]*\): void;/], ["process", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+process\([^)]*\): void;/], ["setConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+setConfig\(config: ProcessorConfig\): void;/], ["takeFeedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeFeedback\(\): Feedback;/], diff --git a/src/error.rs b/src/error.rs index b971968..e75b95c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -110,6 +110,11 @@ pub enum EventProblem { /// The problem with the field. problem: ConfigProblem, }, + /// The packed MIDI event selects an unknown bus. + MidiBus { + /// The unsupported MIDI bus selector. + bus: u8, + }, /// The event has a MIDI message that is not valid. Midi, } @@ -183,6 +188,7 @@ impl fmt::Display for EventProblem { Self::OffsetOutsideBlock => f.write_str("offset is outside the block"), Self::OffsetDecreasing => f.write_str("offset is below the previous event's offset"), Self::Config { field, problem } => write!(f, "{field} {problem}"), + Self::MidiBus { bus } => write!(f, "MIDI bus {bus} must be 0 or 1"), Self::Midi => f.write_str("MIDI message is not valid"), } } diff --git a/src/events.rs b/src/events.rs index ef07dee..2aa2f8c 100644 --- a/src/events.rs +++ b/src/events.rs @@ -312,6 +312,149 @@ pub struct TimedEvent { pub event: ControlEvent, } +/// A MIDI message of three bytes that applies on a selected bus before the +/// zero-based input frame `offset`. +/// +/// Give packed MIDI controls to [`crate::Processor::process_with_midi`], +/// [`crate::Processor::process_planar_with_midi`] or +/// [`crate::Processor::process_mono_in_place_with_midi`]. Offsets obey the same +/// bounds and order rules as [`TimedEvent`]. +/// +/// `bus` selects the destination: `0` ([`Self::MIDI_BUS`]) sends to +/// [`ControlEvent::Midi`], and `1` ([`Self::CORRECTION_MIDI_BUS`]) sends to +/// [`ControlEvent::CorrectionMidi`]. [`MidiEvent::from_bytes`] decodes `bytes`. +/// If `MidiEvent::from_bytes` returns `Ok(None)`, the processor ignores that +/// message after the offset checks succeed. +/// +/// In a packed 32-bit message word, bits 24..=31 hold `bus` and bits 16..=23 +/// hold `bytes[0]`. Bits 8..=15 hold `bytes[1]` and bits 0..=7 hold +/// `bytes[2]`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PackedMidiEvent { + /// The zero-based frame offset in the block, `0..frames`. + pub offset: usize, + /// The target MIDI bus, `0..=1`: `0` for harmony MIDI or `1` for + /// correction MIDI. + pub bus: u8, + /// The MIDI message of three bytes `[status, data1, data2]`, where + /// `status` is in `0x80..=0xff` and `data1` and `data2` are in `0..=127`. + pub bytes: [u8; 3], +} + +impl PackedMidiEvent { + /// The bus selector `0` for [`ControlEvent::Midi`]. + pub const MIDI_BUS: u8 = 0; + + /// The bus selector `1` for [`ControlEvent::CorrectionMidi`]. + pub const CORRECTION_MIDI_BUS: u8 = 1; + + /// Unpacks a frame `offset` and a 32-bit `packed_message` word into an + /// event record. + /// + /// Bits 24..=31 set `bus` (`0..=1` for a valid bus). Bits 16..=23 set + /// `bytes[0]` (`0x80..=0xff` for a valid status byte). Bits 8..=15 set + /// `bytes[1]` and bits 0..=7 set `bytes[2]` (`0..=127` for valid data + /// bytes). This constructor does not validate the unpacked fields. + pub const fn from_packed(offset: usize, packed_message: u32) -> Self { + let [bus, status, data1, data2] = packed_message.to_be_bytes(); + Self { + offset, + bus, + bytes: [status, data1, data2], + } + } + + /// Packs `bus` and `bytes` into one 32-bit message word. + /// + /// Bits 24..=31 hold `bus`, bits 16..=23 hold `bytes[0]`, bits 8..=15 hold + /// `bytes[1]` and bits 0..=7 hold `bytes[2]`. + pub const fn packed_message(self) -> u32 { + u32::from_be_bytes([self.bus, self.bytes[0], self.bytes[1], self.bytes[2]]) + } + + /// Checks `bus` and decodes `bytes` into an optional MIDI control event. + pub(crate) fn decode_payload(self) -> Result, EventProblem> { + let is_correction = match self.bus { + Self::MIDI_BUS => false, + Self::CORRECTION_MIDI_BUS => true, + bus => return Err(EventProblem::MidiBus { bus }), + }; + let Some(midi) = MidiEvent::from_bytes(self.bytes).map_err(|_| EventProblem::Midi)? else { + return Ok(None); + }; + Ok(Some(if is_correction { + ControlEvent::CorrectionMidi(midi) + } else { + ControlEvent::Midi(midi) + })) + } +} + +/// A copyable packed MIDI entry for native slices and Wasm word pairs. +pub(crate) trait PackedMidiRecord: Copy { + /// Converts this entry into a [`PackedMidiEvent`]. + fn into_event(self) -> PackedMidiEvent; +} + +impl PackedMidiRecord for PackedMidiEvent { + fn into_event(self) -> PackedMidiEvent { + self + } +} + +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +impl PackedMidiRecord for [u32; 2] { + fn into_event(self) -> PackedMidiEvent { + PackedMidiEvent::from_packed(self[0] as usize, self[1]) + } +} + +/// A packed MIDI slice that is fully validated before the processor uses an +/// entry. +pub(crate) struct ValidatedPackedMidi<'a, T> { + /// The borrowed remainder of the checked slice, used in frame order. + remaining: &'a [T], +} + +impl<'a, T: PackedMidiRecord> ValidatedPackedMidi<'a, T> { + /// Checks the offsets, the order, the bus and the MIDI bytes in slice + /// order. + pub(crate) fn new(events: &'a [T], frames: usize) -> Result { + let mut previous = 0; + for (index, item) in events.iter().copied().enumerate() { + let event = item.into_event(); + let problem = if event.offset >= frames { + Some(EventProblem::OffsetOutsideBlock) + } else if event.offset < previous { + Some(EventProblem::OffsetDecreasing) + } else { + event.decode_payload().err() + }; + if let Some(problem) = problem { + return Err(Error::InvalidEvent { index, problem }); + } + previous = event.offset; + } + Ok(Self { remaining: events }) + } + + /// Consumes the next supported MIDI event at `frame`, or returns `None` if + /// no event is due. + pub(crate) fn next_at(&mut self, frame: usize) -> Option { + while let Some((first, remaining)) = self.remaining.split_first() { + let event = first.into_event(); + if event.offset != frame { + return None; + } + self.remaining = remaining; + if let Ok(Some(control)) = event.decode_payload() { + return Some(ValidatedEvent(control)); + } + } + None + } +} + /// An event slice that is fully validated before the processor uses an entry. pub(crate) struct ValidatedEvents<'a> { /// The borrowed remainder of the checked event slice, used in frame order. @@ -320,7 +463,7 @@ pub(crate) struct ValidatedEvents<'a> { /// A proof that an event passed validation. /// -/// Only `ValidatedEvents` can make this proof. +/// Only `ValidatedEvents` and `ValidatedPackedMidi` can make this proof. pub(crate) struct ValidatedEvent(ControlEvent); impl ValidatedEvent { diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..d756a4f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,8 +53,12 @@ //! empty block accepts no events. //! //! [`ControlEvent::Midi`] controls harmony. [`ControlEvent::CorrectionMidi`] -//! selects the correction pitch classes independently. The processor does not -//! keep MIDI controls in a queue after the current call. +//! selects the correction pitch classes independently. For blocks that carry +//! only three-byte MIDI messages, [`PackedMidiEvent`] and +//! [`Processor::process_with_midi`], [`Processor::process_planar_with_midi`] +//! and [`Processor::process_mono_in_place_with_midi`] decode messages directly +//! through [`MidiEvent::from_bytes`]. The processor does not keep MIDI +//! controls in a queue after the current call. //! //! # Feedback, latency and lifecycle //! @@ -105,9 +109,12 @@ //! //! To export JavaScript bindings and generated TypeScript definitions, enable //! the optional `wasm` feature for `wasm32-unknown-unknown`. The binding owns -//! reusable `i16` and `f32` buffers, and exposes fixed `f32` pointers for -//! in-place audio. Configuration conversion, event conversion, feedback objects -//! and errors cause more allocation at the JavaScript boundary. +//! reusable `i16`, `f32`, event and packed MIDI buffers, and exposes fixed +//! `f32` pointers for in-place audio. Configuration conversion, event +//! conversion, initial buffer growth, feedback objects and errors cause more +//! allocation at the JavaScript boundary. Packed MIDI calls copy a +//! `Uint32Array` in one call and do not allocate after the buffer reserves +//! enough capacity. //! Refer to the README for how to build the shared package for browsers and //! Node.js. @@ -140,7 +147,7 @@ pub use effects::punch::PunchConfig; pub use effects::reverb::{ReverbConfig, ReverbMode}; pub use effects::warm::WarmConfig; pub use error::{ConfigProblem, Error, EventProblem}; -pub use events::{ControlEvent, ParameterControl, TimedEvent}; +pub use events::{ControlEvent, PackedMidiEvent, ParameterControl, TimedEvent}; pub use formant::FormantConfig; pub use harmony::{ ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, diff --git a/src/processor.rs b/src/processor.rs index 9f8ae9b..0c76ef8 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -4,13 +4,13 @@ use crate::effects::alien::{self, Alien}; use crate::effects::punch::Punch; use crate::effects::reverb::{self, Reverb}; use crate::effects::warm::Warm; -use crate::events::{ValidatedEvent, ValidatedEvents}; +use crate::events::{PackedMidiRecord, ValidatedEvent, ValidatedEvents, ValidatedPackedMidi}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; use crate::{ - ControlActivity, ControlEvent, Error, ParameterControl, PrepareConfig, ProcessorConfig, - TimedEvent, + ControlActivity, ControlEvent, Error, PackedMidiEvent, ParameterControl, PrepareConfig, + ProcessorConfig, TimedEvent, }; /// Selects the output channel layout for the downmix and the peak meters. @@ -320,6 +320,123 @@ impl Processor { }) } + /// Processes mono PCM into `[left, right]` stereo frames with packed + /// three-byte MIDI controls. + /// + /// Each entry in `midi` pairs a zero-based frame `offset` with `bus` and + /// three MIDI bytes. `bus` is `0` for [`ControlEvent::Midi`] or `1` for + /// [`ControlEvent::CorrectionMidi`]. [`crate::MidiEvent::from_bytes`] + /// decodes `bytes`. If `MidiEvent::from_bytes` returns `Ok(None)`, the + /// processor ignores that message after the offset checks succeed. + /// + /// The buffer lengths, the block limit, the offset order, empty blocks and + /// drain cancellation obey the same rules as [`process`](Self::process). + /// This method does not allocate memory. + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] first and + /// [`Error::BlockTooLarge`] second. Then it checks [`Error::InvalidEvent`] + /// for the first event with an invalid offset, an unknown bus or invalid + /// MIDI bytes. All checks finish before the state or the output changes. + pub fn process_with_midi( + &mut self, + input: &[i16], + output: &mut [[i16; 2]], + midi: &[PackedMidiEvent], + ) -> Result<(), Error> { + Error::check_length(input.len(), output.len())?; + self.process_midi_into(input.len(), midi, |processor, index| { + output[index] = processor.next(input[index], OutputLayout::Stereo); + }) + } + + /// Processes mono PCM into separate left and right slices with packed + /// three-byte MIDI controls. + /// + /// The three slices must have equal frame counts. The decode of MIDI, the + /// offset order, empty blocks and drain cancellation are the same as for + /// [`process_with_midi`](Self::process_with_midi). If the call succeeds, it + /// writes all output samples. This method does not allocate memory. + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] for the left channel, then for + /// the right channel. Next, it checks [`Error::BlockTooLarge`], then + /// [`Error::InvalidEvent`]. If an error occurs, the two output buffers and + /// all processor state do not change. + pub fn process_planar_with_midi( + &mut self, + input: &[i16], + left: &mut [i16], + right: &mut [i16], + midi: &[PackedMidiEvent], + ) -> Result<(), Error> { + Error::check_length(input.len(), left.len())?; + Error::check_length(input.len(), right.len())?; + self.process_midi_into(input.len(), midi, |processor, index| { + let frame = processor.next(input[index], OutputLayout::Stereo); + left[index] = frame[0]; + right[index] = frame[1]; + }) + } + + /// Replaces mono PCM with the stereo downmix and applies packed three-byte + /// MIDI controls. + /// + /// The in-place read order, the downmix and the peak measurements are the + /// same as for [`process_mono_in_place`](Self::process_mono_in_place). The + /// decode of MIDI, the offset rules and drain cancellation are the same as + /// for [`process_with_midi`](Self::process_with_midi). This method does not + /// allocate memory. + /// + /// # Errors + /// + /// Returns [`Error::BlockTooLarge`] for a slice that is too large. Returns + /// [`Error::InvalidEvent`] for the first event with an invalid offset, an + /// unknown bus or invalid MIDI bytes. All checks finish before the audio + /// slice or the processor state changes. + pub fn process_mono_in_place_with_midi( + &mut self, + audio: &mut [i16], + midi: &[PackedMidiEvent], + ) -> Result<(), Error> { + self.process_midi_into(audio.len(), midi, |processor, index| { + let output = processor.next(audio[index], OutputLayout::Mono); + audio[index] = output[0]; + }) + } + + /// Processes planar stereo audio for Wasm `(offset, packedMessage)` word + /// pairs. + #[cfg(all(feature = "wasm", target_arch = "wasm32"))] + pub(crate) fn process_planar_midi_words( + &mut self, + input: &[i16], + left: &mut [i16], + right: &mut [i16], + midi: ValidatedPackedMidi<'_, [u32; 2]>, + ) { + self.process_validated_midi(input.len(), midi, |processor, index| { + let frame = processor.next(input[index], OutputLayout::Stereo); + left[index] = frame[0]; + right[index] = frame[1]; + }); + } + + /// Processes in-place mono audio for Wasm `(offset, packedMessage)` word + /// pairs. + #[cfg(all(feature = "wasm", target_arch = "wasm32"))] + pub(crate) fn process_mono_midi_words( + &mut self, + audio: &mut [i16], + midi: ValidatedPackedMidi<'_, [u32; 2]>, + ) { + self.process_validated_midi(audio.len(), midi, |processor, index| { + let output = processor.next(audio[index], OutputLayout::Mono); + audio[index] = output[0]; + }); + } /// Starts a tail with the current [`tail_frames`](Self::tail_frames) /// budget and returns that budget. /// @@ -1027,6 +1144,37 @@ impl Processor { Ok(()) } + /// Checks the block and packed MIDI controls, applies MIDI events at each + /// offset and renders each frame. + fn process_midi_into( + &mut self, + frames: usize, + midi: &[T], + render: impl FnMut(&mut Self, usize), + ) -> Result<(), Error> { + self.check_block(frames)?; + let midi = ValidatedPackedMidi::new(midi, frames)?; + self.process_validated_midi(frames, midi, render); + Ok(()) + } + + /// Applies validated packed MIDI events at each offset and renders each + /// frame. + fn process_validated_midi( + &mut self, + frames: usize, + mut midi: ValidatedPackedMidi<'_, T>, + mut render: impl FnMut(&mut Self, usize), + ) { + self.drain_remaining = None; + for index in 0..frames { + while let Some(event) = midi.next_at(index) { + self.apply(event); + } + render(self, index); + } + } + /// Renders only the budget that is left. The caller writes zeros in the /// unused frames. /// diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..1ea79f2 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -32,11 +32,16 @@ //! 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 -//! across calls. These operations can allocate: +//! each block. It also keeps event and `u32` MIDI buffers and uses their +//! capacity again across calls. For blocks with only three-byte MIDI messages, +//! `processWithMidi` and `processMonoWithMidi` copy `(offset, packedMessage)` +//! word pairs from a `Uint32Array` in one `copy_to` call. +//! +//! These operations can allocate: //! //! - Event decode when a call gives more events than before, or when an event //! converts a stage configuration. +//! - Packed MIDI copy when a call gives more `u32` words than before. //! - The conversion of configurations. //! - Feedback, control-activity and telemetry objects. //! - The buffers of the formant envelopes. @@ -49,13 +54,13 @@ //! read or write views. If you do not need a processor any more, call `free()` //! and do not touch its views again. -use crate::events::ValidatedEvents; +use crate::events::{ValidatedEvents, ValidatedPackedMidi}; use crate::processor::EnvelopeKey; use crate::{ ControlActivity, ControlEvent, Error, Feedback, MidiEvent, ParameterControl, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Array, Float32Array, Int16Array, Object, Reflect}; +use js_sys::{Array, Float32Array, Int16Array, Object, Reflect, Uint32Array}; use serde::{Deserialize, Serialize}; use tsify::{serde_wasm_bindgen, Ts, Tsify}; use wasm_bindgen::prelude::*; @@ -109,7 +114,7 @@ pub fn default_config() -> Result, JsError> { /// - `Float32Array` buffer calls and in-place `Float32` calls share those /// three `f32` buffers. /// - Check `memory.buffer` before input writes and after calls that pass -/// `events`, because Wasm memory growth detaches old views. +/// `events` or `midi`, because Wasm memory growth detaches old views. /// - Do not read or write the views of an instance after `free()`. /// /// If a call that processes audio fails, it throws a JavaScript `Error` before @@ -147,6 +152,9 @@ pub struct WasmProcessor { /// The reusable buffer for block events. It becomes longer when a call /// gives more events, and it does not become shorter. events: Vec, + /// The reusable buffer for `(offset, packedMessage)` MIDI words. It becomes + /// longer when a call gives more words, and it does not become shorter. + midi_words: Vec, } #[wasm_bindgen(js_class = Tunelet)] @@ -211,6 +219,7 @@ impl WasmProcessor { envelope_output: Vec::new(), envelope_cache: None, events: Vec::new(), + midi_words: Vec::new(), }) } @@ -372,6 +381,88 @@ impl WasmProcessor { Ok(()) } + /// Processes mono input into left and right `Int16Array` buffers with + /// packed binary MIDI controls from a `Uint32Array`. + /// + /// `midi` contains `(offset, packedMessage)` word pairs, so its length must + /// be even. Each `offset` is a zero-based frame index below the block + /// length, and offsets must not decrease. In each `packedMessage`, bits + /// `24..=31` select the bus (`0` for harmony MIDI, `1` for correction + /// MIDI). Bits `16..=23` hold the status byte (`0x80..=0xff`). Bits + /// `8..=15` and bits `0..=7` hold the two data bytes (`0..=127`). + /// + /// The supported messages are Note On, Note On with zero velocity, Note + /// Off and controller 123 (All Notes Off). The processor ignores other + /// three-byte messages with valid byte ranges after the offset checks + /// succeed. + /// + /// The method copies `midi` in one pass into a reusable Rust buffer. Only + /// the first call and a call with more words than before reserve memory. + /// Empty blocks and drain cancellation obey the same rules as `process`. + /// + /// # Errors + /// + /// The method throws if the channel lengths are not equal, the block is + /// larger than `maxBlockFrames` or `midi.length` is odd. It also throws if + /// the buffer reservation fails or a MIDI entry has an invalid offset, an + /// unknown bus or invalid MIDI bytes. If an error occurs, the output + /// buffers and the DSP state do not change. + #[wasm_bindgen(js_name = processWithMidi)] + pub fn process_with_midi( + &mut self, + input: &Int16Array, + left: &Int16Array, + right: &Int16Array, + midi: &Uint32Array, + ) -> Result<(), JsError> { + let frames = input.length() as usize; + Error::check_length(frames, left.length() as usize)?; + Error::check_length(frames, right.length() as usize)?; + self.processor.check_block(frames)?; + let midi = decode_midi_words(&mut self.midi_words, midi, frames)?; + input.copy_to(&mut self.input[..frames]); + self.processor.process_planar_midi_words( + &self.input[..frames], + &mut self.left[..frames], + &mut self.right[..frames], + midi, + ); + left.copy_from(&self.left[..frames]); + right.copy_from(&self.right[..frames]); + Ok(()) + } + + /// Replaces the audio in a mono `Int16Array` with the stereo downmix and + /// applies packed binary MIDI controls from a `Uint32Array`. + /// + /// The `(offset, packedMessage)` word layout, the validation rules, the + /// reusable word buffer and the drain cancellation are the same as for + /// `processWithMidi`. Peak feedback and telemetry measure the mono signal + /// after the downmix, as in `processMono`. + /// + /// # Errors + /// + /// The method throws if the block is larger than `maxBlockFrames` or + /// `midi.length` is odd. It also throws if the buffer reservation fails or + /// a MIDI entry has an invalid offset, an unknown bus or invalid MIDI + /// bytes. It throws before the audio of the caller or the DSP state + /// changes. + #[wasm_bindgen(js_name = processMonoWithMidi)] + pub fn process_mono_with_midi( + &mut self, + audio: &Int16Array, + midi: &Uint32Array, + ) -> Result<(), JsError> { + let frames = audio.length() as usize; + self.processor.check_block(frames)?; + let midi = decode_midi_words(&mut self.midi_words, midi, frames)?; + audio.copy_to(&mut self.input[..frames]); + self.processor + .process_mono_midi_words(&mut self.input[..frames], midi); + audio.copy_from(&self.input[..frames]); + Ok(()) + } + /// Processes mono `Float32Array` input into left and right `Float32Array` /// buffers of equal length. /// @@ -828,6 +919,32 @@ impl WasmProcessor { } } +/// Copies and validates `(offset, packedMessage)` word pairs from `midi` +/// before the audio or the state changes. +/// +/// The function rejects an odd word count before it reserves memory or copies +/// data. +fn decode_midi_words<'a>( + buffer: &'a mut Vec, + midi: &Uint32Array, + frames: usize, +) -> Result, JsError> { + let words = midi.length() as usize; + if !words.is_multiple_of(2) { + return Err(JsError::new("midi length must be even")); + } + if buffer.len() < words { + buffer.try_reserve_exact(words - buffer.len())?; + buffer.resize(words, 0); + } + let slice = &mut buffer[..words]; + if words != 0 { + midi.copy_to(slice); + } + let pairs = slice.as_chunks::<2>().0; + Ok(ValidatedPackedMidi::new(pairs, frames)?) +} + /// One cached `ParameterControl` discriminant and its constructor. struct ParameterKey { name: JsValue,