nice_plug_core/buffer.rs
1//! Adapters and utilities for working with audio buffers.
2
3use std::marker::PhantomData;
4
5mod blocks;
6mod samples;
7
8pub use blocks::{Block, BlockChannelsIter, BlocksIter};
9pub use samples::{ChannelSamples, ChannelSamplesIter, SamplesIter};
10
11/// The audio buffers used during processing. This contains the output audio output buffers with the
12/// inputs already copied to the outputs. You can either use the iterator adapters to conveniently
13/// and efficiently iterate over the samples, or you can do your own thing using the raw audio
14/// buffers.
15///
16/// TODO: This lifetime makes zero sense because you're going to need unsafe lifetime casts to use
17/// this either way. Maybe just get rid of it in favor for raw pointers.
18#[derive(Default)]
19pub struct Buffer<'a> {
20 /// The number of samples contained within `output_slices`. This needs to be stored separately
21 /// to be able to handle 0 channel IO for MIDI-only plugins.
22 num_samples: usize,
23
24 /// Contains slices for the plugin's outputs. You can't directly create a nested slice from a
25 /// pointer to pointers, so this needs to be preallocated in the setup call and kept around
26 /// between process calls. And because storing a reference to this means a) that you need a lot
27 /// of lifetime annotations everywhere and b) that at some point you need unsound lifetime casts
28 /// because this `Buffers` either cannot have the same lifetime as the separately stored output
29 /// buffers, and it also cannot be stored in a field next to it because that would mean
30 /// containing mutable references to data stored in a mutex.
31 output_slices: Vec<&'a mut [f32]>,
32}
33
34impl<'a> Buffer<'a> {
35 /// Returns the number of samples per channel in this buffer.
36 #[inline]
37 pub fn samples(&self) -> usize {
38 self.num_samples
39 }
40
41 /// Returns the number of channels in this buffer.
42 #[inline]
43 pub fn channels(&self) -> usize {
44 self.output_slices.len()
45 }
46
47 /// Returns true if this buffer does not contain any samples.
48 #[inline]
49 pub fn is_empty(&self) -> bool {
50 self.num_samples == 0
51 }
52
53 /// Obtain the raw audio buffers.
54 #[inline]
55 pub fn as_slice(&mut self) -> &mut [&'a mut [f32]] {
56 &mut self.output_slices
57 }
58
59 /// The same as [`as_slice()`][Self::as_slice()], but for a non-mutable reference. This is
60 /// usually not needed.
61 #[inline]
62 pub fn as_slice_immutable(&self) -> &[&'a mut [f32]] {
63 &self.output_slices
64 }
65
66 /// Iterate over the samples, returning a channel iterator for each sample.
67 #[inline]
68 pub fn iter_samples<'slice>(&'slice mut self) -> SamplesIter<'slice, 'a> {
69 SamplesIter {
70 buffers: self.output_slices.as_mut_slice(),
71 current_sample: 0,
72 samples_end: self.samples(),
73 _marker: PhantomData,
74 }
75 }
76
77 /// Iterate over the buffer in blocks with the specified maximum size. The ideal maximum block
78 /// size depends on the plugin in question, but 64 or 128 samples works for most plugins. Since
79 /// the buffer's total size may not be cleanly divisible by the maximum size, the returned
80 /// buffers may have any size in `[1, max_block_size]`. This is useful when using algorithms
81 /// that work on entire blocks of audio, like those that would otherwise need to perform
82 /// expensive per-sample branching or that can use per-sample SIMD as opposed to per-channel
83 /// SIMD.
84 ///
85 /// The parameter smoothers can also produce smoothed values for an entire block using
86 /// [`Smoother::next_block()`][crate::params::smoothing::Smoother::next_block()].
87 ///
88 /// You can use this to obtain block-slices from a buffer so you can pass them to a library:
89 ///
90 /// ```ignore
91 /// for block in buffer.iter_blocks(128) {
92 /// let mut block_channels = block.into_iter();
93 /// let stereo_slice = &[
94 /// block_channels.next().unwrap(),
95 /// block_channels.next().unwrap(),
96 /// ];
97 ///
98 /// // Do something cool with `stereo_slice`
99 /// }
100 /// ````
101 #[inline]
102 pub fn iter_blocks<'slice>(&'slice mut self, max_block_size: usize) -> BlocksIter<'slice, 'a> {
103 BlocksIter {
104 buffers: self.output_slices.as_mut_slice(),
105 max_block_size,
106 current_block_start: 0,
107 _marker: PhantomData,
108 }
109 }
110
111 /// Set the slices in the raw output slice vector. This vector needs to be resized to match the
112 /// number of output channels during the plugin's initialization. Then during audio processing,
113 /// these slices should be updated to point to the plugin's audio buffers. The `num_samples`
114 /// argument should match the length of the inner slices.
115 ///
116 /// # Safety
117 ///
118 /// The stored slices must point to live data when this object is passed to the plugins' process
119 /// function. The rest of this object also assumes all channel lengths are equal. Panics will
120 /// likely occur if this is not the case.
121 pub unsafe fn set_slices(
122 &mut self,
123 num_samples: usize,
124 update: impl FnOnce(&mut Vec<&'a mut [f32]>),
125 ) {
126 self.num_samples = num_samples;
127 update(&mut self.output_slices);
128
129 #[cfg(debug_assertions)]
130 for slice in &self.output_slices {
131 use crate::nice_debug_assert_eq;
132
133 nice_debug_assert_eq!(slice.len(), num_samples);
134 }
135 }
136}
137
138#[cfg(any(miri, test))]
139mod miri {
140 use super::*;
141
142 #[test]
143 fn repeated_access() {
144 let mut real_buffers = vec![vec![0.0; 512]; 2];
145 let mut buffer = Buffer::default();
146 unsafe {
147 buffer.set_slices(512, |output_slices| {
148 let (first_channel, other_channels) = real_buffers.split_at_mut(1);
149 *output_slices = vec![&mut first_channel[0], &mut other_channels[0]];
150 })
151 };
152
153 for samples in buffer.iter_samples() {
154 for sample in samples {
155 *sample += 0.001;
156 }
157 }
158
159 for mut samples in buffer.iter_samples() {
160 for _ in 0..2 {
161 for sample in samples.iter_mut() {
162 *sample += 0.001;
163 }
164 }
165 }
166
167 assert_eq!(real_buffers[0][0], 0.003);
168 }
169
170 #[test]
171 fn repeated_slices() {
172 let mut real_buffers = vec![vec![0.0; 512]; 2];
173 let mut buffer = Buffer::default();
174 unsafe {
175 buffer.set_slices(512, |output_slices| {
176 let (first_channel, other_channels) = real_buffers.split_at_mut(1);
177 *output_slices = vec![&mut first_channel[0], &mut other_channels[0]];
178 })
179 };
180
181 // These iterators should not alias
182 let mut blocks = buffer.iter_blocks(16);
183 let (_block1_offset, block1) = blocks.next().unwrap();
184 let (_block2_offset, block2) = blocks.next().unwrap();
185 for channel in block1 {
186 for sample in channel.iter_mut() {
187 *sample += 0.001;
188 }
189 }
190 for channel in block2 {
191 for sample in channel.iter_mut() {
192 *sample += 0.001;
193 }
194 }
195
196 for i in 0..32 {
197 assert_eq!(real_buffers[0][i], 0.001);
198 }
199 for i in 32..48 {
200 assert_eq!(real_buffers[0][i], 0.0);
201 }
202 }
203}