Skip to main content

truce_core/
chunked_process.rs

1//! Sample-accurate parameter-dependent chunking.
2//!
3//! Splits a host audio block into sub-blocks at the
4//! `sample_offset` of every `ParamChange` (for chunkable parameters)
5//! and every `Transport` event, calling `plugin.process()` once per
6//! sub-block. `set_plain` for parameter events is deferred to the
7//! sub-block boundary where the event actually sits, so smoothers
8//! see `set_target` at the right sample instead of at sample 0 of
9//! the whole audio block.
10//!
11//! Every format wrapper routes its `process()` call through
12//! [`process_chunked`]. On formats whose host events all carry
13//! `sample_offset = 0` (VST2, AAX, LV2 in v1, AU until ramp decoding
14//! lands) the loop runs once per block and the splitting machinery
15//! is inert.
16
17use truce_params::{ParamFlags, ParamInfo, Params};
18
19use crate::buffer::AudioBuffer;
20use crate::events::{Event, EventBody, EventList, TransportInfo};
21use crate::plugin::PluginRuntime;
22use crate::process::{ProcessContext, ProcessStatus};
23use crate::sample::Sample;
24
25/// Inputs to [`process_chunked`].
26///
27/// Bundled into a struct because the call has eight load-bearing
28/// references plus a couple of value fields and a positional argument
29/// list at that width is unreadable at the call site (every wrapper
30/// would invent its own helper). Construct one per `process()` call.
31pub struct ChunkedProcess<'a> {
32    /// Sorted, block-rate event stream from the host (param changes,
33    /// transport changes, MIDI). The chunker walks this once forward;
34    /// it does not mutate the list.
35    pub events: &'a EventList,
36    /// Per-instance scratch list pre-allocated to the same capacity
37    /// as `events`. Used to hold the per-sub-block rebased view of
38    /// `events`; `clear()`-ed at the start of every sub-block so the
39    /// backing `Vec` capacity is preserved across blocks. Wrappers
40    /// hold this alongside their input / output event lists.
41    pub sub_event_scratch: &'a mut EventList,
42    /// Initial transport snapshot for the block. Mutated in place
43    /// as the chunker walks past `EventBody::Transport` events; the
44    /// per-sub-block `ProcessContext` reads from this so the plugin
45    /// sees the right tempo / position for the sub-block it's in.
46    pub transport: &'a mut TransportInfo,
47    /// Host sample rate, plumbed through to each per-sub-block
48    /// `ProcessContext`.
49    pub sample_rate: f64,
50    /// Plugin's outbound event queue. The chunker re-bases outbound
51    /// events back to block-relative coordinates before the wrapper
52    /// hands them to the host: the plugin pushes events with
53    /// sub-block-relative offsets, the chunker shifts them by the
54    /// sub-block's start sample.
55    pub output_events: &'a mut EventList,
56    /// Optional read-side params closure plumbed through to each
57    /// per-sub-block `ProcessContext`. Same shape as
58    /// `ProcessContext::with_params`.
59    pub params_fn: Option<&'a dyn Fn(u32) -> f64>,
60    /// Optional meter-write closure plumbed through likewise.
61    pub meters_fn: Option<&'a dyn Fn(u32, f32)>,
62    /// Static param metadata - the chunker keys `is_chunked(id)`
63    /// off `ParamFlags::CHUNKED` here. Wrappers cache this once
64    /// when the plugin instantiates (via
65    /// [`Params::param_infos_static`]) and pass the same slice on
66    /// every block.
67    pub param_infos: &'a [ParamInfo],
68    /// Minimum sub-block size in samples. From
69    /// [`crate::info::AutomationConfig::min_subblock_samples`].
70    /// Events whose `sample_offset` falls within
71    /// `min_subblock_samples` of the current sub-block start are
72    /// coalesced into that sub-block's leading `apply_pending_events`
73    /// batch instead of triggering a split.
74    pub min_subblock_samples: u32,
75}
76
77/// Walk the audio block in sub-block chunks, calling
78/// `plugin.process()` once per chunk with the events that land in
79/// `[block_start, block_end)` rebased to sub-block-relative offsets.
80///
81/// Returns the `ProcessStatus` returned by the *last* sub-block; for
82/// `Tail(N)` the plugin's own clock is the authority, so propagating
83/// the last call's value is the cheapest correct rule.
84///
85/// Allocation-free: the rebased event list lives in
86/// `sub_event_scratch` (capacity preserved across calls) and the
87/// audio buffer sub-views are zero-copy via
88/// [`AudioBuffer::slice`].
89pub fn process_chunked<S, P>(
90    plugin: &mut P,
91    params: &dyn Params,
92    buffer: &mut AudioBuffer<S>,
93    args: ChunkedProcess<'_>,
94) -> ProcessStatus
95where
96    S: Sample,
97    P: PluginRuntime<Sample = S>,
98{
99    let ChunkedProcess {
100        events,
101        sub_event_scratch,
102        transport,
103        sample_rate,
104        output_events,
105        params_fn,
106        meters_fn,
107        param_infos,
108        min_subblock_samples,
109    } = args;
110
111    let total = buffer.num_samples();
112    let mut block_start = 0usize;
113    let mut event_idx = 0usize;
114    let mut last_status = ProcessStatus::Normal;
115    // Floor at 1: a sub-block can't be shorter than one sample, so 0
116    // and 1 both mean "split at every event". Without the floor, an
117    // event sitting exactly on `block_start` (e.g. a Transport at
118    // offset 0, which every wrapper pushes) yields `block_end ==
119    // block_start`, a zero-length sub-block, and a `while block_start
120    // < total` loop that never advances - hanging the audio thread.
121    let min_sub = (min_subblock_samples as usize).max(1);
122
123    while block_start < total {
124        // Find the next split-eligible event at or past
125        // `block_start + min_sub`. Anything before that coalesces
126        // into this sub-block's leading apply batch.
127        let coalesce_until = block_start.saturating_add(min_sub).min(total);
128        let next_split = find_next_split(events, param_infos, event_idx, coalesce_until);
129        let block_end = next_split.map_or(total, |(s, _)| s.min(total));
130
131        // Apply every event with sample_offset < block_end that's
132        // still pending. This is the deferred `set_plain` call that
133        // wrappers used to make eagerly at block start, plus
134        // transport-snapshot updates for `EventBody::Transport`.
135        // Advances `event_idx` past everything consumed.
136        apply_pending_events(events, params, transport, &mut event_idx, block_end);
137
138        // Rebase the in-window events into the scratch list with
139        // sub-block-relative `sample_offset`s. ParamChange entries
140        // get included so plugins that key off them (synths reading
141        // ParamMod, plugins logging) see them at the right time
142        // even though the wrapper has already applied them. Note
143        // events / SysEx get included with rebased offsets.
144        rebase_events_into(events, sub_event_scratch, block_start, block_end);
145
146        let mut sub_buffer = buffer.slice(block_start, block_end - block_start);
147        let sub_output_start = output_events.len();
148
149        let mut ctx = ProcessContext::new(
150            transport,
151            sample_rate,
152            block_end - block_start,
153            output_events,
154        );
155        if let Some(f) = params_fn {
156            ctx = ctx.with_params(f);
157        }
158        if let Some(f) = meters_fn {
159            ctx = ctx.with_meters(f);
160        }
161
162        last_status = plugin.process(&mut sub_buffer, sub_event_scratch, &mut ctx);
163
164        // Re-base any events the plugin pushed during this sub-block
165        // back into block-relative coordinates so the wrapper's
166        // per-event encode loop sees host-block-rate timings.
167        rebase_output_events(output_events, sub_output_start, block_start);
168
169        block_start = block_end;
170    }
171
172    last_status
173}
174
175/// Return the index of the next split-eligible event at sample
176/// `offset >= min_offset`, along with that sample offset.
177///
178/// "Split-eligible" = a `ParamChange` or mono `ParamMod` targeting a
179/// `ParamFlags::CHUNKED` parameter, or any `Transport` event. Note
180/// events (`NoteOn` / `NoteOff` / CC / etc.) don't split; they ride
181/// inside whichever sub-block they fall into via `rebase_events_into`.
182/// Polyphonic mod (`note_id != -1`) doesn't split either - it's a
183/// per-voice offset and subdividing the audio block doesn't help.
184fn find_next_split(
185    events: &EventList,
186    param_infos: &[ParamInfo],
187    from: usize,
188    min_offset: usize,
189) -> Option<(usize, usize)> {
190    for (i, ev) in events.iter().enumerate().skip(from) {
191        let offset = ev.sample_offset as usize;
192        if offset < min_offset {
193            continue;
194        }
195        if is_split_event(&ev.body, param_infos) {
196            return Some((offset, i));
197        }
198    }
199    None
200}
201
202fn is_split_event(body: &EventBody, param_infos: &[ParamInfo]) -> bool {
203    match body {
204        EventBody::ParamChange { id, .. }
205        | EventBody::ParamMod {
206            id, note_id: -1, ..
207        } => is_chunked(*id, param_infos),
208        EventBody::Transport(_) => true,
209        _ => false,
210    }
211}
212
213fn is_chunked(id: u32, param_infos: &[ParamInfo]) -> bool {
214    param_infos
215        .iter()
216        .find(|info| info.id == id)
217        .is_some_and(|info| info.flags.contains(ParamFlags::CHUNKED))
218}
219
220/// Walk `events` from `*event_idx` forward, applying every event with
221/// `sample_offset < block_end` to the param store / transport
222/// snapshot and advancing `*event_idx` past the consumed range.
223///
224/// `ParamChange` writes through to `params.set_plain`; `Transport`
225/// overwrites the per-block snapshot. Note events / `ParamMod` / `SysEx`
226/// are not "applied" - they ride in the rebased sub-event list for
227/// the plugin to process itself; this function just advances past
228/// them so the next split scan starts in the right place.
229fn apply_pending_events(
230    events: &EventList,
231    params: &dyn Params,
232    transport: &mut TransportInfo,
233    event_idx: &mut usize,
234    block_end: usize,
235) {
236    let mut i = *event_idx;
237    for ev in events.iter().skip(i) {
238        if (ev.sample_offset as usize) >= block_end {
239            break;
240        }
241        match ev.body {
242            EventBody::ParamChange { id, value } => {
243                params.set_plain(id, value);
244            }
245            EventBody::Transport(t) => {
246                *transport = t;
247            }
248            // Note events, ParamMod, SysEx: the plugin handles these
249            // via the rebased sub-event list. The apply pass only
250            // advances past them.
251            _ => {}
252        }
253        i += 1;
254    }
255    *event_idx = i;
256}
257
258/// Copy events in `[block_start, block_end)` into `scratch` with
259/// `sample_offset` rebased to sub-block-relative coordinates.
260///
261/// `clear()`s `scratch` first; the backing `Vec` capacity is
262/// preserved across calls so steady-state operation is
263/// allocation-free as long as the wrapper sized the scratch list to
264/// match its input list's capacity.
265///
266/// `SysEx` payloads are copied into the scratch's own byte pool (via
267/// `push_sysex`), so the scratch is self-contained. The plugin only
268/// ever receives the scratch, so `EventList::sysex_bytes` must resolve
269/// against it - copying the body verbatim would leave the rebased entry
270/// pointing at the empty scratch pool and panic on access. The scratch
271/// pool is pre-sized to `SYSEX_POOL_PREALLOC` (it's built with
272/// `EventList::with_capacity`), so the copy stays allocation-free.
273fn rebase_events_into(
274    events: &EventList,
275    scratch: &mut EventList,
276    block_start: usize,
277    block_end: usize,
278) {
279    scratch.clear();
280    for ev in events.iter() {
281        let off = ev.sample_offset as usize;
282        if off < block_start {
283            continue;
284        }
285        if off >= block_end {
286            break;
287        }
288        // Rebase the sample offset. The cast is bounded: `off -
289        // block_start < block_end - block_start <= u32::MAX in
290        // practice` (audio blocks cap at a few thousand samples).
291        #[allow(clippy::cast_possible_truncation)]
292        let rebased_offset = (off - block_start) as u32;
293        match ev.body {
294            // Re-copy the payload so the scratch carries its own pool
295            // entry; a pool-full drop matches the documented `SysEx`
296            // overflow behaviour and can't occur in practice (the
297            // scratch pool matches the source pool's size).
298            EventBody::SysEx { .. } => {
299                let _ = scratch.push_sysex_on_port(
300                    rebased_offset,
301                    ev.port,
302                    events.sysex_bytes(&ev.body),
303                );
304            }
305            body => scratch.push(Event::on_port(rebased_offset, ev.port, body)),
306        }
307    }
308}
309
310/// Shift the `sample_offset` of every output event the plugin
311/// pushed during the just-completed sub-block back into block-relative
312/// coordinates by adding `sub_block_start`.
313///
314/// Output events live in `output_events`; the plugin pushes them
315/// with sub-block-relative offsets (e.g. "MIDI out on sample 10 of
316/// the sub-block"). The wrapper's per-event host-encode loop expects
317/// host-block-rate timings, so shift here once per sub-block.
318fn rebase_output_events(output_events: &mut EventList, from: usize, sub_block_start: usize) {
319    #[allow(clippy::cast_possible_truncation)]
320    let shift = sub_block_start as u32;
321    if shift == 0 {
322        return;
323    }
324    let slice = output_events.events_mut();
325    for ev in slice.iter_mut().skip(from) {
326        ev.sample_offset = ev.sample_offset.saturating_add(shift);
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::events::EVENT_LIST_PREALLOC;
334    use truce_params::{ParamFlags, ParamInfo, ParamRange, ParamUnit, ParamValueKind};
335
336    fn info(id: u32, chunked: bool) -> ParamInfo {
337        let flags = if chunked {
338            ParamFlags::AUTOMATABLE | ParamFlags::CHUNKED
339        } else {
340            ParamFlags::AUTOMATABLE
341        };
342        ParamInfo {
343            id,
344            name: "p",
345            short_name: "p",
346            group: "",
347            range: ParamRange::Linear { min: 0.0, max: 1.0 },
348            default_plain: 0.0,
349            flags,
350            unit: ParamUnit::None,
351            kind: ParamValueKind::Float,
352            midi_map: None,
353            midi_channel: None,
354        }
355    }
356
357    #[test]
358    fn split_only_on_chunked_params() {
359        let infos = [info(0, true), info(1, false)];
360        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
361        events.push(Event::new(
362            100,
363            EventBody::ParamChange { id: 1, value: 0.5 },
364        ));
365        events.push(Event::new(
366            200,
367            EventBody::ParamChange { id: 0, value: 0.5 },
368        ));
369        // Non-chunked param at 100 doesn't split; chunked at 200 does.
370        let next = find_next_split(&events, &infos, 0, 0);
371        assert_eq!(next, Some((200, 1)));
372    }
373
374    #[test]
375    fn min_offset_skips_close_events() {
376        let infos = [info(0, true)];
377        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
378        events.push(Event::new(5, EventBody::ParamChange { id: 0, value: 0.5 }));
379        events.push(Event::new(50, EventBody::ParamChange { id: 0, value: 0.6 }));
380        // min_offset = 32: first event (offset 5) coalesces, second (50) splits.
381        let next = find_next_split(&events, &infos, 0, 32);
382        assert_eq!(next, Some((50, 1)));
383    }
384
385    #[test]
386    fn poly_mod_never_splits() {
387        let infos = [info(0, true)];
388        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
389        events.push(Event::new(
390            100,
391            EventBody::ParamMod {
392                id: 0,
393                note_id: 7,
394                value: 0.1,
395            },
396        ));
397        let next = find_next_split(&events, &infos, 0, 0);
398        assert_eq!(next, None);
399    }
400
401    #[test]
402    fn rebase_drops_out_of_window() {
403        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
404        events.push(Event::new(10, EventBody::ParamChange { id: 0, value: 0.1 }));
405        events.push(Event::new(50, EventBody::ParamChange { id: 0, value: 0.2 }));
406        events.push(Event::new(90, EventBody::ParamChange { id: 0, value: 0.3 }));
407        let mut scratch = EventList::with_capacity(EVENT_LIST_PREALLOC);
408        rebase_events_into(&events, &mut scratch, 40, 80);
409        let collected: Vec<u32> = scratch.iter().map(|e| e.sample_offset).collect();
410        // Only the offset-50 event is in [40, 80); rebased to 10.
411        assert_eq!(collected, vec![10]);
412    }
413
414    #[test]
415    fn rebase_preserves_midi_port() {
416        // The chunker splits the input list into sub-blocks; a
417        // multi-port plugin's per-event port must survive that copy.
418        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
419        events.push(Event::on_port(
420            20,
421            3,
422            EventBody::NoteOn {
423                group: 0,
424                channel: 0,
425                note: 60,
426                velocity: 100,
427            },
428        ));
429        let mut scratch = EventList::with_capacity(EVENT_LIST_PREALLOC);
430        rebase_events_into(&events, &mut scratch, 0, 64);
431        assert_eq!(scratch.iter().map(|e| e.port).collect::<Vec<_>>(), vec![3]);
432    }
433
434    #[test]
435    fn transport_always_splits() {
436        let infos: [ParamInfo; 0] = [];
437        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
438        events.push(Event::new(
439            100,
440            EventBody::Transport(TransportInfo::default()),
441        ));
442        let next = find_next_split(&events, &infos, 0, 0);
443        assert_eq!(next, Some((100, 0)));
444    }
445
446    #[test]
447    fn offset_zero_split_needs_min_offset_at_least_one() {
448        // The `min_subblock_samples.max(1)` clamp in `process_chunked`
449        // rests on this: with `min_offset == 0`, an event sitting
450        // exactly on `block_start` (offset 0 - a Transport every
451        // wrapper pushes) is returned as a split point, so `block_end
452        // == block_start` yields a zero-length sub-block and the loop
453        // never advances (hang). With `min_offset >= 1` that event
454        // coalesces, so `block_end` moves forward and the loop
455        // terminates.
456        let infos: [ParamInfo; 0] = [];
457        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
458        events.push(Event::new(
459            0,
460            EventBody::Transport(TransportInfo::default()),
461        ));
462        // Unclamped (0): the offset-0 event splits at 0 - the hang.
463        assert_eq!(find_next_split(&events, &infos, 0, 0), Some((0, 0)));
464        // Clamped (>= 1): coalesced, no split at the block start.
465        assert_eq!(find_next_split(&events, &infos, 0, 1), None);
466    }
467
468    #[test]
469    fn rebase_copies_sysex_payload_into_scratch() {
470        let mut events = EventList::with_capacity(EVENT_LIST_PREALLOC);
471        events.push_sysex(50, &[0x11, 0x22, 0x33, 0x44]).unwrap();
472        let mut scratch = EventList::with_capacity(EVENT_LIST_PREALLOC);
473        rebase_events_into(&events, &mut scratch, 40, 80);
474
475        let ev = scratch.iter().next().expect("sysex rebased into scratch");
476        assert_eq!(ev.sample_offset, 10); // 50 - 40
477        // Regression: the scratch used to carry the parent's pool
478        // indices against an empty pool, so this access panicked
479        // out-of-bounds. It now resolves against the scratch's own pool.
480        assert_eq!(scratch.sysex_bytes(&ev.body), &[0x11, 0x22, 0x33, 0x44]);
481    }
482}