|
| 1 | +//! cpal integration for zero-copy audio playback |
| 2 | +//! |
| 3 | +//! This module provides adapters to use captured audio with the cpal audio library. |
| 4 | +//! |
| 5 | +//! # Example |
| 6 | +//! |
| 7 | +//! ```ignore |
| 8 | +//! use screencapturekit::cpal_adapter::{AudioSamples, CpalAudioExt}; |
| 9 | +//! use screencapturekit::cm::CMSampleBuffer; |
| 10 | +//! |
| 11 | +//! fn process_audio(sample: &CMSampleBuffer) { |
| 12 | +//! // Get f32 samples from the captured audio |
| 13 | +//! if let Some(samples) = sample.audio_f32_samples() { |
| 14 | +//! for sample in samples.iter() { |
| 15 | +//! // Process or send to cpal output stream |
| 16 | +//! } |
| 17 | +//! } |
| 18 | +//! } |
| 19 | +//! ``` |
| 20 | +
|
| 21 | +use crate::cm::{AudioBufferList, CMSampleBuffer}; |
| 22 | + |
| 23 | +/// Audio samples extracted from a `CMSampleBuffer` |
| 24 | +/// |
| 25 | +/// Owns the underlying `AudioBufferList` and provides access to samples |
| 26 | +/// in various formats compatible with cpal. |
| 27 | +pub struct AudioSamples { |
| 28 | + buffer_list: AudioBufferList, |
| 29 | +} |
| 30 | + |
| 31 | +impl AudioSamples { |
| 32 | + /// Create from a `CMSampleBuffer` |
| 33 | + /// |
| 34 | + /// Returns `None` if the sample buffer doesn't contain audio data. |
| 35 | + pub fn new(sample: &CMSampleBuffer) -> Option<Self> { |
| 36 | + let buffer_list = sample.audio_buffer_list()?; |
| 37 | + Some(Self { buffer_list }) |
| 38 | + } |
| 39 | + |
| 40 | + /// Get the number of audio channels |
| 41 | + pub fn channels(&self) -> usize { |
| 42 | + self.buffer_list |
| 43 | + .get(0) |
| 44 | + .map(|b| b.number_channels as usize) |
| 45 | + .unwrap_or(0) |
| 46 | + } |
| 47 | + |
| 48 | + /// Get raw bytes of audio data |
| 49 | + pub fn as_bytes(&self) -> &[u8] { |
| 50 | + self.buffer_list.get(0).map(|b| b.data()).unwrap_or(&[]) |
| 51 | + } |
| 52 | + |
| 53 | + /// Get audio samples as f32 slice (zero-copy if data is already f32) |
| 54 | + /// |
| 55 | + /// # Safety |
| 56 | + /// Assumes the audio data is in native-endian f32 format. |
| 57 | + #[allow(clippy::cast_ptr_alignment)] |
| 58 | + pub fn as_f32_slice(&self) -> &[f32] { |
| 59 | + let bytes = self.as_bytes(); |
| 60 | + if bytes.len() < 4 { |
| 61 | + return &[]; |
| 62 | + } |
| 63 | + // Safety: macOS audio buffers are properly aligned for the sample type |
| 64 | + unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::<f32>(), bytes.len() / 4) } |
| 65 | + } |
| 66 | + |
| 67 | + /// Get audio samples as i16 slice (zero-copy if data is already i16) |
| 68 | + /// |
| 69 | + /// # Safety |
| 70 | + /// Assumes the audio data is in native-endian i16 format. |
| 71 | + #[allow(clippy::cast_ptr_alignment)] |
| 72 | + pub fn as_i16_slice(&self) -> &[i16] { |
| 73 | + let bytes = self.as_bytes(); |
| 74 | + if bytes.len() < 2 { |
| 75 | + return &[]; |
| 76 | + } |
| 77 | + // Safety: macOS audio buffers are properly aligned for the sample type |
| 78 | + unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::<i16>(), bytes.len() / 2) } |
| 79 | + } |
| 80 | + |
| 81 | + /// Iterator over f32 samples |
| 82 | + pub fn iter_f32(&self) -> impl Iterator<Item = f32> + '_ { |
| 83 | + self.as_f32_slice().iter().copied() |
| 84 | + } |
| 85 | + |
| 86 | + /// Iterator over i16 samples |
| 87 | + pub fn iter_i16(&self) -> impl Iterator<Item = i16> + '_ { |
| 88 | + self.as_i16_slice().iter().copied() |
| 89 | + } |
| 90 | + |
| 91 | + /// Get the number of f32 samples |
| 92 | + pub fn len_f32(&self) -> usize { |
| 93 | + self.as_bytes().len() / 4 |
| 94 | + } |
| 95 | + |
| 96 | + /// Get the number of i16 samples |
| 97 | + pub fn len_i16(&self) -> usize { |
| 98 | + self.as_bytes().len() / 2 |
| 99 | + } |
| 100 | + |
| 101 | + /// Check if empty |
| 102 | + pub fn is_empty(&self) -> bool { |
| 103 | + self.as_bytes().is_empty() |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/// Extension trait for `CMSampleBuffer` to provide cpal-compatible audio access |
| 108 | +pub trait CpalAudioExt { |
| 109 | + /// Get audio samples as f32 (for cpal output) |
| 110 | + fn audio_f32_samples(&self) -> Option<AudioSamples>; |
| 111 | + |
| 112 | + /// Copy f32 audio samples into a cpal-compatible buffer |
| 113 | + /// |
| 114 | + /// Returns the number of samples copied. |
| 115 | + fn copy_f32_to_buffer(&self, buffer: &mut [f32]) -> usize; |
| 116 | + |
| 117 | + /// Copy i16 audio samples into a cpal-compatible buffer |
| 118 | + /// |
| 119 | + /// Returns the number of samples copied. |
| 120 | + fn copy_i16_to_buffer(&self, buffer: &mut [i16]) -> usize; |
| 121 | +} |
| 122 | + |
| 123 | +impl CpalAudioExt for CMSampleBuffer { |
| 124 | + fn audio_f32_samples(&self) -> Option<AudioSamples> { |
| 125 | + AudioSamples::new(self) |
| 126 | + } |
| 127 | + |
| 128 | + fn copy_f32_to_buffer(&self, buffer: &mut [f32]) -> usize { |
| 129 | + let Some(samples) = AudioSamples::new(self) else { |
| 130 | + return 0; |
| 131 | + }; |
| 132 | + let src = samples.as_f32_slice(); |
| 133 | + let len = buffer.len().min(src.len()); |
| 134 | + buffer[..len].copy_from_slice(&src[..len]); |
| 135 | + len |
| 136 | + } |
| 137 | + |
| 138 | + fn copy_i16_to_buffer(&self, buffer: &mut [i16]) -> usize { |
| 139 | + let Some(samples) = AudioSamples::new(self) else { |
| 140 | + return 0; |
| 141 | + }; |
| 142 | + let src = samples.as_i16_slice(); |
| 143 | + let len = buffer.len().min(src.len()); |
| 144 | + buffer[..len].copy_from_slice(&src[..len]); |
| 145 | + len |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +/// Audio format information for cpal stream configuration |
| 150 | +#[derive(Debug, Clone, Copy)] |
| 151 | +pub struct AudioFormat { |
| 152 | + /// Sample rate in Hz |
| 153 | + pub sample_rate: u32, |
| 154 | + /// Number of channels |
| 155 | + pub channels: u16, |
| 156 | + /// Bits per sample |
| 157 | + pub bits_per_sample: u16, |
| 158 | + /// Whether samples are float format |
| 159 | + pub is_float: bool, |
| 160 | +} |
| 161 | + |
| 162 | +impl AudioFormat { |
| 163 | + /// Extract audio format from a `CMSampleBuffer` |
| 164 | + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] |
| 165 | + pub fn from_sample_buffer(sample: &CMSampleBuffer) -> Option<Self> { |
| 166 | + let format_desc = sample.format_description()?; |
| 167 | + if !format_desc.is_audio() { |
| 168 | + return None; |
| 169 | + } |
| 170 | + |
| 171 | + Some(Self { |
| 172 | + sample_rate: format_desc.audio_sample_rate()? as u32, |
| 173 | + channels: format_desc.audio_channel_count()? as u16, |
| 174 | + bits_per_sample: format_desc.audio_bits_per_channel()? as u16, |
| 175 | + is_float: format_desc.audio_is_float(), |
| 176 | + }) |
| 177 | + } |
| 178 | + |
| 179 | + /// Convert to cpal `StreamConfig` |
| 180 | + pub fn to_stream_config(&self) -> cpal::StreamConfig { |
| 181 | + cpal::StreamConfig { |
| 182 | + channels: self.channels, |
| 183 | + sample_rate: cpal::SampleRate(self.sample_rate), |
| 184 | + buffer_size: cpal::BufferSize::Default, |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + /// Get the cpal `SampleFormat` based on the audio format |
| 189 | + pub fn sample_format(&self) -> cpal::SampleFormat { |
| 190 | + if self.is_float { |
| 191 | + cpal::SampleFormat::F32 |
| 192 | + } else if self.bits_per_sample == 8 { |
| 193 | + cpal::SampleFormat::I8 |
| 194 | + } else if self.bits_per_sample == 32 { |
| 195 | + cpal::SampleFormat::I32 |
| 196 | + } else { |
| 197 | + cpal::SampleFormat::I16 |
| 198 | + } |
| 199 | + } |
| 200 | +} |
0 commit comments