From 77048662e27f88fb8eaa4fb4e8b3647ea5161768 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:52:54 +0000 Subject: [PATCH 1/2] feat(wasm): add packed binary MIDI methods and buffers - Add EventProblem::MidiBus for unknown packed MIDI bus values - Add and export PackedMidiEvent for three-byte MIDI messages - Add zero-allocation packed MIDI methods on Processor - Reuse TimedEvent and u32 MIDI buffers in WasmProcessor - Add processWithMidi and processMonoWithMidi for Uint32Array - Check packed MIDI methods and types in scripts/verify-pack.mjs - Document the packed MIDI format and buffer reuse in README.md --- README.md | 66 ++++++++++-- scripts/verify-pack.mjs | 7 ++ src/error.rs | 6 ++ src/events.rs | 143 ++++++++++++++++++++++++ src/lib.rs | 18 ++-- src/processor.rs | 174 ++++++++++++++++++++++++++++-- src/wasm.rs | 233 +++++++++++++++++++++++++++++++++++----- 7 files changed, 595 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 83a8f47..d3d7f93 100644 --- a/README.md +++ b/README.md @@ -216,11 +216,11 @@ processor. Select the process function for your output layout: -| Output layout | Function for input | Function for the tail | -| ------------------------------ | ----------------------- | --------------------- | -| `[[i16; 2]]` stereo frames | `process` | `drain` | -| Separate left and right slices | `process_planar` | `drain_planar` | -| Mono slice | `process_mono_in_place` | `drain_mono` | +| Output layout | Function for input | Function for packed MIDI | Function for the tail | +| ------------------------------ | ----------------------- | --------------------------------- | --------------------- | +| `[[i16; 2]]` stereo frames | `process` | `process_with_midi` | `drain` | +| Separate left and right slices | `process_planar` | `process_planar_with_midi` | `drain_planar` | +| Mono slice | `process_mono_in_place` | `process_mono_in_place_with_midi` | `drain_mono` | These rules apply to each call: @@ -261,6 +261,14 @@ let events = [TimedEvent { 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. + ## Lifecycle ![The processor lifecycle: construction, process calls, drain and reset](docs/images/lifecycle.svg) @@ -417,7 +425,9 @@ page that opens the JavaScript. | --------------------------------- | -------------------------------------------------------- | | Shared initialization | `loadTunelet(source?)` | | Mono PCM to planar stereo | `process(input, left, right, events?)` | +| Planar stereo with packed MIDI | `processWithMidi(input, left, right, midi)` | | In-place mono downmix | `processMono(audio, events?)` | +| Mono downmix with packed MIDI | `processMonoWithMidi(audio, midi)` | | Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | | Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | | Feedback | `feedback()`, `takeFeedback()` | @@ -480,6 +490,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); +``` + +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. State and output then do not change. + ### Feedback, telemetry and formant envelopes `telemetry()` and `takeTelemetry()` return a `Telemetry` object. @@ -502,16 +541,21 @@ call with more points than before reserve memory. ### Memory allocation -The constructor allocates reusable PCM buffers. A successful call that -processes audio without events does not allocate new Rust PCM storage. -However, the call copies the audio across the boundary between JavaScript and -Wasm. These items can allocate: +The constructor allocates reusable PCM buffers. `Tunelet` also keeps reusable +vectors for decoded `TimedEvent` controls, packed `u32` MIDI words and formant +envelope points. Each vector reserves exact capacity on its first use or when a +call needs more entries than before, and keeps that capacity across calls. + +`processWithMidi` and `processMonoWithMidi` copy the `Uint32Array` in one +`copy_to` call and create no JavaScript event objects. After the `u32` buffer +reserves enough capacity, packed MIDI calls do not allocate new Rust vector +storage. These items can allocate: - Object conversion. -- Supplied events. +- Supplied `TimedEvent[]` arrays and initial growth of reusable buffers. - Errors. - Feedback and telemetry. -- The formant envelopes. +- The formant envelopes on first growth. The generated glue can also make temporary views. This binding is for general use, and it does not guarantee hard real-time behavior for allocation or diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..6bbeae2 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -174,7 +174,10 @@ 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);", + " processor.processWithMidi(input, left, right, midi);", + " processor.processMonoWithMidi(input, midi);", "} finally {", " processor.free();", "}", @@ -218,7 +221,11 @@ 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.process(input, left, right);", + " processor.processWithMidi(input, left, right, midi);", + " processor.processMono(input);", + " processor.processMonoWithMidi(input, midi);", " processor.free();", " void rootInitSync;", " void wasmInitSync;", 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 e1c975c..689b803 100644 --- a/src/events.rs +++ b/src/events.rs @@ -115,6 +115,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. diff --git a/src/lib.rs b/src/lib.rs index f17bc85..5a3a7b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,8 +43,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 //! @@ -92,9 +96,11 @@ //! //! To export JavaScript bindings and generated TypeScript definitions, enable //! the optional `wasm` feature for `wasm32-unknown-unknown`. The binding owns -//! PCM buffers that it uses again. Configuration conversion, event conversion, -//! feedback objects and errors cause more allocation at the JavaScript -//! boundary. +//! PCM, event and packed MIDI buffers that it uses again. Configuration +//! conversion, `TimedEvent` conversion, 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. @@ -127,7 +133,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, TimedEvent}; +pub use events::{ControlEvent, PackedMidiEvent, 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 83bccf6..41796b6 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -4,11 +4,11 @@ use crate::effects::alien::{self, Alien}; use crate::effects::punch::{Punch, PunchConfig}; 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::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ControlEvent, Error, PackedMidiEvent, PrepareConfig, ProcessorConfig, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -208,6 +208,124 @@ 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]); + }) + } + + /// 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]); + 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 measurement 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]); + audio[index] = downmix(output); + }) + } + + /// 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_words: &[[u32; 2]], + ) -> Result<(), Error> { + self.process_midi_into(input.len(), midi_words, |processor, index| { + let frame = processor.next(input[index]); + 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_words: &[[u32; 2]], + ) -> Result<(), Error> { + self.process_midi_into(audio.len(), midi_words, |processor, index| { + let output = processor.next(audio[index]); + audio[index] = downmix(output); + }) + } + /// Starts a tail with the current [`tail_frames`](Self::tail_frames) /// budget and returns that budget. /// @@ -578,15 +696,33 @@ impl Processor { /// configuration. MIDI and reset events act directly. A reset does not /// discard later events in the block. fn apply(&mut self, event: ValidatedEvent) { - let mut config = self.config; + let mut config; match event.into_inner() { ControlEvent::Configure(value) => config = value, - ControlEvent::Resynthesis(value) => config.resynthesis = value, - ControlEvent::Punch(value) => config.punch = value, - ControlEvent::Warm(value) => config.warm = value, - ControlEvent::Alien(value) => config.alien = value, - ControlEvent::Reverb(value) => config.reverb = value, - ControlEvent::OutputGain(value) => config.output_gain = value, + ControlEvent::Resynthesis(value) => { + config = self.config; + config.resynthesis = value; + } + ControlEvent::Punch(value) => { + config = self.config; + config.punch = value; + } + ControlEvent::Warm(value) => { + config = self.config; + config.warm = value; + } + ControlEvent::Alien(value) => { + config = self.config; + config.alien = value; + } + ControlEvent::Reverb(value) => { + config = self.config; + config.reverb = value; + } + ControlEvent::OutputGain(value) => { + config = self.config; + config.output_gain = value; + } ControlEvent::Midi(event) => { self.resynthesis.apply_midi(event); return; @@ -658,6 +794,26 @@ 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], + mut render: impl FnMut(&mut Self, usize), + ) -> Result<(), Error> { + self.check_block(frames)?; + let mut midi = ValidatedPackedMidi::new(midi, frames)?; + self.drain_remaining = None; + for index in 0..frames { + while let Some(event) = midi.next_at(index) { + self.apply(event); + } + render(self, index); + } + Ok(()) + } + /// 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 15262e2..149d21f 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -28,12 +28,19 @@ //! that validation uses. //! //! The class allocates the PCM storage at construction and uses it again for -//! each block. These operations can allocate: +//! each block. It also keeps reusable buffers for decoded `TimedEvent` values, +//! packed `u32` MIDI words and formant envelope points. For blocks with only +//! three-byte MIDI messages, `processWithMidi` and `processMonoWithMidi` copy +//! `(offset, packedMessage)` word pairs from a `Uint32Array` in one `copy_to` +//! call. After a reusable buffer reserves enough capacity, later calls with the +//! same or fewer entries do not allocate new Rust vector storage. //! -//! - The decode of events. +//! These operations can allocate: +//! +//! - The decode of `TimedEvent[]` objects. +//! - Initial growth of the event, MIDI word and formant envelope buffers. //! - The conversion of configurations. //! - Feedback and telemetry objects. -//! - The buffers of the formant envelopes. //! - Errors. //! //! The JavaScript glue can also make temporary views when it copies data. This @@ -44,7 +51,8 @@ use crate::{ Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Float32Array, Int16Array}; +use js_sys::{Float32Array, Int16Array, Uint32Array}; +use serde::de::{DeserializeSeed, Error as _, SeqAccess, Visitor}; use serde::{Deserialize, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; @@ -113,6 +121,14 @@ pub struct WasmProcessor { /// when a call needs more points, and they do not become shorter. envelope_input: Vec, envelope_output: Vec, + /// The reusable buffer for decoded `TimedEvent` controls. It grows when a + /// call has more events than before, and it keeps its capacity across + /// calls. + events: Vec, + /// The reusable buffer for `(offset, packedMessage)` MIDI words. It grows + /// when a call has more words than before, and it keeps its capacity + /// across calls. + midi_words: Vec, } #[wasm_bindgen(js_class = Tunelet)] @@ -172,6 +188,8 @@ impl WasmProcessor { right: pcm_buffer(max_block_frames)?, envelope_input: Vec::new(), envelope_output: Vec::new(), + events: Vec::new(), + midi_words: Vec::new(), }) } @@ -236,15 +254,16 @@ impl WasmProcessor { /// events apply before their frame, and their offsets obey the rules of /// `TimedEvent[]`. An empty block must have no events. A successful call /// cancels a drain, also for an empty block. The call uses the existing - /// JavaScript and Rust PCM buffers again. + /// JavaScript and Rust PCM buffers again, and keeps the capacity of the + /// decoded event vector across calls. /// /// # Errors /// /// The method throws if the channel lengths are not equal. It also throws - /// if the block is larger than `maxBlockFrames` or an event is not valid. - /// The call checks the lengths and the block size before it decodes and - /// validates the events. If an error occurs, the output buffers and the DSP - /// state do not change. + /// if the block is larger than `maxBlockFrames`, an event is not valid or + /// the reservation of the event buffer fails. The call checks the lengths + /// and the block size before it decodes and validates the events. If an + /// error occurs, the output buffers and the DSP state do not change. pub fn process( &mut self, input: &Int16Array, @@ -256,13 +275,13 @@ impl WasmProcessor { Error::check_length(frames, left.length() as usize)?; Error::check_length(frames, right.length() as usize)?; self.processor.check_block(frames)?; - let events = decode_events(events)?; + decode_events_into(&mut self.events, events)?; input.copy_to(&mut self.input[..frames]); self.processor.process_planar( &self.input[..frames], &mut self.left[..frames], &mut self.right[..frames], - &events.0, + &self.events, )?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); @@ -271,14 +290,16 @@ impl WasmProcessor { /// Replaces the audio in a mono `Int16Array` with the stereo downmix. /// - /// The timing, the events and the drain cancellation are the same as for - /// `process`. Peak feedback measures the stereo output before the downmix, - /// as in the native processor. + /// The frame offsets, the events, the reuse of the event buffer and the + /// drain cancellation are the same as for `process`. Peak feedback + /// measures the stereo output before the downmix, as in the native + /// processor. /// /// # Errors /// - /// The method throws if the block is too large or an event is not valid. - /// It throws before the audio of the caller or the DSP state changes. + /// The method throws if the block is too large, an event is not valid or + /// the reservation of the event buffer fails. It throws before the audio + /// of the caller or the DSP state changes. #[wasm_bindgen(js_name = processMono)] pub fn process_mono( &mut self, @@ -287,10 +308,93 @@ impl WasmProcessor { ) -> Result<(), JsError> { let frames = audio.length() as usize; self.processor.check_block(frames)?; - let events = decode_events(events)?; + decode_events_into(&mut self.events, events)?; audio.copy_to(&mut self.input[..frames]); self.processor - .process_mono_in_place(&mut self.input[..frames], &events.0)?; + .process_mono_in_place(&mut self.input[..frames], &self.events)?; + audio.copy_from(&self.input[..frames]); + 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 in `0..frames`, and + /// offsets must not be less than the offset before them. 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`). + /// + /// 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 `copy_to` call 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 pairs = copy_midi_words(&mut self.midi_words, midi)?; + input.copy_to(&mut self.input[..frames]); + self.processor.process_planar_midi_words( + &self.input[..frames], + &mut self.left[..frames], + &mut self.right[..frames], + pairs, + )?; + 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 measures the stereo output before 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 pairs = copy_midi_words(&mut self.midi_words, midi)?; + audio.copy_to(&mut self.input[..frames]); + self.processor + .process_mono_midi_words(&mut self.input[..frames], pairs)?; audio.copy_from(&self.input[..frames]); Ok(()) } @@ -477,15 +581,92 @@ impl WasmProcessor { } } -/// Decodes the optional block controls before the audio state changes. +/// Decodes the optional block controls into a reusable `TimedEvent` buffer +/// before the audio state changes. /// -/// If there is no value, the result is an empty `Vec`, and no allocation -/// occurs. If the caller gives an array, the decode can allocate storage. -fn decode_events(events: Option>) -> Result { - Ok(match events { - Some(value) => value.to_rust()?, - None => BlockEvents::default(), - }) +/// If there is no value, the buffer becomes empty without allocation and keeps +/// its capacity. If the caller gives an array with more events than the +/// current capacity, the buffer reserves the exact capacity that it needs. +fn decode_events_into( + buffer: &mut Vec, + events: Option>, +) -> Result<(), JsError> { + buffer.clear(); + if let Some(value) = events { + let deserializer = tsify::serde_wasm_bindgen::Deserializer::from(value.js_value()); + EventBufferSeed(buffer) + .deserialize(deserializer) + .map_err(|error| { + JsError::new(&format!( + "Failed to deserialize JsValue into type `{}`: {error}", + std::any::type_name::() + )) + })?; + } + Ok(()) +} + +/// Deserializes a sequence of `TimedEvent` entries into a reusable `Vec`. +struct EventBufferSeed<'a>(&'a mut Vec); + +impl<'de> DeserializeSeed<'de> for EventBufferSeed<'_> { + type Value = (); + + fn deserialize(self, deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + struct EventBufferVisitor<'a>(&'a mut Vec); + + impl<'de> Visitor<'de> for EventBufferVisitor<'_> { + type Value = (); + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a sequence") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + if let Some(count) = seq.size_hint() { + self.0.try_reserve_exact(count).map_err(A::Error::custom)?; + } + while let Some(event) = seq.next_element()? { + if self.0.len() == self.0.capacity() { + self.0.try_reserve_exact(1).map_err(A::Error::custom)?; + } + self.0.push(event); + } + Ok(()) + } + } + + deserializer.deserialize_seq(EventBufferVisitor(self.0)) + } +} + +/// Copies `(offset, packedMessage)` word pairs from `midi` into a reusable +/// `u32` buffer. +/// +/// Rejects an odd word count before it reserves memory or copies data. +fn copy_midi_words<'a>( + buffer: &'a mut Vec, + midi: &Uint32Array, +) -> Result<&'a [[u32; 2]], 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); + } + Ok(slice.as_chunks::<2>().0) } /// Returns the first `points` entries of a reusable envelope buffer. If the From 2ba285c13ce0006b57ac69af900662f8c671820b Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:32:36 +0000 Subject: [PATCH 2/2] docs: align packed MIDI comments with STE and ValidatedEvent - Name ValidatedPackedMidi in the ValidatedEvent rustdoc - Keep the articles in the packed MIDI comments in src/wasm.rs - Keep the articles in the packed MIDI section of README.md --- README.md | 4 ++-- src/events.rs | 2 +- src/wasm.rs | 7 ++++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8b68623..48c6157 100644 --- a/README.md +++ b/README.md @@ -515,11 +515,11 @@ midi[1] = (0 << 24) | (0x90 << 16) | (60 << 8) | 100; processor.processWithMidi(input, left, right, midi); ``` -Supported messages are Note On, Note On with zero velocity, Note Off and +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. State and output then do not change. +the call rejects the full block. The state and the output then do not change. ### Feedback, telemetry and formant envelopes diff --git a/src/events.rs b/src/events.rs index 689b803..0af5ef3 100644 --- a/src/events.rs +++ b/src/events.rs @@ -266,7 +266,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/wasm.rs b/src/wasm.rs index edde56f..5c7905e 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -328,8 +328,8 @@ impl WasmProcessor { /// 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`). /// - /// Supported messages are Note On, Note On with zero velocity, Note Off - /// and controller 123 (All Notes Off). The processor ignores other + /// 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. /// @@ -586,7 +586,8 @@ impl WasmProcessor { /// Copies and validates `(offset, packedMessage)` word pairs from `midi` /// before the audio or the state changes. /// -/// Rejects an odd word count before it reserves memory or copies data. +/// 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,