clack-host 0.1.0

Low-level, safe Rust wrappers to create audio plugin hosts using the CLAP audio plugin API.
Documentation
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Types to manipulate input and output audio buffers for processing.

use crate::util::check_collection_clap_size_overflow;
use clack_common::process::AudioPortProcessingInfo;
use clap_sys::audio_buffer::clap_audio_buffer;
use core::array::IntoIter;

pub struct InputChannel<'a, T> {
    pub buffer: &'a mut [T],
    pub is_constant: bool,
}

impl<'a, T> InputChannel<'a, T> {
    #[inline]
    pub fn from_buffer<D: ?Sized + AsMut<[T]> + 'a>(buffer: &'a mut D, is_constant: bool) -> Self {
        Self {
            buffer: buffer.as_mut(),
            is_constant,
        }
    }

    #[inline]
    pub fn variable<D: ?Sized + AsMut<[T]> + 'a>(buffer: &'a mut D) -> Self {
        Self::from_buffer(buffer, false)
    }

    #[inline]
    pub fn constant<D: ?Sized + AsMut<[T]> + 'a>(buffer: &'a mut D) -> Self {
        Self::from_buffer(buffer, true)
    }
}

pub enum AudioPortBufferType<I32, I64> {
    F32(I32),
    F64(I64),
}

impl<I32> AudioPortBufferType<I32, IntoIter<InputChannel<'static, f64>, 0>> {
    #[inline]
    pub fn f32_input_only(iterator: I32) -> Self {
        Self::F32(iterator)
    }
}

impl<I32> AudioPortBufferType<I32, IntoIter<&'static mut [f64], 0>> {
    #[inline]
    pub fn f32_output_only(iterator: I32) -> Self {
        Self::F32(iterator)
    }
}

impl<I64> AudioPortBufferType<IntoIter<InputChannel<'static, f32>, 0>, I64> {
    #[inline]
    pub fn f64_input_only(iterator: I64) -> Self {
        Self::F64(iterator)
    }
}

impl<I64> AudioPortBufferType<IntoIter<&'static mut [f32], 0>, I64> {
    #[inline]
    pub fn f64_output_only(iterator: I64) -> Self {
        Self::F64(iterator)
    }
}

pub struct AudioPortBuffer<I32, I64> {
    pub channels: AudioPortBufferType<I32, I64>,
    pub latency: u32,
}

// bikeshed
pub struct AudioPorts {
    buffer_lists: Vec<*mut f32>, // Can be f32 or f64, cast on-demand
    buffer_configs: Vec<clap_audio_buffer>,
}

// SAFETY: The pointers are only temporary storage, they are not used unless AudioPorts is exclusively borrowed
unsafe impl Send for AudioPorts {}
// SAFETY: The pointers are only temporary storage, they are not used unless AudioPorts is exclusively borrowed
unsafe impl Sync for AudioPorts {}

impl AudioPorts {
    #[cfg(feature = "clack-plugin")]
    pub fn from_plugin_audio_mut<'a>(
        audio: &'a mut clack_plugin::prelude::Audio,
    ) -> (InputAudioBuffers<'a>, OutputAudioBuffers<'a>) {
        let frames_count = audio.frames_count();
        let (ins, outs) = audio.raw_buffers();

        // SAFETY: the validity of the buffers is guaranteed by the Audio type
        unsafe {
            (
                InputAudioBuffers::from_raw_buffers(ins, frames_count),
                OutputAudioBuffers::from_raw_buffers(outs, frames_count),
            )
        }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn from_plugin_audio(
        audio: clack_plugin::prelude::Audio,
    ) -> (InputAudioBuffers, OutputAudioBuffers) {
        let frames_count = audio.frames_count();
        let (ins, outs) = audio.to_raw_buffers();

        // SAFETY: the validity of the buffers is guaranteed by the Audio type
        unsafe {
            (
                InputAudioBuffers::from_raw_buffers(ins, frames_count),
                OutputAudioBuffers::from_raw_buffers(outs, frames_count),
            )
        }
    }

    pub fn with_capacity(total_channel_count: usize, port_count: usize) -> Self {
        let mut bufs = Self {
            buffer_configs: Vec::with_capacity(port_count),
            buffer_lists: Vec::with_capacity(total_channel_count),
        };
        bufs.resize_buffer_configs(port_count);

        bufs
    }

    #[inline]
    pub fn port_capacity(&self) -> usize {
        self.buffer_configs.len()
    }

    fn resize_buffer_configs(&mut self, new_size: usize) {
        if new_size > self.buffer_configs.len() {
            self.buffer_configs.resize(
                new_size,
                clap_audio_buffer {
                    data32: core::ptr::null_mut(),
                    data64: core::ptr::null_mut(),
                    channel_count: 0,
                    latency: 0,
                    constant_mask: 0,
                },
            );
        }
    }

    pub fn with_input_buffers<'a, I, Iter, ChannelIter32, ChannelIter64>(
        &'a mut self,
        iter: I,
    ) -> InputAudioBuffers<'a>
    where
        I: IntoIterator<Item = AudioPortBuffer<ChannelIter32, ChannelIter64>, IntoIter = Iter>,
        Iter: ExactSizeIterator<Item = AudioPortBuffer<ChannelIter32, ChannelIter64>>,
        ChannelIter32: IntoIterator<Item = InputChannel<'a, f32>>,
        ChannelIter64: IntoIterator<Item = InputChannel<'a, f64>>,
    {
        let iter = iter.into_iter();
        self.resize_buffer_configs(iter.len());
        self.buffer_lists.clear();

        let mut min_channel_buffer_length = u32::MAX;
        let mut total = 0;
        let mut has_reallocated = false;

        for (i, port) in iter.enumerate() {
            total = i + 1;

            let last = self.buffer_lists.len();

            let mut constant_mask = 0u64;
            let is_f64 = match port.channels {
                AudioPortBufferType::F32(channels) => {
                    for channel in channels {
                        min_channel_buffer_length = min_channel_buffer_length
                            .min(saturate_usize_to_clap_size(channel.buffer.len()));
                        if channel.is_constant {
                            constant_mask |= 1 << i as u64
                        }

                        check_collection_clap_size_overflow(&self.buffer_lists);

                        if self.buffer_lists.len() >= self.buffer_lists.capacity() {
                            has_reallocated = true;
                        }

                        self.buffer_lists.push(channel.buffer.as_mut_ptr().cast())
                    }
                    false
                }
                AudioPortBufferType::F64(channels) => {
                    for channel in channels {
                        min_channel_buffer_length = min_channel_buffer_length
                            .min(saturate_usize_to_clap_size(channel.buffer.len()));
                        if channel.is_constant {
                            constant_mask |= 1 << i as u64
                        }

                        check_collection_clap_size_overflow(&self.buffer_lists);

                        if self.buffer_lists.len() >= self.buffer_lists.capacity() {
                            has_reallocated = true;
                        }

                        self.buffer_lists.push(channel.buffer.as_mut_ptr().cast())
                    }
                    true
                }
            };

            let buffers = self.buffer_lists.get_mut(last..).unwrap_or(&mut []);

            // PANIC: this can only panic with an invalid implementation of ExactSizeIterator
            let descriptor = &mut self.buffer_configs[i];
            #[allow(clippy::cast_possible_truncation)]
            // We already checked above that it cannot be overflowed
            {
                descriptor.channel_count = buffers.len() as u32;
            }
            descriptor.latency = port.latency;
            descriptor.constant_mask = constant_mask;

            if is_f64 {
                descriptor.data64 = buffers.as_mut_ptr().cast();
                descriptor.data32 = core::ptr::null_mut();
            } else {
                descriptor.data64 = core::ptr::null_mut();
                descriptor.data32 = buffers.as_mut_ptr();
            }
        }

        // If a realloc occurred, we must rewrite all the pointers.
        // Thankfully, we know we wrote them sequentially, and we stored the lengths, so it's easy
        // to find them back.
        if has_reallocated {
            let mut last_len = 0;
            for descriptor in &mut self.buffer_configs[..total] {
                let channel_count = descriptor.channel_count as usize;
                let buffers = self
                    .buffer_lists
                    .get_mut(last_len..channel_count)
                    .unwrap_or(&mut []);
                last_len += channel_count;

                if descriptor.data32.is_null() {
                    descriptor.data64 = buffers.as_mut_ptr().cast();
                } else {
                    descriptor.data32 = buffers.as_mut_ptr();
                }
            }
        }

        InputAudioBuffers {
            buffers: &self.buffer_configs[..total],
            frames_count: if min_channel_buffer_length == u32::MAX {
                None
            } else {
                Some(min_channel_buffer_length)
            },
        }
    }

    pub fn with_output_buffers<'a, I, Iter, ChannelIter32, ChannelIter64>(
        &'a mut self,
        iter: I,
    ) -> OutputAudioBuffers<'a>
    where
        I: IntoIterator<Item = AudioPortBuffer<ChannelIter32, ChannelIter64>, IntoIter = Iter>,
        Iter: ExactSizeIterator<Item = AudioPortBuffer<ChannelIter32, ChannelIter64>>,
        ChannelIter32: IntoIterator<Item = &'a mut [f32]>,
        ChannelIter64: IntoIterator<Item = &'a mut [f64]>,
    {
        let iter = iter.into_iter();
        self.resize_buffer_configs(iter.len());
        self.buffer_lists.clear();

        let mut min_channel_buffer_length = u32::MAX;
        let mut total = 0;
        let mut has_reallocated = false;

        for (i, port) in iter.enumerate() {
            total = i + 1;

            let last = self.buffer_lists.len();

            let is_f64 = match port.channels {
                AudioPortBufferType::F32(channels) => {
                    for channel in channels {
                        min_channel_buffer_length = min_channel_buffer_length
                            .min(saturate_usize_to_clap_size(channel.len()));

                        check_collection_clap_size_overflow(&self.buffer_lists);

                        if self.buffer_lists.len() >= self.buffer_lists.capacity() {
                            has_reallocated = true;
                        }

                        self.buffer_lists.push(channel.as_mut_ptr().cast())
                    }
                    false
                }
                AudioPortBufferType::F64(channels) => {
                    for channel in channels {
                        min_channel_buffer_length = min_channel_buffer_length
                            .min(saturate_usize_to_clap_size(channel.len()));

                        check_collection_clap_size_overflow(&self.buffer_lists);

                        if self.buffer_lists.len() >= self.buffer_lists.capacity() {
                            has_reallocated = true;
                        }

                        self.buffer_lists.push(channel.as_mut_ptr().cast())
                    }
                    true
                }
            };

            let buffers = self.buffer_lists.get_mut(last..).unwrap_or(&mut []);

            // PANIC: this can only panic with an invalid implementation of ExactSizeIterator
            let descriptor = &mut self.buffer_configs[i];
            #[allow(clippy::cast_possible_truncation)]
            // We already checked above that it cannot be overflowed
            {
                descriptor.channel_count = buffers.len() as u32;
            }
            descriptor.latency = port.latency;
            descriptor.constant_mask = 0;

            if is_f64 {
                descriptor.data64 = buffers.as_mut_ptr().cast();
                descriptor.data32 = core::ptr::null_mut();
            } else {
                descriptor.data64 = core::ptr::null_mut();
                descriptor.data32 = buffers.as_mut_ptr();
            }
        }

        // If a realloc occurred, we must rewrite all the pointers.
        // Thankfully, we know we wrote them sequentially, and we stored the lengths, so it's easy
        // to find them back.
        if has_reallocated {
            let mut last_len = 0;
            for descriptor in &mut self.buffer_configs[..total] {
                let channel_count = descriptor.channel_count as usize;
                let buffers = self
                    .buffer_lists
                    .get_mut(last_len..channel_count)
                    .unwrap_or(&mut []);
                last_len += channel_count;

                if descriptor.data32.is_null() {
                    descriptor.data64 = buffers.as_mut_ptr().cast();
                } else {
                    descriptor.data32 = buffers.as_mut_ptr();
                }
            }
        }

        OutputAudioBuffers {
            buffers: &mut self.buffer_configs[..total],
            frames_count: if min_channel_buffer_length == u32::MAX {
                None
            } else {
                Some(min_channel_buffer_length)
            },
        }
    }

    #[inline]
    pub fn port_count(&self) -> usize {
        self.buffer_configs.len()
    }
}

#[inline]
const fn saturate_usize_to_clap_size(value: usize) -> u32 {
    if value > u32::MAX as usize {
        u32::MAX - 1
    } else {
        #[allow(clippy::cast_possible_truncation)] // We just checked it above, it cannot overflow
        {
            value as u32
        }
    }
}

pub struct InputAudioBuffers<'a> {
    buffers: &'a [clap_audio_buffer],
    frames_count: Option<u32>,
}

impl<'a> InputAudioBuffers<'a> {
    #[inline]
    pub const fn empty() -> Self {
        Self {
            buffers: &[],
            frames_count: None,
        }
    }

    /// Shortens the [`frames_count`] of these input buffers.
    ///
    /// This does not actually change the underlying buffers themselves, it only reduces the
    /// slice that will be exposed to the plugin.
    ///
    /// This method does nothing if `max_buffer_size` is greater or equal than the current [`frames_count`].
    ///
    /// [`frames_count`]: self.frames_count
    pub fn truncate(&mut self, max_buffer_size: u32) {
        if let Some(frames_count) = self.frames_count {
            self.frames_count = Some(frames_count.min(max_buffer_size))
        }
    }

    /// # 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`.
    #[inline]
    pub unsafe fn from_raw_buffers(buffers: &'a [clap_audio_buffer], frames_count: u32) -> Self {
        check_collection_clap_size_overflow(buffers);

        Self {
            buffers,
            frames_count: Some(frames_count),
        }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn from_plugin_audio(audio: &clack_plugin::prelude::Audio<'a>) -> InputAudioBuffers<'a> {
        let frames_count = audio.frames_count();
        let ins = audio.raw_input_buffers();

        // SAFETY: the validity of the buffers is guaranteed by the Audio type
        unsafe { InputAudioBuffers::from_raw_buffers(ins, frames_count) }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn as_plugin_audio(&self) -> clack_plugin::prelude::Audio<'a> {
        // SAFETY: the validity of the buffers is guaranteed by this type
        unsafe {
            clack_plugin::prelude::Audio::from_raw_buffers(
                self.buffers,
                &mut [],
                self.frames_count.unwrap_or(0),
            )
        }
    }

    #[inline]
    pub fn as_raw_buffers(&self) -> &'a [clap_audio_buffer] {
        self.buffers
    }

    /// The number of port buffers this [`InputAudioBuffers`] has been given.
    #[inline]
    pub fn port_count(&self) -> u32 {
        #[allow(clippy::cast_possible_truncation)]
        // We checked above that buffers' len cannot overflow u32
        {
            self.buffers.len() as u32
        }
    }

    /// The number of frames in these input buffers.
    ///
    /// This is the minimum frame count of all the port buffers this has been given.
    ///
    /// If this has no port buffer (i.e. [`port_count`](self.port_count) is zero), this returns `None`.
    #[inline]
    pub fn frames_count(&self) -> Option<u32> {
        self.frames_count
    }

    #[inline]
    pub fn port_info(&self, port_index: u32) -> Option<AudioPortProcessingInfo> {
        self.buffers
            .get(port_index as usize)
            .map(AudioPortProcessingInfo::from_raw)
    }

    #[inline]
    pub fn port_infos(&self) -> impl Iterator<Item = AudioPortProcessingInfo> + '_ {
        self.buffers.iter().map(AudioPortProcessingInfo::from_raw)
    }

    /// Returns the minimum number of frames available both in this [`InputAudioBuffers`] and
    /// the given [`OutputAudioBuffers`].
    ///
    /// This is useful to ensure a safe frame count for a `process` batch that would receive those
    /// input and output audio buffers.
    pub fn min_available_frames_with(&self, outputs: &OutputAudioBuffers) -> u32 {
        match (self.frames_count, outputs.frames_count) {
            (Some(a), Some(b)) => a.min(b),
            (Some(a), None) | (None, Some(a)) => a,
            (None, None) => 0,
        }
    }
}

pub struct OutputAudioBuffers<'a> {
    buffers: &'a mut [clap_audio_buffer],
    frames_count: Option<u32>,
}

impl<'a> OutputAudioBuffers<'a> {
    #[inline]
    pub fn empty() -> Self {
        Self {
            buffers: &mut [],
            frames_count: None,
        }
    }

    /// Shortens the [`frames_count`] of these output buffers.
    ///
    /// This does not actually change the underlying buffers themselves, it only reduces the
    /// slice that will be exposed to the plugin.
    ///
    /// This method does nothing if `max_buffer_size` is greater or equal than the current [`frames_count`].
    ///
    /// [`frames_count`]: self.frames_count
    pub fn truncate(&mut self, max_buffer_size: u32) {
        if let Some(frames_count) = self.frames_count {
            self.frames_count = Some(frames_count.min(max_buffer_size))
        }
    }

    /// # 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`.
    #[inline]
    pub unsafe fn from_raw_buffers(
        buffers: &'a mut [clap_audio_buffer],
        frames_count: u32,
    ) -> Self {
        check_collection_clap_size_overflow(buffers);

        Self {
            buffers,
            frames_count: Some(frames_count),
        }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn from_plugin_audio(audio: clack_plugin::prelude::Audio<'a>) -> OutputAudioBuffers<'a> {
        let frames_count = audio.frames_count();
        let outs = audio.to_raw_output_buffers();

        // SAFETY: the validity of the buffers is guaranteed by the Audio type
        unsafe { OutputAudioBuffers::from_raw_buffers(outs, frames_count) }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn from_plugin_audio_mut(
        audio: &'a mut clack_plugin::prelude::Audio,
    ) -> OutputAudioBuffers<'a> {
        let frames_count = audio.frames_count();
        let outs = audio.raw_output_buffers();

        // SAFETY: the validity of the buffers is guaranteed by the Audio type
        unsafe { OutputAudioBuffers::from_raw_buffers(outs, frames_count) }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn as_plugin_audio(&'a mut self) -> clack_plugin::prelude::Audio<'a> {
        // SAFETY: the validity of the buffers is guaranteed by this type
        unsafe {
            clack_plugin::prelude::Audio::from_raw_buffers(
                &[],
                self.buffers,
                self.frames_count.unwrap_or(0),
            )
        }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn to_plugin_audio(self) -> clack_plugin::prelude::Audio<'a> {
        // SAFETY: the validity of the buffers is guaranteed by this type
        unsafe {
            clack_plugin::prelude::Audio::from_raw_buffers(
                &[],
                self.buffers,
                self.frames_count.unwrap_or(0),
            )
        }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn as_plugin_audio_with_inputs(
        &'a mut self,
        inputs: &InputAudioBuffers<'a>,
    ) -> clack_plugin::prelude::Audio<'a> {
        let frames_count = inputs.min_available_frames_with(self);

        // SAFETY: the validity of the buffers is guaranteed by this type
        unsafe {
            clack_plugin::prelude::Audio::from_raw_buffers(
                inputs.buffers,
                self.buffers,
                frames_count,
            )
        }
    }

    #[cfg(feature = "clack-plugin")]
    pub fn to_plugin_audio_with_inputs(
        self,
        inputs: &InputAudioBuffers<'a>,
    ) -> clack_plugin::prelude::Audio<'a> {
        let frames_count = inputs.min_available_frames_with(&self);

        // SAFETY: the validity of the buffers is guaranteed by this type
        unsafe {
            clack_plugin::prelude::Audio::from_raw_buffers(
                inputs.buffers,
                self.buffers,
                frames_count,
            )
        }
    }

    #[inline]
    pub fn as_raw_buffers(&mut self) -> &mut [clap_audio_buffer] {
        self.buffers
    }

    #[inline]
    pub fn into_raw_buffers(self) -> &'a mut [clap_audio_buffer] {
        self.buffers
    }

    /// The number of port buffers this [`OutputAudioBuffers`] has been given.
    #[inline]
    pub fn port_count(&self) -> u32 {
        #[allow(clippy::cast_possible_truncation)]
        // We checked above that buffers' len cannot overflow u32
        {
            self.buffers.len() as u32
        }
    }

    /// The number of frames in these output buffers.
    ///
    /// This is the minimum frame count of all the port buffers this has been given.
    ///
    /// If this has no port buffer (i.e. [`port_count`](self.port_count) is zero), this returns `None`.
    #[inline]
    pub fn frames_count(&self) -> Option<u32> {
        self.frames_count
    }

    #[inline]
    pub fn port_info(&self, port_index: u32) -> Option<AudioPortProcessingInfo> {
        self.buffers
            .get(port_index as usize)
            .map(AudioPortProcessingInfo::from_raw)
    }

    #[inline]
    pub fn port_infos(&self) -> impl Iterator<Item = AudioPortProcessingInfo> + '_ {
        self.buffers.iter().map(AudioPortProcessingInfo::from_raw)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use clack_plugin::prelude::*;
    use clap_sys::process::clap_process;
    use std::cell::RefCell;
    use std::ptr::null_mut;

    #[test]
    pub fn input_audio_buffers_work() {
        let mut ports = AudioPorts::with_capacity(2, 1);
        let mut bufs = [[0f32; 4]; 2];

        let buffers = ports.with_input_buffers([AudioPortBuffer {
            latency: 0,
            channels: AudioPortBufferType::f32_input_only(bufs.iter_mut().map(|b| InputChannel {
                buffer: b.as_mut_slice(),
                is_constant: false,
            })),
        }]);

        assert_eq!(buffers.buffers.len(), 1);
        assert_eq!(buffers.frames_count, Some(4));
    }

    #[test]
    pub fn output_audio_buffers_work() {
        let mut ports = AudioPorts::with_capacity(2, 1);
        let mut bufs = [[0f32; 4]; 2];

        let buffers = ports.with_output_buffers([AudioPortBuffer {
            latency: 0,
            channels: AudioPortBufferType::f32_output_only(
                bufs.iter_mut().map(|b| b.as_mut_slice()),
            ),
        }]);

        assert_eq!(buffers.buffers.len(), 1);
        assert_eq!(buffers.frames_count, Some(4));

        assert_eq!(bufs.len(), 2); // Check borrow still works
        assert_eq!(ports.port_count(), 1);
    }

    #[test]
    pub fn input_audio_buffers_work_with_refcell() {
        let mut ports = AudioPorts::with_capacity(2, 1);
        let bufs = [RefCell::new([0f32; 4]), RefCell::new([0f32; 4])];
        let mut borrowed: Vec<_> = bufs.iter().map(|c| c.borrow_mut()).collect();

        let buffers = ports.with_input_buffers([AudioPortBuffer {
            latency: 0,
            channels: AudioPortBufferType::f32_input_only(borrowed.iter_mut().map(|b| {
                InputChannel {
                    buffer: b.as_mut_slice(),
                    is_constant: false,
                }
            })),
        }]);

        assert_eq!(buffers.buffers.len(), 1);
        assert_eq!(buffers.frames_count, Some(4));
    }

    #[test]
    pub fn output_audio_buffers_work_with_refcell() {
        let mut ports = AudioPorts::with_capacity(2, 1);
        let bufs = [RefCell::new([0f32; 4]), RefCell::new([0f32; 4])];
        let mut borrowed: Vec<_> = bufs.iter().map(|c| c.borrow_mut()).collect();

        let buffers = ports.with_output_buffers([AudioPortBuffer {
            latency: 0,
            channels: AudioPortBufferType::f32_output_only(
                borrowed.iter_mut().map(|b| b.as_mut_slice()),
            ),
        }]);

        assert_eq!(buffers.buffers.len(), 1);
        assert_eq!(buffers.frames_count, Some(4));

        assert_eq!(bufs.len(), 2); // Check borrow still works
        assert_eq!(ports.port_count(), 1);
    }

    #[test]
    pub fn audio_buffers_work_with_wrong_capacity() {
        let mut input_ports = AudioPorts::with_capacity(1, 1);
        let mut output_ports = AudioPorts::with_capacity(1, 1);
        let mut input_bufs = [[[42f32; 4]; 128], [[69f32; 4]; 128]];
        let mut output_bufs = [[[42f32; 4]; 128], [[69f32; 4]; 128]];

        let input_buffers =
            input_ports.with_input_buffers(input_bufs.iter_mut().map(|bufs| AudioPortBuffer {
                latency: 0,
                channels: AudioPortBufferType::f32_input_only(bufs.iter_mut().map(|b| {
                    InputChannel {
                        buffer: b.as_mut_slice(),
                        is_constant: false,
                    }
                })),
            }));

        let mut output_buffers =
            output_ports.with_output_buffers(output_bufs.iter_mut().map(|bufs| AudioPortBuffer {
                latency: 0,
                channels: AudioPortBufferType::f32_output_only(
                    bufs.iter_mut().map(|b| b.as_mut_slice()),
                ),
            }));

        assert_eq!(input_buffers.buffers.len(), 2);
        assert_eq!(input_buffers.frames_count, Some(4));
        assert_eq!(output_buffers.buffers.len(), 2);
        assert_eq!(output_buffers.frames_count, Some(4));

        let raw_input_buffers = input_buffers.as_raw_buffers();
        let raw_output_buffers = output_buffers.as_raw_buffers();
        let process = clap_process {
            audio_inputs: raw_input_buffers.as_ptr(),
            audio_outputs: raw_output_buffers.as_ptr() as *mut _,
            audio_inputs_count: input_buffers.port_count(),
            audio_outputs_count: output_buffers.port_count(),

            steady_time: 0,
            frames_count: 4,
            transport: null_mut(),
            in_events: null_mut(),
            out_events: null_mut(),
        };

        // SAFETY: we built the process struct above, it should be good.
        let mut audio = unsafe { Audio::from_raw(&process) };

        for (port, bufs) in audio.input_ports().zip(&input_bufs) {
            let channels = port.channels().unwrap().into_f32().unwrap();

            assert_eq!(channels.channel_count(), 128);
            for (channel, buf) in channels.iter().zip(bufs.iter()) {
                assert_eq!(buf, channel)
            }
        }

        for (mut port, bufs) in audio.output_ports().zip(&output_bufs) {
            let channels = port.channels().unwrap().into_f32().unwrap();

            assert_eq!(channels.channel_count(), 128);
            for (channel, buf) in channels.iter().zip(bufs.iter()) {
                assert_eq!(buf, channel)
            }
        }
    }
}