Debian Codegraph @

third_party/rust/cubeb-coreaudio/src/backend/buffer_manager.rs

raw
1 use std::cmp::Ordering;
2 use std::fmt;
3 use std::os::raw::c_void;
4 use std::slice;
5
6 use cubeb_backend::SampleFormat;
7
8 use super::ringbuf::RingBuffer;
9
10 use self::LinearBuffer::*;
11 use self::RingBufferConsumer::*;
12 use self::RingBufferProducer::*;
13
14 // Shuffles the data so that the first n channels of the interleaved buffer are overwritten by
15 // the remaining channels.
16 fn drop_first_n_channels_in_place<T: Copy>(
17 n: usize,
18 data: &mut [T],
19 frame_count: usize,
20 channel_count: usize,
21 ) {
22 // This function works if the numbers are equal but it's not particularly useful, so we hope to
23 // catch issues by checking using > and not >= here.
24 assert!(channel_count > n);
25 let mut read_idx: usize = 0;
26 let mut write_idx: usize = 0;
27
28 let channel_to_keep = channel_count - n;
29 for _ in 0..frame_count {
30 read_idx += n;
31 for _ in 0..channel_to_keep {
32 data[write_idx] = data[read_idx];
33 read_idx += 1;
34 write_idx += 1;
35 }
36 }
37 }
38
39 // It can be that the a stereo microphone is in use, but the user asked for mono input. In this
40 // particular case, downmix the stereo pair into a mono channel. In all other cases, simply drop
41 // the remaining channels before appending to the ringbuffer, becauses there is no right or wrong
42 // way to do this, unlike with the output side, where proper channel matrixing can be done.
43 // Return the number of valid samples in the buffer.
44 fn remix_or_drop_channels<T: Copy + std::ops::Add<Output = T>>(
45 input_channels: usize,
46 output_channels: usize,
47 data: &mut [T],
48 frame_count: usize,
49 ) -> usize {
50 assert!(input_channels >= output_channels);
51 // Nothing to do, just return
52 if input_channels == output_channels {
53 return output_channels * frame_count;
54 }
55 // Simple stereo downmix
56 if input_channels == 2 && output_channels == 1 {
57 let mut read_idx = 0;
58 for (write_idx, _) in (0..frame_count).enumerate() {
59 data[write_idx] = data[read_idx] + data[read_idx + 1];
60 read_idx += 2;
61 }
62 return output_channels * frame_count;
63 }
64 // Drop excess channels
65 let mut read_idx = 0;
66 let mut write_idx = 0;
67 let channel_dropped_count = input_channels - output_channels;
68 for _ in 0..frame_count {
69 for _ in 0..output_channels {
70 data[write_idx] = data[read_idx];
71 write_idx += 1;
72 read_idx += 1;
73 }
74 read_idx += channel_dropped_count;
75 }
76 output_channels * frame_count
77 }
78
79 fn process_data<T: Copy + std::ops::Add<Output = T>>(
80 data: *mut c_void,
81 frame_count: usize,
82 input_channel_count: usize,
83 input_channels_to_ignore: usize,
84 output_channel_count: usize,
85 ) -> &'static [T] {
86 assert!(
87 input_channels_to_ignore == 0
88 || input_channel_count >= input_channels_to_ignore + output_channel_count
89 );
90 let input_slice = unsafe {
91 slice::from_raw_parts_mut::<T>(data as *mut T, frame_count * input_channel_count)
92 };
93 match input_channel_count.cmp(&output_channel_count) {
94 Ordering::Equal => {
95 assert_eq!(input_channels_to_ignore, 0);
96 input_slice
97 }
98 Ordering::Greater => {
99 if input_channels_to_ignore > 0 {
100 drop_first_n_channels_in_place(
101 input_channels_to_ignore,
102 input_slice,
103 frame_count,
104 input_channel_count,
105 );
106 }
107 let new_count_remixed = remix_or_drop_channels(
108 input_channel_count - input_channels_to_ignore,
109 output_channel_count,
110 input_slice,
111 frame_count,
112 );
113 unsafe { slice::from_raw_parts_mut::<T>(data as *mut T, new_count_remixed) }
114 }
115 Ordering::Less => {
116 assert!(input_channel_count < output_channel_count);
117 // Upmix happens on pull.
118 input_slice
119 }
120 }
121 }
122
123 pub enum RingBufferConsumer {
124 IntegerRingBufferConsumer(ringbuf::Consumer<i16>),
125 FloatRingBufferConsumer(ringbuf::Consumer<f32>),
126 }
127
128 pub enum RingBufferProducer {
129 IntegerRingBufferProducer(ringbuf::Producer<i16>),
130 FloatRingBufferProducer(ringbuf::Producer<f32>),
131 }
132
133 pub enum LinearBuffer {
134 IntegerLinearBuffer(Vec<i16>),
135 FloatLinearBuffer(Vec<f32>),
136 }
137
138 pub struct BufferManager {
139 consumer: RingBufferConsumer,
140 producer: RingBufferProducer,
141 linear_buffer: LinearBuffer,
142 // The number of channels in the interleaved data given to push_data
143 input_channel_count: usize,
144 // The number of channels that needs to be skipped in the beginning of input_channel_count
145 input_channels_to_ignore: usize,
146 // The number of channels we actually needs, which is also the channel count of the
147 // processed data stored in the internal ring buffer.
148 output_channel_count: usize,
149 }
150
151 impl BufferManager {
152 pub fn new(
153 format: SampleFormat,
154 buffer_size_frames: usize,
155 input_channel_count: usize,
156 input_channels_to_ignore: usize,
157 output_channel_count: usize,
158 ) -> Self {
159 assert!(
160 (input_channels_to_ignore == 0 && input_channel_count == 1)
161 || input_channel_count >= input_channels_to_ignore + output_channel_count
162 );
163 // 8 times the expected callback size, to handle the input callback being caled multiple
164 // times in a row correctly.
165 let buffer_element_count = output_channel_count * buffer_size_frames * 8;
166 match format {
167 SampleFormat::S16LE | SampleFormat::S16BE | SampleFormat::S16NE => {
168 let ring = RingBuffer::<i16>::new(buffer_element_count);
169 let (prod, cons) = ring.split();
170 Self {
171 producer: IntegerRingBufferProducer(prod),
172 consumer: IntegerRingBufferConsumer(cons),
173 linear_buffer: IntegerLinearBuffer(Vec::<i16>::with_capacity(
174 buffer_element_count,
175 )),
176 input_channel_count,
177 input_channels_to_ignore,
178 output_channel_count,
179 }
180 }
181 SampleFormat::Float32LE | SampleFormat::Float32BE | SampleFormat::Float32NE => {
182 let ring = RingBuffer::<f32>::new(buffer_element_count);
183 let (prod, cons) = ring.split();
184 Self {
185 producer: FloatRingBufferProducer(prod),
186 consumer: FloatRingBufferConsumer(cons),
187 linear_buffer: FloatLinearBuffer(Vec::<f32>::with_capacity(
188 buffer_element_count,
189 )),
190 input_channel_count,
191 input_channels_to_ignore,
192 output_channel_count,
193 }
194 }
195 }
196 }
197 fn stored_channel_count(&self) -> usize {
198 if self.output_channel_count > self.input_channel_count {
199 // This case allows upmix from mono on pull.
200 self.input_channel_count
201 } else {
202 // Other cases only downmix on push.
203 self.output_channel_count
204 }
205 }
206 fn input_channel_count(&self) -> usize {
207 self.input_channel_count
208 }
209 fn input_channels_to_ignore(&self) -> usize {
210 self.input_channels_to_ignore
211 }
212 fn output_channel_count(&self) -> usize {
213 self.output_channel_count
214 }
215 pub fn push_data(&mut self, data: *mut c_void, frame_count: usize) {
216 let to_push = frame_count * self.stored_channel_count();
217 let input_channel_count = self.input_channel_count();
218 let input_channels_to_ignore = self.input_channels_to_ignore();
219 let output_channel_count = self.output_channel_count();
220 let pushed = match &mut self.producer {
221 RingBufferProducer::FloatRingBufferProducer(p) => {
222 let processed_input = process_data(
223 data,
224 frame_count,
225 input_channel_count,
226 input_channels_to_ignore,
227 output_channel_count,
228 );
229 p.push_slice(processed_input)
230 }
231 RingBufferProducer::IntegerRingBufferProducer(p) => {
232 let processed_input = process_data(
233 data,
234 frame_count,
235 input_channel_count,
236 input_channels_to_ignore,
237 output_channel_count,
238 );
239 p.push_slice(processed_input)
240 }
241 };
242 assert!(pushed <= to_push);
243 if pushed != to_push {
244 cubeb_alog!(
245 "Input ringbuffer full, could only push {} instead of {}",
246 pushed,
247 to_push
248 );
249 }
250 }
251 fn pull_data(&mut self, data: *mut c_void, needed_samples: usize) {
252 assert_eq!(needed_samples % self.output_channel_count(), 0);
253 let needed_frames = needed_samples / self.output_channel_count();
254 let to_pull = needed_frames * self.stored_channel_count();
255 match &mut self.consumer {
256 IntegerRingBufferConsumer(p) => {
257 let input: &mut [i16] =
258 unsafe { slice::from_raw_parts_mut::<i16>(data as *mut i16, needed_samples) };
259 let pulled = p.pop_slice(input);
260 if pulled < to_pull {
261 cubeb_alog!(
262 "Underrun during input data pull: (needed: {}, available: {})",
263 to_pull,
264 pulled
265 );
266 for i in 0..(to_pull - pulled) {
267 input[pulled + i] = 0;
268 }
269 }
270 if needed_samples > to_pull {
271 // Mono upmix. This can happen with voice processing.
272 let mut write_idx = needed_samples;
273 for read_idx in (0..to_pull).rev() {
274 write_idx -= self.output_channel_count();
275 for offset in 0..self.output_channel_count() {
276 input[write_idx + offset] = input[read_idx];
277 }
278 }
279 }
280 }
281 FloatRingBufferConsumer(p) => {
282 let input: &mut [f32] =
283 unsafe { slice::from_raw_parts_mut::<f32>(data as *mut f32, needed_samples) };
284 let pulled = p.pop_slice(input);
285 if pulled < to_pull {
286 cubeb_alog!(
287 "Underrun during input data pull: (needed: {}, available: {})",
288 to_pull,
289 pulled
290 );
291 for i in 0..(to_pull - pulled) {
292 input[pulled + i] = 0.0;
293 }
294 }
295 if needed_samples > to_pull {
296 // Mono upmix. This can happen with voice processing.
297 let mut write_idx = needed_samples;
298 for read_idx in (0..to_pull).rev() {
299 write_idx -= self.output_channel_count();
300 for offset in 0..self.output_channel_count() {
301 input[write_idx + offset] = input[read_idx];
302 }
303 }
304 }
305 }
306 }
307 }
308 pub fn get_linear_data(&mut self, frame_count: usize) -> *mut c_void {
309 let output_sample_count = frame_count * self.output_channel_count();
310 let p = match &mut self.linear_buffer {
311 LinearBuffer::IntegerLinearBuffer(b) => {
312 b.resize(output_sample_count, 0);
313 b.as_mut_ptr() as *mut c_void
314 }
315 LinearBuffer::FloatLinearBuffer(b) => {
316 b.resize(output_sample_count, 0.);
317 b.as_mut_ptr() as *mut c_void
318 }
319 };
320 self.pull_data(p, output_sample_count);
321
322 p
323 }
324 pub fn available_frames(&self) -> usize {
325 assert_ne!(self.stored_channel_count(), 0);
326 let stored_samples = match &self.consumer {
327 IntegerRingBufferConsumer(p) => p.len(),
328 FloatRingBufferConsumer(p) => p.len(),
329 };
330 stored_samples / self.stored_channel_count()
331 }
332 pub fn trim(&mut self, final_frame_count: usize) {
333 let final_sample_count = final_frame_count * self.stored_channel_count();
334 match &mut self.consumer {
335 IntegerRingBufferConsumer(c) => {
336 let available = c.len();
337 assert!(available >= final_sample_count);
338 let to_pop = available - final_sample_count;
339 c.discard(to_pop);
340 }
341 FloatRingBufferConsumer(c) => {
342 let available = c.len();
343 assert!(available >= final_sample_count);
344 let to_pop = available - final_sample_count;
345 c.discard(to_pop);
346 }
347 }
348 }
349 }
350
351 impl fmt::Debug for BufferManager {
352 fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
353 Ok(())
354 }
355 }