Skip to main content

Audio

Struct Audio 

Source
pub struct Audio<'a> { /* private fields */ }
Expand description

Input and output audio buffers to processed by the plugin.

Audio data in CLAP follow the following tree structure:

  • Plugins may have an arbitrary amount of input and output ports;
  • Each port can hold either 32-bit, or 64-bit floating-point sample data;
  • Port sample data is split in multiple channels (1 for mono, 2 for stereo, etc.);
  • Each channel is a raw buffer (i.e. slice) of either f32 or f64 samples.

This structure applies both to inputs and outputs: the Audio struct allows to retrieve InputPorts and OutputPorts separately, but they can also be accessed together as Input/Output PortPairs. This allows for the common use-case of borrowing both an input and its matching output for processing, while also being safe to hosts using the same buffer for both.

For each port type (input, output, or paired), ports can be accessed either individually with an index, or all at once with an iterator. For instance, InputPorts can be accessed either one-at-a-time with Audio::input_port, or with an iterator from Audio::input_ports. A Audio::input_port_count method is also available. The same methods are available for OutputPorts and PortPairs.

Note that because ports can individually hold either 32-bit or 64-bit sample data, an extra sample type detection step is necessary before the port’s channels themselves can be accessed. This is done through the channels methods on each port type, and returns a SampleType enum indicating whether the port’s buffers hold 32-bit or 64-bit samples.

§Example

The following example implements a gain plugin that amplifies every input channel by 2, and writes the result to a matching output channel.

use clack_plugin::prelude::*;

pub fn process(mut audio: Audio) -> Result<ProcessStatus, PluginError> {
    for mut port_pair in &mut audio {
        // For this example, we'll only care about 32-bit sample data.
        let Some(channel_pairs) = port_pair.channels()?.into_f32() else { continue };

        for channel_pair in channel_pairs {
            match channel_pair {
                // If this input has no matching output, we simply do nothing with it.
                ChannelPair::InputOnly(_) => {}
                // If this output has no matching input, we fill it with silence.
                ChannelPair::OutputOnly(buf) => buf.fill(0.0),
                // If this is a separate pair of I/O buffers,
                // we can copy the input to the outputs while multiplying
                ChannelPair::InputOutput(input, output) => {
                    for (input, output) in input.iter().zip(output) {
                        *output = input * 2.0
                    }
                }
                // If the host sent us a single buffer to be processed in-place
                // (i.e. input and output buffers point to the same location),
                // then we can do the processing in-place directly.
                ChannelPair::InPlace(buf) => {
                    for sample in buf {
                        *sample *= 2.0
                    }
                }
            }
        }
    }

    Ok(ProcessStatus::Continue)
}

The following example shows how to gather different inputs and outputs simultaneously, and here uses it to simply swap the left and right stereo channels.

use clack_plugin::prelude::*;

pub fn process(mut audio: Audio) -> Result<ProcessStatus, PluginError> {
    for mut port_pair in &mut audio {
        // For this example, we'll only care about 32-bit sample data.
        let Some(mut channel_pairs) = port_pair.channels()?.into_f32() else { continue; };

        // Buffers to hold pointers to the left and right channels
        let mut input_channels: [Option<&[f32]>; 2] = [None, None];
        let mut output_channels: [Option<&mut [f32]>; 2] = [None, None];

        // Before we can process the buffers, we need to check all the necessary channels
        // are present, in case the host messed up the port configuration.
        // (Yes, some do.)
        for ((channel_pair, in_ptr), out_ptr) in channel_pairs
            .iter_mut()
            .zip(&mut input_channels)
            .zip(&mut output_channels)
        {
            // A separate pair of channels is just what we want for this example!
            // However, a real plugin implementation would need to gracefully handle
            // the other cases, including having spare input buffers ready for
            // in-place processing.
            if let ChannelPair::InputOutput(input, output) = channel_pair {
                *in_ptr = Some(input);
                *out_ptr = Some(output);
            }
        }

        // Channel swap! (assuming all channels are there)
        if let (Some(in_l), Some(out_r)) = (&input_channels[0], &mut output_channels[1]) {
            out_r.copy_from_slice(in_l)
        }
        if let (Some(in_r), Some(out_l)) = (&input_channels[1], &mut output_channels[0]) {
            out_l.copy_from_slice(in_r)
        }
    }

    Ok(ProcessStatus::Continue)
}

Implementations§

Source§

impl<'a> Audio<'a>

Source

pub unsafe fn from_raw(raw_process: &clap_process) -> Audio<'_>

Create a new Audio from the information in a given raw, C-FFI compatible clap_process struct.

§Safety

Users must ensure all fields of the given raw_process are valid, and that all buffers it points to stay valid for the given lifetime.

Source

pub unsafe fn from_raw_buffers( inputs: &'a [clap_audio_buffer], outputs: &'a mut [clap_audio_buffer], frames_count: u32, ) -> Self

Create a new Audio from raw buffer structs.

§Safety

The caller must ensure all buffer structs are valid for ’a, including all the buffer pointers they contain.

The caller must also ensure frames_count is lower than or equal to the sizes of the channel buffers pointed to by buffers.

Source

pub fn raw_buffers( &mut self, ) -> (&'a [clap_audio_buffer], &mut [clap_audio_buffer])

Returns the raw input and output buffers structs, respectively.

Source

pub fn to_raw_buffers( self, ) -> (&'a [clap_audio_buffer], &'a mut [clap_audio_buffer])

Returns the raw input and output buffers structs, respectively, consuming the audio struct.

Source

pub fn raw_input_buffers(&self) -> &'a [clap_audio_buffer]

Returns the raw input buffers structs.

Source

pub fn raw_output_buffers(&mut self) -> &mut [clap_audio_buffer]

Returns the raw output buffers structs.

Source

pub fn to_raw_output_buffers(self) -> &'a mut [clap_audio_buffer]

Returns the raw output buffers structs, consuming the audio struct.

Source

pub fn input_port(&self, index: usize) -> Option<InputPort<'_>>

Retrieves the InputPort at a given index.

This returns None if there is no input port at the given index.

See also the input_port_count method to know how many input ports are available, and the input_ports method to get all input ports at once.

Source

pub fn input_port_info(&self, index: usize) -> Option<AudioPortProcessingInfo>

Retrieves the AudioPortProcessingInfo of the InputPort at a given index.

This returns None if there is no input port at the given index.

See also the input_port_count method to know how many output ports are available, and the input_ports_infos method to get the info of all input ports at once.

Source

pub fn input_port_count(&self) -> usize

Retrieves the number of available InputPorts.

Source

pub fn input_ports(&self) -> InputPortsIter<'_> ⓘ

Returns an iterator of all the available InputPorts at once.

See also the input_port method to retrieve a single input port by its index.

Source

pub fn input_ports_infos( &self, ) -> impl ExactSizeIterator<Item = AudioPortProcessingInfo> + '_

Retrieves the AudioPortProcessingInfo of all the available OutputPorts at once.

See also the output_port_info method to retrieve a single output port by its index.

Source

pub fn output_port(&mut self, index: usize) -> Option<OutputPort<'_>>

Retrieves the OutputPort at a given index.

This returns None if there is no output port at the given index.

See also the output_port_count method to know how many output ports are available, and the output_ports method to get all output ports at once.

Source

pub fn output_port_info(&self, index: usize) -> Option<AudioPortProcessingInfo>

Retrieves the AudioPortProcessingInfo of the OutputPort at a given index.

This returns None if there is no output port at the given index.

See also the output_port_count method to know how many output ports are available, and the output_ports_infos method to get the info of all output ports at once.

Source

pub fn output_port_count(&self) -> usize

Retrieves the number of available OutputPorts.

Source

pub fn output_ports(&mut self) -> OutputPortsIter<'_> ⓘ

Returns an iterator of all the available OutputPorts at once.

See also the output_port method to retrieve a single output port by its index.

Source

pub fn output_ports_infos( &self, ) -> impl ExactSizeIterator<Item = AudioPortProcessingInfo> + '_

Retrieves the AudioPortProcessingInfo of all the available OutputPorts at once.

See also the output_port_info method to retrieve a single output port by its index.

Source

pub fn port_pair(&mut self, index: usize) -> Option<PortPair<'_>>

Retrieves the PortPair at a given index.

This returns None if there is no available port at the given index.

See also the port_pair_count method to know how many port pairs are available, and the port_pairs method to get all port pairs at once.

Source

pub fn port_pair_count(&self) -> usize

Retrieves the number of available PortPairs.

Because PortPair can be mismatched (i.e. have an input but no output, or vice-versa), this is effectively equal to the maximum number of ports available, either on the input side or the output side.

Source

pub fn port_pairs(&mut self) -> PortPairsIter<'_> ⓘ

Returns an iterator of all the available PortPairs at once.

See also the port_pair method to retrieve a single input port by its index.

Source

pub fn port_sub_range<R: RangeBounds<usize> + Clone>( &mut self, range: R, ) -> Audio<'_>

Returns a sub-range of ports as a new Audio struct, similar to a subslice of items.

Source

pub fn frames_count(&self) -> u32

Returns the number of frames to process in this block.

This will always match the number of samples of every audio buffer in this Audio struct.

Trait Implementations§

Source§

impl<'buf: 'a, 'a> IntoIterator for &'a mut Audio<'buf>

Source§

fn into_iter(self) -> Self::IntoIter

Returns an iterator of all the available PortPairs at once. This is equivalent to using port_pairs.

Source§

type Item = PortPair<'a>

The type of the elements being iterated over.
Source§

type IntoIter = PortPairsIter<'a>

Which kind of iterator are we turning this into?

Auto Trait Implementations§

§

impl<'a> !UnwindSafe for Audio<'a>

§

impl<'a> Freeze for Audio<'a>

§

impl<'a> RefUnwindSafe for Audio<'a>

§

impl<'a> Send for Audio<'a>

§

impl<'a> Sync for Audio<'a>

§

impl<'a> Unpin for Audio<'a>

§

impl<'a> UnsafeUnpin for Audio<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.