Skip to main content

plughost_core/
audio.rs

1//! Portable audio bus configuration and explicit, serial chain routing.
2
3use crate::{InputError, Layout, ProcessMode, SampleFormat, Support};
4
5/// Bus enumeration and configuration are bounded before allocation or native iteration.
6pub const MAX_AUDIO_BUSES: usize = 64;
7/// Maximum active channel count in one direction, including all buses.
8pub const MAX_AUDIO_CHANNELS: usize = 512;
9/// Maximum sample storage in one prepared chain's external-input alignment delays and host
10/// bypass delays (256 MiB). Preparation or staged state replacement fails before committing if
11/// the external-input delays, with the host bypass delays of the slots whose host bypass is on,
12/// exceed the budget; a slot whose host bypass is off gets its delay only while it fits, and
13/// cannot turn host bypass on without it. During replacement both the old bank and its prepared
14/// replacement may coexist.
15pub const MAX_ALIGNMENT_BYTES: usize = 256 * 1024 * 1024;
16
17/// Direction of an audio or event port relative to its plugin.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19#[non_exhaustive]
20pub enum AudioDirection {
21    /// Data delivered to the plugin.
22    Input,
23    /// Data produced by the plugin.
24    Output,
25}
26
27/// Native distinction between a main bus and an additional bus.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum AudioBusRole {
31    /// Primary audio signal.
32    Main,
33    /// Additional signal, such as a sidechain or instrument output.
34    Auxiliary,
35}
36
37/// A native bus snapshot. An unknown layout is not inferred from its channel count.
38/// IDs are scoped to a direction and the selected native configuration.
39#[derive(Clone, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct AudioBusInfo {
42    /// Native bus ID, scoped to its direction; not a position in the returned list.
43    pub id: u64,
44    /// Native bus index within its direction.
45    pub index: u32,
46    /// Native display name.
47    pub name: String,
48    /// Whether this bus receives or produces audio.
49    pub direction: AudioDirection,
50    /// Native main or auxiliary designation.
51    pub role: AudioBusRole,
52    /// Recognized portable layout, or `None` when the native arrangement is unknown.
53    pub layout: Option<Layout>,
54    /// Native channel count, including when the layout is unknown.
55    pub channels: u32,
56    /// Current activation state, or `None` if the format cannot report it.
57    pub active: Option<bool>,
58    /// Whether this bus supports single-precision processing.
59    pub f32: Support,
60    /// Whether this bus supports double-precision processing.
61    pub f64: Support,
62}
63
64impl AudioBusInfo {
65    /// A bus with an unknown layout, activation and precision support.
66    #[must_use]
67    pub fn new(
68        id: u64,
69        index: u32,
70        name: impl Into<String>,
71        direction: AudioDirection,
72        role: AudioBusRole,
73        channels: u32,
74    ) -> AudioBusInfo {
75        AudioBusInfo {
76            id,
77            index,
78            name: name.into(),
79            direction,
80            role,
81            layout: None,
82            channels,
83            active: None,
84            f32: Support::Unknown,
85            f64: Support::Unknown,
86        }
87    }
88}
89
90/// A named native bus configuration, such as a CLAP audio-port configuration.
91#[derive(Clone, Debug, PartialEq, Eq)]
92#[non_exhaustive]
93pub struct AudioConfiguration {
94    /// Native configuration ID; not a position in the returned list.
95    pub id: u64,
96    /// Native display name.
97    pub name: String,
98    /// Input buses belonging to this configuration.
99    pub inputs: Vec<AudioBusInfo>,
100    /// Output buses belonging to this configuration.
101    pub outputs: Vec<AudioBusInfo>,
102}
103
104impl AudioConfiguration {
105    /// Each field as given. Internal to the plughost crates; exempt from semver.
106    #[doc(hidden)]
107    #[must_use]
108    pub fn new(
109        id: u64,
110        name: String,
111        inputs: Vec<AudioBusInfo>,
112        outputs: Vec<AudioBusInfo>,
113    ) -> AudioConfiguration {
114        AudioConfiguration {
115            id,
116            name,
117            inputs,
118            outputs,
119        }
120    }
121}
122
123/// Requested layout and activation for one native audio bus.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125#[non_exhaustive]
126pub struct AudioBusConfig {
127    /// Native bus ID, scoped to its direction; not a position in the returned list.
128    pub id: u64,
129    /// Requested channel layout; an active bus cannot use `Layout::None`.
130    pub layout: Layout,
131    /// Whether to activate this bus for processing.
132    pub active: bool,
133}
134
135impl AudioBusConfig {
136    /// A request for native bus `id` with `layout`, active or not.
137    #[must_use]
138    pub const fn new(id: u64, layout: Layout, active: bool) -> AudioBusConfig {
139        AudioBusConfig { id, layout, active }
140    }
141}
142
143/// Requested native buses. Buses omitted from a direction are inactive. Native layout/precision
144/// negotiation follows validation; successful preparation returns the complete negotiated map.
145#[derive(Clone, Debug, PartialEq)]
146#[non_exhaustive]
147pub struct AudioConfig {
148    /// Samples per second; must be finite and greater than zero.
149    pub sample_rate: f64,
150    /// Maximum frames per processing call, from 1 through `i32::MAX`.
151    pub max_block_size: usize,
152    /// Sample precision shared by all buses and slots.
153    pub sample_format: SampleFormat,
154    /// Processing mode reported to the plugin.
155    pub mode: ProcessMode,
156    /// Native named configuration to select, or `None` to retain the current selection.
157    pub configuration: Option<u64>,
158    /// Requested input buses; omitted buses are inactive.
159    pub inputs: Vec<AudioBusConfig>,
160    /// Requested output buses; omitted buses are inactive.
161    pub outputs: Vec<AudioBusConfig>,
162    /// Native event ports to activate; ports not named are left inactive where the format allows.
163    pub events: crate::EventConfig,
164}
165
166/// Native bypass support and its last queried state.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168#[non_exhaustive]
169pub struct BypassState {
170    /// Whether the plugin exposes writable native bypass.
171    pub support: Support,
172    /// Current bypass state, or `None` when unavailable.
173    pub enabled: Option<bool>,
174}
175
176impl BypassState {
177    /// Each field as given. Internal to the plughost crates; exempt from semver.
178    #[doc(hidden)]
179    #[must_use]
180    pub fn new(support: Support, enabled: Option<bool>) -> BypassState {
181        BypassState { support, enabled }
182    }
183}
184
185/// Explicit channel adaptation. Surround layouts are never inferred, reordered or downmixed.
186#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187#[non_exhaustive]
188pub enum ChannelAdaptation {
189    /// Require identical source and destination layouts.
190    Exact,
191    /// Duplicate the mono sample into left and right with unity gain.
192    MonoToStereo,
193    /// Average left and right with gain 0.5 per channel.
194    StereoToMono,
195}
196
197/// Source of one slot’s input bus in a serial chain.
198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
199#[non_exhaustive]
200pub enum AudioSource {
201    /// Read an external bus supplied by the caller.
202    External {
203        /// Index into `RoutedChainConfig::inputs`.
204        bus: usize,
205    },
206    /// Read an active output bus of the immediately preceding slot.
207    Previous {
208        /// Native output bus ID in the immediately preceding slot.
209        bus: u64,
210    },
211    /// Fill the destination bus with zero samples.
212    Silence,
213}
214
215/// An input bus request together with its source and explicit channel conversion.
216#[derive(Clone, Copy, Debug, PartialEq, Eq)]
217#[non_exhaustive]
218pub struct AudioInputRoute {
219    /// Destination native input bus and requested layout.
220    pub bus: AudioBusConfig,
221    /// Signal source for the destination.
222    pub source: AudioSource,
223    /// Conversion to apply between source and destination layouts.
224    pub adaptation: ChannelAdaptation,
225}
226
227impl AudioInputRoute {
228    /// Input `bus` fed from `source`, with an exact layout match; see [`Self::with_adaptation`].
229    #[must_use]
230    pub const fn new(bus: AudioBusConfig, source: AudioSource) -> AudioInputRoute {
231        AudioInputRoute {
232            bus,
233            source,
234            adaptation: ChannelAdaptation::Exact,
235        }
236    }
237
238    /// Converts the source's channels to the bus layout with `adaptation`.
239    #[must_use]
240    pub const fn with_adaptation(mut self, adaptation: ChannelAdaptation) -> AudioInputRoute {
241        self.adaptation = adaptation;
242        self
243    }
244}
245
246/// Audio and event routing for a single plugin slot.
247#[derive(Clone, Debug, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct SlotAudioConfig {
250    /// Native named configuration to select, or `None` to retain the current selection.
251    pub configuration: Option<u64>,
252    /// Input bus requests in caller order; native processing retains native bus order.
253    pub inputs: Vec<AudioInputRoute>,
254    /// Requested output buses; omitted buses are inactive.
255    pub outputs: Vec<AudioBusConfig>,
256    /// Native event ports and their serial-chain routing.
257    pub events: crate::SlotEventConfig,
258}
259
260impl SlotAudioConfig {
261    /// A slot's input routes and output buses, keeping its current named configuration and
262    /// leaving its event ports inactive.
263    #[must_use]
264    pub fn new(inputs: Vec<AudioInputRoute>, outputs: Vec<AudioBusConfig>) -> SlotAudioConfig {
265        SlotAudioConfig {
266            configuration: None,
267            inputs,
268            outputs,
269            events: crate::SlotEventConfig::default(),
270        }
271    }
272
273    /// Selects the native named configuration `configuration` first.
274    #[must_use]
275    pub fn with_configuration(mut self, configuration: u64) -> SlotAudioConfig {
276        self.configuration = Some(configuration);
277        self
278    }
279
280    /// Activates and routes the slot's event ports as `events` says.
281    #[must_use]
282    pub fn with_events(mut self, events: crate::SlotEventConfig) -> SlotAudioConfig {
283        self.events = events;
284        self
285    }
286}
287
288/// Explicit serial-chain configuration, validated before native preparation.
289///
290/// Each direction permits at most 64 audio buses and 512 active channels. External inputs
291/// are flattened in caller order; a slot’s native bus IDs do not imply buffer positions.
292#[derive(Clone, Debug, PartialEq)]
293#[non_exhaustive]
294pub struct RoutedChainConfig {
295    /// Samples per second; must be finite and greater than zero.
296    pub sample_rate: f64,
297    /// Maximum frames per processing call, from 1 through `i32::MAX`.
298    pub max_block_size: usize,
299    /// Sample precision shared by all buses and slots.
300    pub sample_format: SampleFormat,
301    /// Processing mode reported to the plugin.
302    pub mode: ProcessMode,
303    /// External bus layouts in caller buffer order.
304    pub inputs: Vec<Layout>,
305    /// The chain's external event inputs, which events name by index.
306    pub event_inputs: usize,
307    /// Per-plugin requests, in the same order as the chain’s instances.
308    pub slots: Vec<SlotAudioConfig>,
309}
310
311impl AudioConfig {
312    /// One plugin's `inputs` and `outputs` offline, keeping its current named configuration and
313    /// leaving its event ports inactive.
314    #[must_use]
315    pub fn new(
316        sample_rate: f64,
317        max_block_size: usize,
318        sample_format: SampleFormat,
319        inputs: Vec<AudioBusConfig>,
320        outputs: Vec<AudioBusConfig>,
321    ) -> AudioConfig {
322        AudioConfig {
323            sample_rate,
324            max_block_size,
325            sample_format,
326            mode: ProcessMode::Offline,
327            configuration: None,
328            inputs,
329            outputs,
330            events: crate::EventConfig::default(),
331        }
332    }
333
334    /// Reports `mode` to the plugin.
335    #[must_use]
336    pub fn with_mode(mut self, mode: ProcessMode) -> AudioConfig {
337        self.mode = mode;
338        self
339    }
340
341    /// Selects the native named configuration `configuration` first.
342    #[must_use]
343    pub fn with_configuration(mut self, configuration: u64) -> AudioConfig {
344        self.configuration = Some(configuration);
345        self
346    }
347
348    /// Activates the native event ports `events` names.
349    #[must_use]
350    pub fn with_events(mut self, events: crate::EventConfig) -> AudioConfig {
351        self.events = events;
352        self
353    }
354
355    /// Checks scalar processing values, unique bus IDs, layouts, and audio capacity limits.
356    pub fn validate(&self) -> Result<(), InputError> {
357        crate::config::validate_processing(self.sample_rate, self.max_block_size)?;
358        validate_buses(&self.inputs)?;
359        validate_buses(&self.outputs)
360    }
361
362    /// Total active input channels across the requested native buses.
363    pub fn input_channels(&self) -> usize {
364        active_channels(&self.inputs)
365    }
366
367    /// Total active output channels across the requested native buses.
368    pub fn output_channels(&self) -> usize {
369        active_channels(&self.outputs)
370    }
371}
372
373impl RoutedChainConfig {
374    /// A chain processing `inputs` through `slots` offline, without external event inputs; see
375    /// [`Self::with_mode`] and [`Self::with_event_inputs`].
376    #[must_use]
377    pub fn new(
378        sample_rate: f64,
379        max_block_size: usize,
380        sample_format: SampleFormat,
381        inputs: Vec<Layout>,
382        slots: Vec<SlotAudioConfig>,
383    ) -> RoutedChainConfig {
384        RoutedChainConfig {
385            sample_rate,
386            max_block_size,
387            sample_format,
388            mode: ProcessMode::Offline,
389            inputs,
390            event_inputs: 0,
391            slots,
392        }
393    }
394
395    /// Reports `mode` to the plugins.
396    #[must_use]
397    pub fn with_mode(mut self, mode: ProcessMode) -> RoutedChainConfig {
398        self.mode = mode;
399        self
400    }
401
402    /// Gives the chain `event_inputs` external event inputs.
403    #[must_use]
404    pub fn with_event_inputs(mut self, event_inputs: usize) -> RoutedChainConfig {
405        self.event_inputs = event_inputs;
406        self
407    }
408
409    /// Validates routing without querying or mutating any plugin. Native bus IDs/layouts are
410    /// checked when each slot negotiates its requested configuration.
411    pub fn validate(&self, slots: usize) -> Result<(), InputError> {
412        if slots == 0 {
413            return Err(InputError::EmptyChain);
414        }
415        if self.slots.len() != slots {
416            return Err(InputError::AudioSlotCount);
417        }
418        crate::config::validate_processing(self.sample_rate, self.max_block_size)?;
419        if self.inputs.len() > MAX_AUDIO_BUSES {
420            return Err(InputError::AudioBusCount);
421        }
422        if self.input_channels() > MAX_AUDIO_CHANNELS {
423            return Err(InputError::AudioChannelCount);
424        }
425        if self.event_inputs > crate::MAX_EVENT_PORTS {
426            return Err(InputError::EventPortCount);
427        }
428        for (slot, config) in self.slots.iter().enumerate() {
429            let previous = slot
430                .checked_sub(1)
431                .map(|previous| &self.slots[previous].events);
432            config.events.validate(slot, self.event_inputs, previous)?;
433            if config.inputs.len() > MAX_AUDIO_BUSES {
434                return Err(InputError::AudioBusCount);
435            }
436            let inputs: Vec<AudioBusConfig> = config.inputs.iter().map(|route| route.bus).collect();
437            validate_buses(&inputs)?;
438            validate_buses(&config.outputs)?;
439            for route in &config.inputs {
440                // A disabled bus consumes no audio; its saved source choice is not resolved.
441                if !route.bus.active {
442                    continue;
443                }
444                let source = match route.source {
445                    AudioSource::External { bus } => self.inputs.get(bus).copied(),
446                    AudioSource::Previous { bus } => slot
447                        .checked_sub(1)
448                        .and_then(|previous| {
449                            self.slots[previous]
450                                .outputs
451                                .iter()
452                                .find(|output| output.id == bus && output.active)
453                        })
454                        .map(|output| output.layout),
455                    // Silence has the target's layout and requires no channel conversion.
456                    AudioSource::Silence => Some(route.bus.layout),
457                }
458                .ok_or(InputError::AudioRoute {
459                    slot,
460                    bus: route.bus.id,
461                })?;
462                route.adaptation.validate(source, route.bus.layout)?;
463            }
464        }
465        Ok(())
466    }
467
468    /// Total external input channels in caller buffer order.
469    pub fn input_channels(&self) -> usize {
470        self.inputs.iter().map(|layout| layout.channels()).sum()
471    }
472
473    /// Total active output channels of the final slot.
474    pub fn output_channels(&self) -> usize {
475        self.slots
476            .last()
477            .map_or(0, |slot| active_channels(&slot.outputs))
478    }
479
480    /// The chain's event outputs: the last slot's collected output ports.
481    pub fn event_outputs(&self) -> usize {
482        self.slots
483            .last()
484            .map_or(0, |slot| slot.events.outputs.len())
485    }
486
487    /// The selected slot's native request, retaining the chain's shared processing precision.
488    /// Internal to the plughost crates; exempt from semver.
489    #[doc(hidden)]
490    pub fn slot_config(&self, slot: usize) -> Result<AudioConfig, InputError> {
491        let config = self.slots.get(slot).ok_or(InputError::Slot)?;
492        Ok(AudioConfig {
493            sample_rate: self.sample_rate,
494            max_block_size: self.max_block_size,
495            sample_format: self.sample_format,
496            mode: self.mode,
497            configuration: config.configuration,
498            inputs: config.inputs.iter().map(|route| route.bus).collect(),
499            outputs: config.outputs.clone(),
500            events: config.events.native(),
501        })
502    }
503}
504
505impl ChannelAdaptation {
506    /// Checks whether this conversion supports the exact source and target layouts.
507    pub fn validate(self, source: Layout, target: Layout) -> Result<(), InputError> {
508        let valid = match self {
509            Self::Exact => source == target,
510            Self::MonoToStereo => source == Layout::Mono && target == Layout::Stereo,
511            Self::StereoToMono => source == Layout::Stereo && target == Layout::Mono,
512        };
513        if !valid {
514            return Err(InputError::ChannelAdaptation { source, target });
515        }
516        Ok(())
517    }
518}
519
520fn active_channels(buses: &[AudioBusConfig]) -> usize {
521    buses
522        .iter()
523        .filter(|bus| bus.active)
524        .map(|bus| bus.layout.channels())
525        .sum()
526}
527
528fn validate_buses(buses: &[AudioBusConfig]) -> Result<(), InputError> {
529    if buses.len() > MAX_AUDIO_BUSES {
530        return Err(InputError::AudioBusCount);
531    }
532    for (index, bus) in buses.iter().enumerate() {
533        if buses[..index].iter().any(|previous| previous.id == bus.id) {
534            return Err(InputError::DuplicateAudioBus { id: bus.id });
535        }
536        if bus.active && bus.layout == Layout::None {
537            return Err(InputError::AudioBusLayout { id: bus.id });
538        }
539    }
540    if active_channels(buses) > MAX_AUDIO_CHANNELS {
541        return Err(InputError::AudioChannelCount);
542    }
543    Ok(())
544}
545
546#[cfg(test)]
547mod tests;