Skip to main content

alpha2_audio/
graph.rs

1#![allow(clippy::needless_range_loop)]
2
3use crate::{
4    CONTROL_INTERVAL, ChannelLayout, ControlLane, Controls, ProcessCtx, Processor, StateBlob,
5    StateError,
6};
7
8/// Why a [`ProcessorChain`] refuses a processor.
9#[derive(Copy, Clone, Debug, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum ChainError {
12    /// The processor reads a second bus ([`Processor::inputs_per_output`]), which
13    /// [`ProcessorChain::push`] cannot supply.
14    MultipleInputs,
15    /// The processor does not read exactly one second bus for [`ProcessorChain::push_keyed`] to
16    /// supply as its key.
17    NotKeyed,
18}
19
20impl core::fmt::Display for ChainError {
21    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22        formatter.write_str(match self {
23            Self::MultipleInputs => {
24                "a processor that reads a second input per output is pushed with its key"
25            }
26            Self::NotKeyed => "a keyed processor reads two inputs per output",
27        })
28    }
29}
30
31impl std::error::Error for ChainError {}
32
33/// Where and why a [`ProcessorChain`] refused a saved state. The chain is unchanged.
34#[derive(Copy, Clone, Debug, Eq, PartialEq)]
35#[non_exhaustive]
36pub struct ChainStateError {
37    /// The refusing node's index; `None` for the chain's own node count, framing or bypass
38    /// record.
39    pub node: Option<usize>,
40    /// Why.
41    pub error: StateError,
42}
43
44impl ChainStateError {
45    const fn chain(error: StateError) -> Self {
46        Self { node: None, error }
47    }
48}
49
50impl core::fmt::Display for ChainStateError {
51    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
52        match self.node {
53            Some(node) => write!(formatter, "node {node}: {}", self.error),
54            None => write!(formatter, "the chain: {}", self.error),
55        }
56    }
57}
58
59impl std::error::Error for ChainStateError {
60    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
61        Some(&self.error)
62    }
63}
64
65/// Where and why an [`AudioGraph`] refused a saved state. The graph is unchanged.
66#[derive(Copy, Clone, Debug, Eq, PartialEq)]
67#[non_exhaustive]
68pub enum GraphStateError {
69    /// The state was saved by a graph with another number of buses.
70    Topology,
71    /// A bus's clip chain refused its part.
72    ClipChain {
73        /// The bus.
74        bus: usize,
75        /// Where in the chain, and why.
76        error: ChainStateError,
77    },
78    /// A track bus refused its part.
79    TrackBus {
80        /// The bus.
81        bus: usize,
82        /// Where in the chain, and why.
83        error: ChainStateError,
84    },
85    /// The master chain refused its part.
86    Master(ChainStateError),
87    /// A bus's alignment state does not fit because bus latencies differ from the saving graph.
88    Alignment {
89        /// The bus.
90        bus: usize,
91        /// Why.
92        error: StateError,
93    },
94}
95
96impl core::fmt::Display for GraphStateError {
97    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
98        match self {
99            Self::Topology => {
100                formatter.write_str("the saved state was made by a graph with other buses")
101            }
102            Self::ClipChain { bus, error } => write!(formatter, "clip chain {bus}, {error}"),
103            Self::TrackBus { bus, error } => write!(formatter, "track bus {bus}, {error}"),
104            Self::Master(error) => write!(formatter, "master, {error}"),
105            Self::Alignment { bus, error } => write!(formatter, "bus {bus} alignment: {error}"),
106        }
107    }
108}
109
110impl std::error::Error for GraphStateError {}
111
112/// How far a chain has been prepared since its processors last changed.
113#[derive(Copy, Clone, Debug, Eq, PartialEq)]
114enum Prepared {
115    /// Not prepared since the last push; processing passes input through.
116    No,
117    /// By [`ProcessorChain::prepare_nodes`]; only [`ProcessorChain::process_in_place`] runs
118    /// nodes.
119    Nodes,
120    /// By [`ProcessorChain::prepare`].
121    Full,
122}
123
124/// Ordered processor chain with all realtime scratch allocated by `prepare`.
125///
126/// Until prepared (initially and after each `push`), a chain passes its input through.
127///
128/// Each node's context is moved back by the latency of the nodes before it, so sample-addressed
129/// nodes (fades, automation) after a lookahead act on the audio they receive.
130pub struct ProcessorChain {
131    processors: Vec<Box<dyn Processor>>,
132    key_slots: Vec<Option<usize>>,
133    keyed: usize,
134    silence: Vec<f32>,
135    layout: ChannelLayout,
136    scratch_a: [Vec<f32>; 2],
137    scratch_b: [Vec<f32>; 2],
138    bypass: bool,
139    prepared: Prepared,
140    max_block: usize,
141    /// Whether [`Self::dry`] is kept, which starts with the first [`Self::set_bypass`].
142    bypassable: bool,
143    /// The last [`Self::latency_samples`] of input, played while bypassed.
144    dry: DelayLine,
145}
146
147impl ProcessorChain {
148    /// Creates an empty chain for a validated layout.
149    #[must_use]
150    pub fn new(layout: ChannelLayout) -> Self {
151        Self {
152            processors: Vec::new(),
153            key_slots: Vec::new(),
154            keyed: 0,
155            silence: Vec::new(),
156            layout,
157            scratch_a: [Vec::new(), Vec::new()],
158            scratch_b: [Vec::new(), Vec::new()],
159            bypass: false,
160            prepared: Prepared::No,
161            max_block: 0,
162            bypassable: false,
163            dry: DelayLine::default(),
164        }
165    }
166    /// Adds a processor outside the realtime path. The chain passes input through until prepared
167    /// again.
168    ///
169    /// # Errors
170    /// Returns [`ChainError::MultipleInputs`] for a processor that reads more than one input per
171    /// output.
172    pub fn push(&mut self, processor: impl Processor + 'static) -> Result<(), ChainError> {
173        if processor.inputs_per_output() != 1 {
174            return Err(ChainError::MultipleInputs);
175        }
176        self.processors.push(Box::new(processor));
177        self.key_slots.push(None);
178        self.prepared = Prepared::No;
179        Ok(())
180    }
181    /// Adds a processor that reads a key as its second bus, outside the realtime path, and
182    /// returns its key slot: its position among the chain's keyed processors, which
183    /// [`Self::process_keyed`] supplies keys by.
184    ///
185    /// # Errors
186    /// Returns [`ChainError::NotKeyed`] for a processor that does not read two inputs per output.
187    pub fn push_keyed(&mut self, processor: impl Processor + 'static) -> Result<usize, ChainError> {
188        if processor.inputs_per_output() != 2 {
189            return Err(ChainError::NotKeyed);
190        }
191        self.processors.push(Box::new(processor));
192        self.key_slots.push(Some(self.keyed));
193        self.keyed += 1;
194        self.prepared = Prepared::No;
195        Ok(self.keyed - 1)
196    }
197    /// Sets or clears bypass, outside the realtime path.
198    ///
199    /// A bypassed chain plays its input delayed by [`Self::latency_samples`] so hosts stay
200    /// aligned, and keeps running its nodes so ending the bypass resumes on current audio. The
201    /// delayed input record starts with the first call; until it fills, the gap plays silence.
202    /// Chains never bypassed keep no record.
203    pub fn set_bypass(&mut self, bypass: bool) {
204        self.bypass = bypass;
205        if !self.bypassable {
206            self.bypassable = true;
207            if self.prepared != Prepared::No {
208                self.dry
209                    .resize(self.delay_samples(), self.layout.channels());
210            }
211        }
212        // `process_in_place` needs the chain's own scratch while bypassed.
213        if bypass && self.prepared == Prepared::Nodes {
214            self.allocate_scratch(false);
215        }
216    }
217    /// Whether [`Self::process`] would only copy input to output (empty or unprepared), so a host
218    /// may skip it.
219    #[must_use]
220    pub fn passes_through(&self) -> bool {
221        self.processors.is_empty() || self.prepared == Prepared::No
222    }
223    /// Whether the chain has been prepared since its processors last changed.
224    #[must_use]
225    pub fn is_prepared(&self) -> bool {
226        self.prepared != Prepared::No
227    }
228    /// Allocates scratch and prepares every node.
229    pub fn prepare(&mut self, sample_rate: u32, max_block: usize) {
230        for processor in &mut self.processors {
231            processor.prepare(sample_rate, max_block);
232        }
233        // At least one, so any block length can run in pieces.
234        self.max_block = max_block.max(1);
235        self.allocate_silence();
236        self.prepared = Prepared::Full;
237        if self.processors.is_empty() {
238            self.scratch_a.iter_mut().for_each(Vec::clear);
239            self.scratch_b.iter_mut().for_each(Vec::clear);
240            self.dry.resize(0, 0);
241            return;
242        }
243        self.allocate_scratch(true);
244        self.dry
245            .resize(self.delay_samples(), self.layout.channels());
246    }
247    /// Prepares the nodes without allocating chain scratch, for chains run only through
248    /// [`Self::process_in_place`]. [`Self::process`] passes input through until [`Self::prepare`].
249    pub fn prepare_nodes(&mut self, sample_rate: u32, max_block: usize) {
250        for processor in &mut self.processors {
251            processor.prepare(sample_rate, max_block);
252        }
253        self.max_block = max_block.max(1);
254        self.allocate_silence();
255        for channel in self.scratch_a.iter_mut().chain(&mut self.scratch_b) {
256            *channel = Vec::new();
257        }
258        self.prepared = Prepared::Nodes;
259        if self.bypass {
260            self.allocate_scratch(false);
261        }
262        self.dry
263            .resize(self.delay_samples(), self.layout.channels());
264    }
265    fn allocate_silence(&mut self) {
266        self.silence.clear();
267        if self.keyed > 0 {
268            self.silence.resize(self.max_block, 0.0);
269        }
270    }
271    fn allocate_scratch(&mut self, both: bool) {
272        for channel in 0..self.layout.channels() {
273            self.scratch_a[channel].resize(self.max_block, 0.0);
274            if both {
275                self.scratch_b[channel].resize(self.max_block, 0.0);
276            }
277        }
278    }
279    fn delay_samples(&self) -> usize {
280        if self.bypassable {
281            usize::try_from(self.latency_samples()).unwrap_or(usize::MAX)
282        } else {
283            0
284        }
285    }
286    /// Processes the first `frames` samples of each `buffer` channel in place without
287    /// allocating. `spare` holds intermediate node output and may swap allocations with `buffer`;
288    /// both need `frames` samples per layout channel.
289    pub fn process_in_place(
290        &mut self,
291        ctx: &ProcessCtx,
292        buffer: &mut [Vec<f32>; 2],
293        spare: &mut [Vec<f32>; 2],
294        frames: usize,
295    ) {
296        self.process_in_place_controlled(ctx, &Controls::default(), buffer, spare, frames);
297    }
298    /// As [`Self::process_in_place`], retuning the nodes `controls` holds a lane for.
299    pub fn process_in_place_controlled(
300        &mut self,
301        ctx: &ProcessCtx,
302        controls: &Controls<'_>,
303        buffer: &mut [Vec<f32>; 2],
304        spare: &mut [Vec<f32>; 2],
305        frames: usize,
306    ) {
307        let channels = self.layout.channels();
308        if self.processors.is_empty() || self.prepared == Prepared::No {
309            return;
310        }
311        let frames = buffer
312            .iter()
313            .take(channels)
314            .chain(spare.iter().take(channels))
315            .map(Vec::len)
316            .fold(frames, usize::min);
317        if !self.bypass {
318            for channel in 0..channels {
319                self.dry.remember(channel, &buffer[channel][..frames]);
320            }
321            self.dry.advance(frames);
322            let mut upstream = 0_u32;
323            let mut lanes = Lanes::of(controls);
324            for (index, processor) in self.processors.iter_mut().enumerate() {
325                let node_ctx = ctx.offset_by(-i64::from(upstream));
326                let retune = lanes.take(index);
327                if self.key_slots[index].is_some() {
328                    process_keyed_by_silence(
329                        processor.as_mut(),
330                        &node_ctx,
331                        channels,
332                        &self.silence,
333                        retune,
334                        (buffer, 0..frames),
335                        (spare, 0..frames),
336                    );
337                } else {
338                    process_node(
339                        processor.as_mut(),
340                        &node_ctx,
341                        channels,
342                        None,
343                        retune,
344                        (buffer, 0..frames),
345                        (spare, 0..frames),
346                    );
347                }
348                core::mem::swap(buffer, spare);
349                upstream = upstream.saturating_add(processor.latency_samples());
350            }
351            return;
352        }
353        // Bypassed: nodes alternate between `spare` and the chain scratch, in scratch-sized
354        // pieces, and the buffer becomes the delayed input.
355        let piece = self.scratch_a[0].len().max(1);
356        let mut start = 0;
357        while start < frames {
358            let end = (start + piece).min(frames);
359            let count = end - start;
360            let piece_ctx = ctx.offset_by(i64::try_from(start).unwrap_or(i64::MAX));
361            let mut upstream = 0_u32;
362            let mut lanes = Lanes::of(controls);
363            for (index, processor) in self.processors.iter_mut().enumerate() {
364                let node_ctx = piece_ctx.offset_by(-i64::from(upstream));
365                let key = self.key_slots[index].map(|_| silent_key(&self.silence, count));
366                let retune = lanes.take(index);
367                if index == 0 {
368                    process_node(
369                        processor.as_mut(),
370                        &node_ctx,
371                        channels,
372                        key,
373                        retune,
374                        (buffer, start..end),
375                        (spare, start..end),
376                    );
377                } else if index % 2 == 1 {
378                    process_node(
379                        processor.as_mut(),
380                        &node_ctx,
381                        channels,
382                        key,
383                        retune,
384                        (spare, start..end),
385                        (&mut self.scratch_a, 0..count),
386                    );
387                } else {
388                    process_node(
389                        processor.as_mut(),
390                        &node_ctx,
391                        channels,
392                        key,
393                        retune,
394                        (&self.scratch_a, 0..count),
395                        (spare, start..end),
396                    );
397                }
398                upstream = upstream.saturating_add(processor.latency_samples());
399            }
400            for channel in 0..channels {
401                self.dry
402                    .process_in_place(channel, &mut buffer[channel][start..end]);
403            }
404            self.dry.advance(count);
405            start = end;
406        }
407    }
408    /// Sum of serial node latencies; zero while unprepared.
409    #[must_use]
410    pub fn latency_samples(&self) -> u32 {
411        if self.prepared == Prepared::No {
412            return 0;
413        }
414        self.processors.iter().fold(0_u32, |total, processor| {
415            total.saturating_add(processor.latency_samples())
416        })
417    }
418    /// Sum of the latencies of the nodes from `index` to the end; zero while unprepared.
419    #[must_use]
420    pub fn latency_from(&self, index: usize) -> u32 {
421        if self.prepared == Prepared::No {
422            return 0;
423        }
424        self.processors
425            .iter()
426            .skip(index)
427            .fold(0_u32, |total, processor| {
428                total.saturating_add(processor.latency_samples())
429            })
430    }
431    /// How many nodes were added with [`Self::push_keyed`].
432    #[must_use]
433    pub const fn key_slots(&self) -> usize {
434        self.keyed
435    }
436    /// Sum of serial processor settling horizons, excluding their delays.
437    #[must_use]
438    pub fn history_samples(&self) -> u32 {
439        self.processors.iter().fold(0_u32, |total, processor| {
440            total.saturating_add(processor.history_samples())
441        })
442    }
443    /// Clears all histories.
444    pub fn reset(&mut self) {
445        for processor in &mut self.processors {
446            processor.reset();
447        }
448        for channel in &mut self.scratch_a {
449            channel.fill(0.0);
450        }
451        for channel in &mut self.scratch_b {
452            channel.fill(0.0);
453        }
454        self.dry.reset();
455    }
456    /// Processes one block without allocating, covering the shortest input or output channel.
457    /// Blocks longer than `max_block` run in pieces. With missing layout channels the outputs are
458    /// silenced. Keyed nodes read silence as their key.
459    pub fn process(&mut self, ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
460        self.process_keyed(ctx, inputs, &[], outputs);
461    }
462    /// As [`Self::process`], with the key of each keyed node by its key slot, one plane per
463    /// layout channel. A key that is missing or shorter than the block is silence.
464    pub fn process_keyed(
465        &mut self,
466        ctx: &ProcessCtx,
467        inputs: &[&[f32]],
468        keys: &[[&[f32]; 2]],
469        outputs: &mut [&mut [f32]],
470    ) {
471        self.process_controlled(ctx, inputs, keys, &Controls::default(), outputs);
472    }
473    /// As [`Self::process_keyed`], retuning the nodes `controls` holds a lane for. A retuned
474    /// node's key is cut at the same samples as its program.
475    pub fn process_controlled(
476        &mut self,
477        ctx: &ProcessCtx,
478        inputs: &[&[f32]],
479        keys: &[[&[f32]; 2]],
480        controls: &Controls<'_>,
481        outputs: &mut [&mut [f32]],
482    ) {
483        let channels = self.layout.channels();
484        if inputs.len() < channels || outputs.len() < channels {
485            for output in outputs.iter_mut() {
486                output.fill(0.0);
487            }
488            return;
489        }
490        let frames = inputs
491            .iter()
492            .take(channels)
493            .map(|v| v.len())
494            .chain(outputs.iter().take(channels).map(|v| v.len()))
495            .min()
496            .unwrap_or(0);
497        if self.processors.is_empty() || self.prepared != Prepared::Full {
498            for channel in 0..channels {
499                outputs[channel][..frames].copy_from_slice(&inputs[channel][..frames]);
500            }
501            return;
502        }
503        let piece = self.scratch_a[0].len();
504        let mut start = 0;
505        while start < frames {
506            let end = (start + piece).min(frames);
507            let count = end - start;
508            for channel in 0..channels {
509                self.scratch_a[channel][..count].copy_from_slice(&inputs[channel][start..end]);
510            }
511            let piece_ctx = ctx.offset_by(i64::try_from(start).unwrap_or(i64::MAX));
512            let mut upstream = 0_u32;
513            let mut lanes = Lanes::of(controls);
514            for (index, processor) in self.processors.iter_mut().enumerate() {
515                let node_ctx = piece_ctx.offset_by(-i64::from(upstream));
516                let key = self.key_slots[index].map(|slot| {
517                    let silent = silent_key(&self.silence, count);
518                    keys.get(slot).map_or(silent, |planes| {
519                        let piece_of = |plane: usize| {
520                            planes[plane.min(channels - 1)]
521                                .get(start..end)
522                                .unwrap_or(silent[0])
523                        };
524                        [piece_of(0), piece_of(1)]
525                    })
526                });
527                process_node(
528                    processor.as_mut(),
529                    &node_ctx,
530                    channels,
531                    key,
532                    lanes.take(index),
533                    (&self.scratch_a, 0..count),
534                    (&mut self.scratch_b, 0..count),
535                );
536                core::mem::swap(&mut self.scratch_a, &mut self.scratch_b);
537                upstream = upstream.saturating_add(processor.latency_samples());
538            }
539            for channel in 0..channels {
540                if self.bypass {
541                    self.dry.process(
542                        channel,
543                        &inputs[channel][start..end],
544                        &mut outputs[channel][start..end],
545                    );
546                } else {
547                    self.dry.remember(channel, &inputs[channel][start..end]);
548                    outputs[channel][start..end].copy_from_slice(&self.scratch_a[channel][..count]);
549                }
550            }
551            self.dry.advance(count);
552            start = end;
553        }
554    }
555    /// Serializes each processor state with length framing, then the bypass record.
556    #[must_use]
557    pub fn save_state(&self) -> StateBlob {
558        let mut bytes = Vec::new();
559        bytes.extend_from_slice(
560            &(u32::try_from(self.processors.len()).unwrap_or(u32::MAX)).to_le_bytes(),
561        );
562        for state in self
563            .processors
564            .iter()
565            .map(|processor| processor.save_state())
566            .chain(core::iter::once(self.dry.save_state()))
567        {
568            bytes.extend_from_slice(
569                &(u64::try_from(state.as_bytes().len()).unwrap_or(u64::MAX)).to_le_bytes(),
570            );
571            bytes.extend_from_slice(state.as_bytes());
572        }
573        StateBlob::new(bytes)
574    }
575    /// Restores a state saved by a chain of the same nodes and preparation, atomically: if a node
576    /// refuses, earlier nodes are rolled back.
577    ///
578    /// A missing bypass record leaves this chain's empty; a record this chain does not keep is
579    /// dropped.
580    ///
581    /// # Errors
582    /// Returns where and why the state was refused.
583    pub fn load_state(&mut self, state: &StateBlob) -> Result<(), ChainStateError> {
584        let (nodes, record) = Self::split_state(state.as_bytes(), self.processors.len())
585            .ok_or(ChainStateError::chain(StateError::Mismatch))?;
586        let record = self
587            .dry
588            .check_record(&record)
589            .map_err(ChainStateError::chain)?;
590        let snapshot = self
591            .processors
592            .iter()
593            .map(|processor| processor.save_state())
594            .collect::<Vec<_>>();
595        for (index, part) in nodes.iter().enumerate() {
596            if let Err(error) = self.processors[index].load_state(part) {
597                undo(&mut self.processors[..index], &snapshot);
598                return Err(ChainStateError {
599                    node: Some(index),
600                    error,
601                });
602            }
603        }
604        self.dry.load_record(record);
605        Ok(())
606    }
607    /// The [`Processor::save_state`] of the node at `index`, for carrying history across a chain
608    /// rebuild with [`Self::load_node_state`].
609    #[must_use]
610    pub fn node_state(&self, index: usize) -> Option<StateBlob> {
611        self.processors
612            .get(index)
613            .map(|processor| processor.save_state())
614    }
615    /// Restores the node at `index` from [`Self::node_state`], atomically.
616    ///
617    /// # Errors
618    /// Returns [`StateError::Mismatch`] past the last node, or the node's own refusal.
619    pub fn load_node_state(&mut self, index: usize, state: &StateBlob) -> Result<(), StateError> {
620        self.processors
621            .get_mut(index)
622            .ok_or(StateError::Mismatch)?
623            .load_state(state)
624    }
625    /// Splits a chain state into `count` node states and the bypass record.
626    fn split_state(bytes: &[u8], count: usize) -> Option<(Vec<StateBlob>, StateBlob)> {
627        let saved = u32::from_le_bytes(bytes.get(0..4)?.try_into().ok()?);
628        if usize::try_from(saved).ok()? != count {
629            return None;
630        }
631        let mut offset = 4;
632        let mut parts = Vec::with_capacity(count + 1);
633        for _ in 0..=count {
634            let length = usize::try_from(u64::from_le_bytes(
635                bytes.get(offset..offset + 8)?.try_into().ok()?,
636            ))
637            .ok()?;
638            let end = (offset + 8).checked_add(length)?;
639            parts.push(StateBlob::new(bytes.get(offset + 8..end)?.to_vec()));
640            offset = end;
641        }
642        let record = parts.pop()?;
643        (offset == bytes.len()).then_some((parts, record))
644    }
645}
646
647/// Rolls `processors` back to their own `snapshot`; a processor that refuses its own state is
648/// reset.
649fn undo(processors: &mut [Box<dyn Processor>], snapshot: &[StateBlob]) {
650    for (processor, state) in processors.iter_mut().zip(snapshot) {
651        if processor.load_state(state).is_err() {
652            processor.reset();
653        }
654    }
655}
656
657/// Runs `processor` over `range` of `input` into `output` on the first `channels`.
658fn process_processor(
659    processor: &mut dyn Processor,
660    ctx: &ProcessCtx,
661    channels: usize,
662    (input, from): (&[Vec<f32>; 2], core::ops::Range<usize>),
663    (output, to): (&mut [Vec<f32>; 2], core::ops::Range<usize>),
664) {
665    match channels {
666        1 => processor.process(ctx, &[&input[0][from]], &mut [&mut output[0][to]]),
667        2 => {
668            let (left, right) = output.split_at_mut(1);
669            processor.process(
670                ctx,
671                &[&input[0][from.clone()], &input[1][from]],
672                &mut [&mut left[0][to.clone()], &mut right[0][to]],
673            );
674        }
675        _ => {}
676    }
677}
678
679fn silent_key(silence: &[f32], count: usize) -> [&[f32]; 2] {
680    let plane = &silence[..count.min(silence.len())];
681    [plane, plane]
682}
683
684fn process_processor_with_key(
685    processor: &mut dyn Processor,
686    ctx: &ProcessCtx,
687    channels: usize,
688    key: Option<[&[f32]; 2]>,
689    (input, from): (&[Vec<f32>; 2], core::ops::Range<usize>),
690    (output, to): (&mut [Vec<f32>; 2], core::ops::Range<usize>),
691) {
692    let Some(key) = key else {
693        process_processor(processor, ctx, channels, (input, from), (output, to));
694        return;
695    };
696    match channels {
697        1 => processor.process(ctx, &[&input[0][from], key[0]], &mut [&mut output[0][to]]),
698        2 => {
699            let (left, right) = output.split_at_mut(1);
700            processor.process(
701                ctx,
702                &[&input[0][from.clone()], &input[1][from], key[0], key[1]],
703                &mut [&mut left[0][to.clone()], &mut right[0][to]],
704            );
705        }
706        _ => {}
707    }
708}
709
710fn process_keyed_by_silence(
711    processor: &mut dyn Processor,
712    ctx: &ProcessCtx,
713    channels: usize,
714    silence: &[f32],
715    retune: Option<Retune<'_>>,
716    (input, from): (&[Vec<f32>; 2], core::ops::Range<usize>),
717    (output, to): (&mut [Vec<f32>; 2], core::ops::Range<usize>),
718) {
719    let piece = silence.len().max(1);
720    let mut done = 0;
721    while done < from.len() {
722        let count = piece.min(from.len() - done);
723        process_node(
724            processor,
725            &ctx.offset_by(i64::try_from(done).unwrap_or(i64::MAX)),
726            channels,
727            Some(silent_key(silence, count)),
728            retune,
729            (input, from.start + done..from.start + done + count),
730            (output, to.start + done..to.start + done + count),
731        );
732        done += count;
733    }
734}
735
736#[derive(Clone, Copy)]
737struct Retune<'a> {
738    lane: &'a ControlLane,
739    controls: &'a Controls<'a>,
740}
741
742struct Lanes<'a> {
743    controls: &'a Controls<'a>,
744    next: usize,
745}
746
747impl<'a> Lanes<'a> {
748    const fn of(controls: &'a Controls<'a>) -> Self {
749        Self { controls, next: 0 }
750    }
751
752    fn take(&mut self, node: usize) -> Option<Retune<'a>> {
753        let lane = self
754            .controls
755            .lanes
756            .get(self.next)
757            .filter(|lane| lane.node == node)?;
758        self.next += 1;
759        Some(Retune {
760            lane,
761            controls: self.controls,
762        })
763    }
764}
765
766fn process_node(
767    processor: &mut dyn Processor,
768    ctx: &ProcessCtx,
769    channels: usize,
770    key: Option<[&[f32]; 2]>,
771    retune: Option<Retune<'_>>,
772    (input, from): (&[Vec<f32>; 2], core::ops::Range<usize>),
773    (output, to): (&mut [Vec<f32>; 2], core::ops::Range<usize>),
774) {
775    let Some(Retune { lane, controls }) = retune else {
776        process_processor_with_key(processor, ctx, channels, key, (input, from), (output, to));
777        return;
778    };
779    let params = processor.control_params();
780    let count = from.len();
781    let mut done = 0;
782    while done < count {
783        let offset = i64::try_from(done).unwrap_or(i64::MAX);
784        let sample = ctx.sample_position.saturating_add(offset);
785        let next_point = (sample.div_euclid(CONTROL_INTERVAL) + 1).saturating_mul(CONTROL_INTERVAL);
786        let run = usize::try_from(next_point - sample)
787            .unwrap_or(count)
788            .clamp(1, count - done);
789        processor.control(&controls.span_at(lane, sample, params));
790        process_processor_with_key(
791            processor,
792            &ctx.offset_by(offset),
793            channels,
794            key.map(|key| key.map(|plane| plane.get(done..done + run).unwrap_or(&[]))),
795            (input, from.start + done..from.start + done + run),
796            (output, to.start + done..to.start + done + run),
797        );
798        done += run;
799    }
800}
801
802/// A fixed delay of whole samples on up to two channels that share one cursor: process each
803/// channel of a block, then call [`Self::advance`] once.
804#[derive(Clone, Debug, Default)]
805pub struct DelayLine {
806    lines: [Vec<f32>; 2],
807    cursor: usize,
808}
809
810impl DelayLine {
811    /// A silent delay of `samples` on `channels` channels. A delay of zero passes through.
812    #[must_use]
813    pub fn new(samples: usize, channels: usize) -> Self {
814        let mut delay = Self::default();
815        delay.resize(samples, channels);
816        delay
817    }
818    /// The delay in samples.
819    #[must_use]
820    pub fn samples(&self) -> usize {
821        self.lines[0].len()
822    }
823    /// Empties the delay and makes it `samples` long on `channels` channels.
824    fn resize(&mut self, samples: usize, channels: usize) {
825        for (channel, line) in self.lines.iter_mut().enumerate() {
826            line.clear();
827            if channel < channels {
828                line.resize(samples, 0.0);
829            } else {
830                line.shrink_to_fit();
831            }
832        }
833        self.cursor = 0;
834    }
835    /// Clears the held samples.
836    pub fn reset(&mut self) {
837        for line in &mut self.lines {
838            line.fill(0.0);
839        }
840        self.cursor = 0;
841    }
842    /// Writes `input` delayed into `output` for one channel, covering the shorter of the two.
843    pub fn process(&mut self, channel: usize, input: &[f32], output: &mut [f32]) {
844        let line = &mut self.lines[channel];
845        if line.is_empty() {
846            output.copy_from_slice(input);
847            return;
848        }
849        let frames = input.len().min(output.len());
850        let mut cursor = self.cursor;
851        let mut done = 0;
852        while done < frames {
853            let run = (frames - done).min(line.len() - cursor);
854            output[done..done + run].copy_from_slice(&line[cursor..cursor + run]);
855            line[cursor..cursor + run].copy_from_slice(&input[done..done + run]);
856            done += run;
857            cursor = (cursor + run) % line.len();
858        }
859    }
860    /// Replaces one channel's `samples` with themselves delayed.
861    pub fn process_in_place(&mut self, channel: usize, samples: &mut [f32]) {
862        let line = &mut self.lines[channel];
863        if line.is_empty() {
864            return;
865        }
866        let mut cursor = self.cursor;
867        let mut done = 0;
868        while done < samples.len() {
869            let run = (samples.len() - done).min(line.len() - cursor);
870            line[cursor..cursor + run].swap_with_slice(&mut samples[done..done + run]);
871            done += run;
872            cursor = (cursor + run) % line.len();
873        }
874    }
875    /// Records `input` as [`Self::delay`] would, without writing it out.
876    fn remember(&mut self, channel: usize, input: &[f32]) {
877        let line = &mut self.lines[channel];
878        let length = line.len();
879        if length == 0 {
880            return;
881        }
882        let skip = input.len().saturating_sub(length);
883        let mut cursor = (self.cursor + skip % length) % length;
884        for &sample in &input[skip..] {
885            line[cursor] = sample;
886            cursor += 1;
887            if cursor == length {
888                cursor = 0;
889            }
890        }
891    }
892    /// Moves every channel on by `frames` samples, after each was processed over them.
893    pub fn advance(&mut self, frames: usize) {
894        let length = self.lines[0].len();
895        if length != 0 {
896            self.cursor = (self.cursor + frames % length) % length;
897        }
898    }
899    /// The held samples and the cursor.
900    #[must_use]
901    pub fn save_state(&self) -> StateBlob {
902        let mut bytes = Vec::with_capacity(8 + self.lines.iter().map(Vec::len).sum::<usize>() * 4);
903        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
904        for value in self.lines.iter().flatten() {
905            bytes.extend_from_slice(&value.to_le_bytes());
906        }
907        StateBlob::new(bytes)
908    }
909    /// The cursor of a state saved by a delay of the same length and channels. Any sample values
910    /// are accepted.
911    fn check(&self, state: &StateBlob) -> Result<usize, StateError> {
912        let bytes = state.as_bytes();
913        let samples = self.lines.iter().map(Vec::len).sum::<usize>();
914        if bytes.len() != 8 + samples * 4 {
915            return Err(StateError::Mismatch);
916        }
917        let cursor = usize::try_from(u64::from_le_bytes(
918            bytes[..8].try_into().expect("fixed range"),
919        ))
920        .map_err(|_| StateError::Invalid)?;
921        if cursor >= self.lines[0].len().max(1) {
922            return Err(StateError::Invalid);
923        }
924        Ok(cursor)
925    }
926    /// Restores a state saved by a delay of the same length and channels.
927    ///
928    /// # Errors
929    /// Returns [`StateError::Mismatch`] for another length or channel count and
930    /// [`StateError::Invalid`] for a cursor past the end; the delay is unchanged.
931    pub fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
932        let cursor = self.check(state)?;
933        self.load(state, cursor);
934        Ok(())
935    }
936    /// Restores a state [`Self::check`] took, at the cursor it returned.
937    fn load(&mut self, state: &StateBlob, cursor: usize) {
938        let values = state.as_bytes()[8..]
939            .as_chunks::<4>()
940            .0
941            .iter()
942            .map(|word| f32::from_le_bytes(*word));
943        for (target, value) in self.lines.iter_mut().flatten().zip(values) {
944            *target = value;
945        }
946        self.cursor = cursor;
947    }
948    /// How a saved bypass record loads ([`Self::load_record`]): whole when both keep one, emptied
949    /// when only this chain does, skipped when this chain keeps none.
950    fn check_record<'a>(&self, state: &'a StateBlob) -> Result<Record<'a>, StateError> {
951        if self.lines[0].is_empty() {
952            Ok(Record::Ignore)
953        } else if state.as_bytes().len() == 8 {
954            Ok(Record::Empty)
955        } else {
956            Ok(Record::Load(state, self.check(state)?))
957        }
958    }
959    fn load_record(&mut self, record: Record<'_>) {
960        match record {
961            Record::Ignore => {}
962            Record::Empty => self.reset(),
963            Record::Load(state, cursor) => self.load(state, cursor),
964        }
965    }
966}
967
968/// What a chain's bypass record does with a saved one.
969#[derive(Copy, Clone)]
970enum Record<'a> {
971    Ignore,
972    Empty,
973    Load(&'a StateBlob, usize),
974}
975
976/// Clip chain -> track bus -> master bus graph with deterministic latency aggregation.
977///
978/// Each bus is delayed to the longest clip-and-track latency before the mix, so output is input
979/// delayed by exactly [`Self::latency_samples`] regardless of where lookahead sits.
980pub struct AudioGraph {
981    layout: ChannelLayout,
982    clip_chains: Vec<ProcessorChain>,
983    track_buses: Vec<ProcessorChain>,
984    master: ProcessorChain,
985    alignment: Vec<DelayLine>,
986    mix: [Vec<f32>; 2],
987    bus_output: [Vec<f32>; 2],
988    track_output: [Vec<f32>; 2],
989    max_block: usize,
990}
991
992/// Complete graph history captured between offline chunks.
993#[derive(Clone, Debug, Default, Eq, PartialEq)]
994pub struct AudioGraphState {
995    clip_chains: Vec<StateBlob>,
996    track_buses: Vec<StateBlob>,
997    master: StateBlob,
998    alignment: Vec<StateBlob>,
999}
1000
1001impl AudioGraph {
1002    /// Creates one clip chain and one track bus per input bus.
1003    #[must_use]
1004    pub fn new(layout: ChannelLayout, buses: usize) -> Self {
1005        Self {
1006            layout,
1007            clip_chains: (0..buses).map(|_| ProcessorChain::new(layout)).collect(),
1008            track_buses: (0..buses).map(|_| ProcessorChain::new(layout)).collect(),
1009            master: ProcessorChain::new(layout),
1010            alignment: (0..buses).map(|_| DelayLine::default()).collect(),
1011            mix: [Vec::new(), Vec::new()],
1012            bus_output: [Vec::new(), Vec::new()],
1013            track_output: [Vec::new(), Vec::new()],
1014            max_block: 0,
1015        }
1016    }
1017    /// Channel layout every bus and the master run in.
1018    #[must_use]
1019    pub const fn layout(&self) -> ChannelLayout {
1020        self.layout
1021    }
1022    /// Number of input buses, each with its own clip chain and track bus.
1023    #[must_use]
1024    pub fn buses(&self) -> usize {
1025        self.clip_chains.len()
1026    }
1027    /// Mutable clip effect chain of `bus`; `None` past the last bus.
1028    pub fn clip_chain_mut(&mut self, bus: usize) -> Option<&mut ProcessorChain> {
1029        self.clip_chains.get_mut(bus)
1030    }
1031    /// Mutable track effect chain of `bus`; `None` past the last bus.
1032    pub fn track_bus_mut(&mut self, bus: usize) -> Option<&mut ProcessorChain> {
1033        self.track_buses.get_mut(bus)
1034    }
1035    /// Mutable master effect chain.
1036    pub fn master_mut(&mut self) -> &mut ProcessorChain {
1037        &mut self.master
1038    }
1039    /// Prepares every allocation before realtime processing.
1040    pub fn prepare(&mut self, sample_rate: u32, max_block: usize) {
1041        // At least one, so any block length can run in pieces.
1042        self.max_block = max_block.max(1);
1043        for chain in self
1044            .clip_chains
1045            .iter_mut()
1046            .chain(&mut self.track_buses)
1047            .chain(core::iter::once(&mut self.master))
1048        {
1049            chain.prepare(sample_rate, self.max_block);
1050        }
1051        for channel in 0..2 {
1052            self.mix[channel].resize(self.max_block, 0.0);
1053            self.bus_output[channel].resize(self.max_block, 0.0);
1054            self.track_output[channel].resize(self.max_block, 0.0);
1055        }
1056        let longest = self.bus_latency();
1057        for bus in 0..self.alignment.len() {
1058            let pad = longest - self.path_latency(bus);
1059            self.alignment[bus].resize(
1060                usize::try_from(pad).unwrap_or(usize::MAX),
1061                self.layout.channels(),
1062            );
1063        }
1064    }
1065    /// The latency of bus `bus` through its clip chain and track bus.
1066    fn path_latency(&self, bus: usize) -> u32 {
1067        self.clip_chains[bus]
1068            .latency_samples()
1069            .saturating_add(self.track_buses[bus].latency_samples())
1070    }
1071    /// The longest latency of any bus through its clip chain and track bus.
1072    fn bus_latency(&self) -> u32 {
1073        (0..self.clip_chains.len())
1074            .map(|bus| self.path_latency(bus))
1075            .max()
1076            .unwrap_or(0)
1077    }
1078    /// Maximum bus latency plus master latency.
1079    #[must_use]
1080    pub fn latency_samples(&self) -> u32 {
1081        self.bus_latency()
1082            .saturating_add(self.master.latency_samples())
1083    }
1084    /// Mixes flattened planar bus inputs (`bus0-L, bus0-R, bus1-L, ...`) over the shortest output
1085    /// channel. Short buses are padded with silence and long blocks run in pieces. With missing
1086    /// channels or no [`Self::prepare`], the outputs are silenced.
1087    pub fn process(&mut self, ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
1088        let channels = self.layout.channels();
1089        if inputs.len() < self.clip_chains.len() * channels
1090            || outputs.len() < channels
1091            || self.max_block == 0
1092        {
1093            for output in outputs.iter_mut() {
1094                output.fill(0.0);
1095            }
1096            return;
1097        }
1098        let frames = outputs
1099            .iter()
1100            .take(channels)
1101            .map(|v| v.len())
1102            .min()
1103            .unwrap_or(0);
1104        let mut start = 0;
1105        while start < frames {
1106            let end = (start + self.max_block).min(frames);
1107            let ctx = ctx.offset_by(i64::try_from(start).unwrap_or(i64::MAX));
1108            self.process_piece(&ctx, inputs, outputs, start, end);
1109            start = end;
1110        }
1111    }
1112
1113    /// Mixes samples `start..end` of the block, at most `max_block` of them.
1114    fn process_piece(
1115        &mut self,
1116        ctx: &ProcessCtx,
1117        inputs: &[&[f32]],
1118        outputs: &mut [&mut [f32]],
1119        start: usize,
1120        end: usize,
1121    ) {
1122        let channels = self.layout.channels();
1123        let frames = end - start;
1124        for channel in 0..channels {
1125            self.mix[channel][..frames].fill(0.0);
1126        }
1127        for bus in 0..self.clip_chains.len() {
1128            let base = bus * channels;
1129            let piece = |channel: usize| {
1130                let input = inputs[base + channel];
1131                &input[start.min(input.len())..end.min(input.len())]
1132            };
1133            let bus_inputs: [&[f32]; 2] = [piece(0), piece(channels - 1)];
1134            process_chain_to_internal(
1135                &mut self.clip_chains[bus],
1136                ctx,
1137                channels,
1138                frames,
1139                &bus_inputs[..channels],
1140                &mut self.bus_output,
1141            );
1142            let bus_refs: [&[f32]; 2] =
1143                [&self.bus_output[0][..frames], &self.bus_output[1][..frames]];
1144            // The track bus receives audio delayed by the clip chain.
1145            let track_ctx = ctx.offset_by(-i64::from(self.clip_chains[bus].latency_samples()));
1146            process_chain_to_internal(
1147                &mut self.track_buses[bus],
1148                &track_ctx,
1149                channels,
1150                frames,
1151                &bus_refs[..channels],
1152                &mut self.track_output,
1153            );
1154            let alignment = &mut self.alignment[bus];
1155            for channel in 0..channels {
1156                alignment.process_in_place(channel, &mut self.track_output[channel][..frames]);
1157            }
1158            alignment.advance(frames);
1159            for channel in 0..channels {
1160                for frame in 0..frames {
1161                    self.mix[channel][frame] += self.track_output[channel][frame];
1162                }
1163            }
1164        }
1165        let mix_refs: [&[f32]; 2] = [&self.mix[0][..frames], &self.mix[1][..frames]];
1166        // Every bus reaches the master as late as the longest.
1167        let ctx = ctx.offset_by(-i64::from(self.bus_latency()));
1168        let (left, right) = outputs.split_at_mut(1);
1169        match channels {
1170            1 => self
1171                .master
1172                .process(&ctx, &mix_refs[..1], &mut [&mut left[0][start..end]]),
1173            _ => self.master.process(
1174                &ctx,
1175                &mix_refs[..2],
1176                &mut [&mut left[0][start..end], &mut right[0][start..end]],
1177            ),
1178        }
1179    }
1180    /// Clears every graph node.
1181    pub fn reset(&mut self) {
1182        for chain in self
1183            .clip_chains
1184            .iter_mut()
1185            .chain(&mut self.track_buses)
1186            .chain(core::iter::once(&mut self.master))
1187        {
1188            chain.reset();
1189        }
1190        for alignment in &mut self.alignment {
1191            alignment.reset();
1192        }
1193    }
1194
1195    /// Captures every chain's history and the alignment delays.
1196    #[must_use]
1197    pub fn save_state(&self) -> AudioGraphState {
1198        AudioGraphState {
1199            clip_chains: self
1200                .clip_chains
1201                .iter()
1202                .map(ProcessorChain::save_state)
1203                .collect(),
1204            track_buses: self
1205                .track_buses
1206                .iter()
1207                .map(ProcessorChain::save_state)
1208                .collect(),
1209            master: self.master.save_state(),
1210            alignment: self.alignment.iter().map(DelayLine::save_state).collect(),
1211        }
1212    }
1213
1214    /// Restores a state saved by a graph of the same buses, chains and preparation, atomically.
1215    ///
1216    /// # Errors
1217    /// Returns where and why the state was refused.
1218    pub fn load_state(&mut self, state: &AudioGraphState) -> Result<(), GraphStateError> {
1219        let buses = self.clip_chains.len();
1220        if state.clip_chains.len() != buses
1221            || state.track_buses.len() != buses
1222            || state.alignment.len() != buses
1223        {
1224            return Err(GraphStateError::Topology);
1225        }
1226        let mut cursors = Vec::with_capacity(buses);
1227        for (bus, (alignment, saved)) in self.alignment.iter().zip(&state.alignment).enumerate() {
1228            cursors.push(
1229                alignment
1230                    .check(saved)
1231                    .map_err(|error| GraphStateError::Alignment { bus, error })?,
1232            );
1233        }
1234        let snapshot = self
1235            .chains()
1236            .map(ProcessorChain::save_state)
1237            .collect::<Vec<_>>();
1238        let saved = state
1239            .clip_chains
1240            .iter()
1241            .chain(&state.track_buses)
1242            .chain(core::iter::once(&state.master));
1243        let refused =
1244            self.chains_mut()
1245                .zip(saved)
1246                .enumerate()
1247                .find_map(|(index, (chain, saved))| {
1248                    chain.load_state(saved).err().map(|error| (index, error))
1249                });
1250        if let Some((index, error)) = refused {
1251            for (chain, state) in self.chains_mut().zip(&snapshot).take(index) {
1252                if chain.load_state(state).is_err() {
1253                    chain.reset();
1254                }
1255            }
1256            return Err(if index < buses {
1257                GraphStateError::ClipChain { bus: index, error }
1258            } else if index < 2 * buses {
1259                GraphStateError::TrackBus {
1260                    bus: index - buses,
1261                    error,
1262                }
1263            } else {
1264                GraphStateError::Master(error)
1265            });
1266        }
1267        for ((alignment, saved), cursor) in
1268            self.alignment.iter_mut().zip(&state.alignment).zip(cursors)
1269        {
1270            alignment.load(saved, cursor);
1271        }
1272        Ok(())
1273    }
1274
1275    /// Every chain: the clip chains, the track buses, then the master.
1276    fn chains(&self) -> impl Iterator<Item = &ProcessorChain> {
1277        self.clip_chains
1278            .iter()
1279            .chain(&self.track_buses)
1280            .chain(core::iter::once(&self.master))
1281    }
1282
1283    fn chains_mut(&mut self) -> impl Iterator<Item = &mut ProcessorChain> {
1284        self.clip_chains
1285            .iter_mut()
1286            .chain(&mut self.track_buses)
1287            .chain(core::iter::once(&mut self.master))
1288    }
1289}
1290
1291fn process_chain_to_internal(
1292    chain: &mut ProcessorChain,
1293    ctx: &ProcessCtx,
1294    channels: usize,
1295    frames: usize,
1296    inputs: &[&[f32]],
1297    output: &mut [Vec<f32>; 2],
1298) {
1299    // Clear the whole block so a short bus is padded with silence, not the previous bus's tail.
1300    for channel in output.iter_mut().take(channels) {
1301        channel[..frames].fill(0.0);
1302    }
1303    match channels {
1304        1 => chain.process(ctx, inputs, &mut [&mut output[0][..frames]]),
1305        2 => {
1306            let (left, right) = output.split_at_mut(1);
1307            chain.process(
1308                ctx,
1309                inputs,
1310                &mut [&mut left[0][..frames], &mut right[0][..frames]],
1311            );
1312        }
1313        _ => {}
1314    }
1315}