1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Trait for dealing with abstract channel buffers.

use crate::channel::{Channel, ChannelMut};

mod skip;
pub use self::skip::Skip;

mod limit;
pub use self::limit::Limit;

mod chunk;
pub use self::chunk::Chunk;

mod tail;
pub use self::tail::Tail;

mod exact_size_buf;
pub use self::exact_size_buf::ExactSizeBuf;

mod resizable_buf;
pub use self::resizable_buf::ResizableBuf;

mod interleaved_buf;
pub use self::interleaved_buf::InterleavedBuf;

mod as_interleaved;
pub use self::as_interleaved::AsInterleaved;

mod as_interleaved_mut;
pub use self::as_interleaved_mut::AsInterleavedMut;

/// The base trait available to all audio buffers.
///
/// This provides information which is available to all buffers, such as the
/// number of channels.
///
/// ```rust
/// use rotary::Buf as _;
///
/// let buffer = rotary::interleaved![[0; 4]; 2];
///
/// assert_eq!(buffer.channels(), 2);
/// ```
///
/// It also carries a number of slicing combinators, wuch as [skip][Buf::skip]
/// and [limit][Buf::limit] which allows an audio buffer to be sliced as needed.
///
///
/// ```rust
/// use rotary::{Buf as _, ExactSizeBuf as _};
///
/// let buffer = rotary::interleaved![[0; 4]; 2];
///
/// assert_eq!(buffer.channels(), 2);
/// assert_eq!(buffer.frames(), 4);
/// assert_eq!(buffer.limit(2).frames(), 2);
/// ```
pub trait Buf {
    /// A typical number of frames for each channel in the buffer, if known.
    ///
    /// If you only want to support buffers which have exact sizes use
    /// [ExactSizeBuf].
    ///
    /// This is only a best effort hint. We can't require any [Channels] to know
    /// the exact number of frames, because we want to be able to implement it
    /// for types which does not keep track of the exact number of frames it
    /// expects each channel to have such as `Vec<Vec<i16>>`.
    ///
    /// ```rust
    /// use rotary::Buf;
    ///
    /// fn test(buf: impl Buf) {
    ///     assert_eq!(buf.channels(), 2);
    ///     assert_eq!(buf.frames_hint(), Some(4));
    /// }
    ///
    /// test(vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]);
    /// ```
    ///
    /// But it should be clear that such a buffer supports a variable number of
    /// frames in each channel.
    ///
    /// ```rust
    /// use rotary::Channels;
    ///
    /// fn test(buf: impl Channels<i16>) {
    ///     assert_eq!(buf.channels(), 2);
    ///     assert_eq!(buf.frames_hint(), Some(4));
    ///
    ///     assert_eq!(buf.channel(0).frames(), 4);
    ///     assert_eq!(buf.channel(1).frames(), 2);
    /// }
    ///
    /// test(vec![vec![1, 2, 3, 4], vec![5, 6]]);
    /// ```
    fn frames_hint(&self) -> Option<usize>;

    /// The number of channels in the buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rotary::Channels;
    ///
    /// fn test(buf: impl Channels<i16>) {
    ///     assert_eq!(buf.channels(), 2);
    ///
    ///     assert_eq! {
    ///         buf.channel(0).iter().collect::<Vec<_>>(),
    ///         &[1, 2, 3, 4],
    ///     }
    ///
    ///     assert_eq! {
    ///         buf.channel(1).iter().collect::<Vec<_>>(),
    ///         &[5, 6, 7, 8],
    ///     }
    /// }
    ///
    /// test(rotary::interleaved![[1, 2, 3, 4], [5, 6, 7, 8]]);
    /// test(rotary::wrap::interleaved(&[1, 5, 2, 6, 3, 7, 4, 8], 2));
    /// test(vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]);
    /// ```
    fn channels(&self) -> usize;

    /// Construct a new buffer where `n` frames are skipped.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rotary::Buf as _;
    /// use rotary::buf;
    ///
    /// let from = rotary::interleaved![[0, 0, 1, 1], [0; 4]];
    /// let mut to = rotary::Interleaved::with_topology(2, 4);
    ///
    /// buf::copy(from.skip(2), &mut to);
    ///
    /// assert_eq!(to.as_slice(), &[1, 0, 1, 0, 0, 0, 0, 0]);
    /// ```
    ///
    /// With a mutable buffer.
    ///
    /// ```rust
    /// use rotary::{Buf as _, ChannelsMut as _};
    /// use rotary::{buf, wrap};
    ///
    /// let from = wrap::interleaved(&[1, 1, 1, 1, 1, 1, 1, 1], 2);
    /// let mut to = rotary::Interleaved::with_topology(2, 4);
    ///
    /// buf::copy(from, (&mut to).skip(2));
    ///
    /// assert_eq!(to.as_slice(), &[0, 0, 0, 0, 1, 1, 1, 1])
    /// ```
    fn skip(self, n: usize) -> Skip<Self>
    where
        Self: Sized,
    {
        Skip::new(self, n)
    }

    /// Construct a new buffer where `n` frames are skipped.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rotary::Buf as _;
    /// use rotary::buf;
    ///
    /// let from = rotary::interleaved![[1; 4]; 2];
    /// let mut to = rotary::interleaved![[0; 4]; 2];
    ///
    /// buf::copy(from, (&mut to).tail(2));
    ///
    /// assert_eq!(to.as_slice(), &[0, 0, 0, 0, 1, 1, 1, 1]);
    /// ```
    fn tail(self, n: usize) -> Tail<Self>
    where
        Self: Sized,
    {
        Tail::new(self, n)
    }

    /// Limit the channel buffer to `limit` number of frames.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rotary::Buf as _;
    /// use rotary::buf;
    ///
    /// let from = rotary::interleaved![[1; 4]; 2];
    /// let mut to = rotary::Interleaved::with_topology(2, 4);
    ///
    /// buf::copy(from, (&mut to).limit(2));
    ///
    /// assert_eq!(to.as_slice(), &[1, 1, 1, 1, 0, 0, 0, 0]);
    /// ```
    fn limit(self, limit: usize) -> Limit<Self>
    where
        Self: Sized,
    {
        Limit::new(self, limit)
    }

    /// Construct a range of frames corresponds to the chunk with `len` and
    /// position `n`.
    ///
    /// Which is the range `n * len .. n * len + len`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rotary::Buf as _;
    /// use rotary::buf;
    ///
    /// let from = rotary::interleaved![[1; 4]; 2];
    /// let mut to = rotary::interleaved![[0; 4]; 2];
    ///
    /// buf::copy(from, (&mut to).chunk(1, 2));
    ///
    /// assert_eq!(to.as_slice(), &[0, 0, 0, 0, 1, 1, 1, 1]);
    /// ```
    fn chunk(self, n: usize, len: usize) -> Chunk<Self>
    where
        Self: Sized,
    {
        Chunk::new(self, n, len)
    }
}

/// A trait describing something that has channels.
pub trait Channels<T>: Buf {
    /// Return a handler to the buffer associated with the channel.
    ///
    /// Note that we don't access the buffer for the underlying channel directly
    /// as a linear buffer like `&[T]`, because the underlying representation
    /// might be different.
    ///
    /// We must instead make use of the various utility functions found on
    /// [Channel] to copy data out of the channel.
    ///
    /// # Panics
    ///
    /// Panics if the specified channel is out of bound as reported by
    /// [Buf::channels].
    fn channel(&self, channel: usize) -> Channel<'_, T>;
}

/// A trait describing a mutable audio buffer.
pub trait ChannelsMut<T>: Channels<T> {
    /// Return a mutable handler to the buffer associated with the channel.
    ///
    /// # Panics
    ///
    /// Panics if the specified channel is out of bound as reported by
    /// [Buf::channels].
    fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T>;

    /// Copy one channel into another.
    ///
    /// If the channels have different sizes, the minimul difference between
    /// them will be copied.
    ///
    /// # Panics
    ///
    /// Panics if one of the channels being tried to copy from or to is out of
    /// bounds as reported by [Buf::channels].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rotary::{Channels, ChannelsMut};
    ///
    /// let mut buffer: rotary::Dynamic<i16> = rotary::dynamic![[1, 2, 3, 4], [0, 0, 0, 0]];
    /// buffer.copy_channels(0, 1);
    ///
    /// assert_eq!(buffer.channel(1), buffer.channel(0));
    /// ```
    fn copy_channels(&mut self, from: usize, to: usize)
    where
        T: Copy;
}

impl<B> Buf for &B
where
    B: ?Sized + Buf,
{
    #[inline]
    fn frames_hint(&self) -> Option<usize> {
        (**self).frames_hint()
    }

    #[inline]
    fn channels(&self) -> usize {
        (**self).channels()
    }
}

impl<B, T> Channels<T> for &B
where
    B: Channels<T>,
{
    #[inline]
    fn channel(&self, channel: usize) -> Channel<'_, T> {
        (**self).channel(channel)
    }
}

impl<B> Buf for &mut B
where
    B: ?Sized + Buf,
{
    #[inline]
    fn frames_hint(&self) -> Option<usize> {
        (**self).frames_hint()
    }

    #[inline]
    fn channels(&self) -> usize {
        (**self).channels()
    }
}

impl<B, T> Channels<T> for &mut B
where
    B: ?Sized + Channels<T>,
{
    #[inline]
    fn channel(&self, channel: usize) -> Channel<'_, T> {
        (**self).channel(channel)
    }
}

impl<B, T> ChannelsMut<T> for &mut B
where
    B: ?Sized + ChannelsMut<T>,
{
    #[inline]
    fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T> {
        (**self).channel_mut(channel)
    }

    #[inline]
    fn copy_channels(&mut self, from: usize, to: usize)
    where
        T: Copy,
    {
        (**self).copy_channels(from, to);
    }
}

impl<T> Buf for Vec<Vec<T>> {
    fn frames_hint(&self) -> Option<usize> {
        Some(self.get(0)?.len())
    }

    fn channels(&self) -> usize {
        self.len()
    }
}

impl<T> Channels<T> for Vec<Vec<T>> {
    fn channel(&self, channel: usize) -> Channel<'_, T> {
        Channel::linear(&self[channel])
    }
}

impl<T> ChannelsMut<T> for Vec<Vec<T>>
where
    T: Copy,
{
    fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T> {
        ChannelMut::linear(&mut self[channel])
    }

    fn copy_channels(&mut self, from: usize, to: usize) {
        assert! {
            from < self.len(),
            "copy from channel {} is out of bounds 0-{}",
            from,
            self.len()
        };
        assert! {
            to < self.len(),
            "copy to channel {} which is out of bounds 0-{}",
            to,
            self.len()
        };

        if from != to {
            // Safety: We're making sure not to access any mutable buffers which are
            // not initialized.
            unsafe {
                let ptr = self.as_mut_ptr();
                let from = &*ptr.add(from);
                let to = &mut *ptr.add(to);
                let end = usize::min(from.len(), to.len());
                to[..end].copy_from_slice(&from[..end]);
            }
        }
    }
}

impl<T> Buf for [Vec<T>] {
    fn frames_hint(&self) -> Option<usize> {
        Some(self.get(0)?.len())
    }

    fn channels(&self) -> usize {
        self.as_ref().len()
    }
}

impl<T> Channels<T> for [Vec<T>] {
    fn channel(&self, channel: usize) -> Channel<'_, T> {
        Channel::linear(&self[channel])
    }
}