summaryrefslogtreecommitdiffstats
path: root/third_party/rust/cubeb-coreaudio/src/backend/buffer_manager.rs
blob: 6f1c299bfb23602f4cedc61989f760b1ceeda3c0 (plain)
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
use std::cmp::Ordering;
use std::fmt;
use std::os::raw::c_void;
use std::slice;

use cubeb_backend::SampleFormat;

use super::ringbuf::RingBuffer;

use self::LinearBuffer::*;
use self::RingBufferConsumer::*;
use self::RingBufferProducer::*;

// Shuffles the data so that the first n channels of the interleaved buffer are overwritten by
// the remaining channels.
fn drop_first_n_channels_in_place<T: Copy>(
    n: usize,
    data: &mut [T],
    frame_count: usize,
    channel_count: usize,
) {
    // This function works if the numbers are equal but it's not particularly useful, so we hope to
    // catch issues by checking using > and not >= here.
    assert!(channel_count > n);
    let mut read_idx: usize = 0;
    let mut write_idx: usize = 0;

    let channel_to_keep = channel_count - n;
    for _ in 0..frame_count {
        read_idx += n;
        for _ in 0..channel_to_keep {
            data[write_idx] = data[read_idx];
            read_idx += 1;
            write_idx += 1;
        }
    }
}

// It can be that the a stereo microphone is in use, but the user asked for mono input. In this
// particular case, downmix the stereo pair into a mono channel. In all other cases, simply drop
// the remaining channels before appending to the ringbuffer, becauses there is no right or wrong
// way to do this, unlike with the output side, where proper channel matrixing can be done.
// Return the number of valid samples in the buffer.
fn remix_or_drop_channels<T: Copy + std::ops::Add<Output = T>>(
    input_channels: usize,
    output_channels: usize,
    data: &mut [T],
    frame_count: usize,
) -> usize {
    assert!(input_channels >= output_channels);
    // Nothing to do, just return
    if input_channels == output_channels {
        return output_channels * frame_count;
    }
    // Simple stereo downmix
    if input_channels == 2 && output_channels == 1 {
        let mut read_idx = 0;
        for (write_idx, _) in (0..frame_count).enumerate() {
            data[write_idx] = data[read_idx] + data[read_idx + 1];
            read_idx += 2;
        }
        return output_channels * frame_count;
    }
    // Drop excess channels
    let mut read_idx = 0;
    let mut write_idx = 0;
    let channel_dropped_count = input_channels - output_channels;
    for _ in 0..frame_count {
        for _ in 0..output_channels {
            data[write_idx] = data[read_idx];
            write_idx += 1;
            read_idx += 1;
        }
        read_idx += channel_dropped_count;
    }
    output_channels * frame_count
}

fn process_data<T: Copy + std::ops::Add<Output = T>>(
    data: *mut c_void,
    frame_count: usize,
    input_channel_count: usize,
    input_channels_to_ignore: usize,
    output_channel_count: usize,
) -> &'static [T] {
    assert!(
        input_channels_to_ignore == 0
            || input_channel_count >= input_channels_to_ignore + output_channel_count
    );
    let input_slice = unsafe {
        slice::from_raw_parts_mut::<T>(data as *mut T, frame_count * input_channel_count)
    };
    match input_channel_count.cmp(&output_channel_count) {
        Ordering::Equal => {
            assert_eq!(input_channels_to_ignore, 0);
            input_slice
        }
        Ordering::Greater => {
            if input_channels_to_ignore > 0 {
                drop_first_n_channels_in_place(
                    input_channels_to_ignore,
                    input_slice,
                    frame_count,
                    input_channel_count,
                );
            }
            let new_count_remixed = remix_or_drop_channels(
                input_channel_count - input_channels_to_ignore,
                output_channel_count,
                input_slice,
                frame_count,
            );
            unsafe { slice::from_raw_parts_mut::<T>(data as *mut T, new_count_remixed) }
        }
        Ordering::Less => {
            assert!(input_channel_count < output_channel_count);
            // Upmix happens on pull.
            input_slice
        }
    }
}

pub enum RingBufferConsumer {
    IntegerRingBufferConsumer(ringbuf::Consumer<i16>),
    FloatRingBufferConsumer(ringbuf::Consumer<f32>),
}

pub enum RingBufferProducer {
    IntegerRingBufferProducer(ringbuf::Producer<i16>),
    FloatRingBufferProducer(ringbuf::Producer<f32>),
}

pub enum LinearBuffer {
    IntegerLinearBuffer(Vec<i16>),
    FloatLinearBuffer(Vec<f32>),
}

pub struct BufferManager {
    consumer: RingBufferConsumer,
    producer: RingBufferProducer,
    linear_buffer: LinearBuffer,
    // The number of channels in the interleaved data given to push_data
    input_channel_count: usize,
    // The number of channels that needs to be skipped in the beginning of input_channel_count
    input_channels_to_ignore: usize,
    // The number of channels we actually needs, which is also the channel count of the
    // processed data stored in the internal ring buffer.
    output_channel_count: usize,
}

impl BufferManager {
    pub fn new(
        format: SampleFormat,
        buffer_size_frames: usize,
        input_channel_count: usize,
        input_channels_to_ignore: usize,
        output_channel_count: usize,
    ) -> Self {
        assert!(
            (input_channels_to_ignore == 0 && input_channel_count == 1)
                || input_channel_count >= input_channels_to_ignore + output_channel_count
        );
        // 8 times the expected callback size, to handle the input callback being caled multiple
        //   times in a row correctly.
        let buffer_element_count = output_channel_count * buffer_size_frames * 8;
        match format {
            SampleFormat::S16LE | SampleFormat::S16BE | SampleFormat::S16NE => {
                let ring = RingBuffer::<i16>::new(buffer_element_count);
                let (prod, cons) = ring.split();
                Self {
                    producer: IntegerRingBufferProducer(prod),
                    consumer: IntegerRingBufferConsumer(cons),
                    linear_buffer: IntegerLinearBuffer(Vec::<i16>::with_capacity(
                        buffer_element_count,
                    )),
                    input_channel_count,
                    input_channels_to_ignore,
                    output_channel_count,
                }
            }
            SampleFormat::Float32LE | SampleFormat::Float32BE | SampleFormat::Float32NE => {
                let ring = RingBuffer::<f32>::new(buffer_element_count);
                let (prod, cons) = ring.split();
                Self {
                    producer: FloatRingBufferProducer(prod),
                    consumer: FloatRingBufferConsumer(cons),
                    linear_buffer: FloatLinearBuffer(Vec::<f32>::with_capacity(
                        buffer_element_count,
                    )),
                    input_channel_count,
                    input_channels_to_ignore,
                    output_channel_count,
                }
            }
        }
    }
    fn stored_channel_count(&self) -> usize {
        if self.output_channel_count > self.input_channel_count {
            // This case allows upmix from mono on pull.
            self.input_channel_count
        } else {
            // Other cases only downmix on push.
            self.output_channel_count
        }
    }
    fn input_channel_count(&self) -> usize {
        self.input_channel_count
    }
    fn input_channels_to_ignore(&self) -> usize {
        self.input_channels_to_ignore
    }
    fn output_channel_count(&self) -> usize {
        self.output_channel_count
    }
    pub fn push_data(&mut self, data: *mut c_void, frame_count: usize) {
        let to_push = frame_count * self.stored_channel_count();
        let input_channel_count = self.input_channel_count();
        let input_channels_to_ignore = self.input_channels_to_ignore();
        let output_channel_count = self.output_channel_count();
        let pushed = match &mut self.producer {
            RingBufferProducer::FloatRingBufferProducer(p) => {
                let processed_input = process_data(
                    data,
                    frame_count,
                    input_channel_count,
                    input_channels_to_ignore,
                    output_channel_count,
                );
                p.push_slice(processed_input)
            }
            RingBufferProducer::IntegerRingBufferProducer(p) => {
                let processed_input = process_data(
                    data,
                    frame_count,
                    input_channel_count,
                    input_channels_to_ignore,
                    output_channel_count,
                );
                p.push_slice(processed_input)
            }
        };
        assert!(pushed <= to_push);
        if pushed != to_push {
            cubeb_alog!(
                "Input ringbuffer full, could only push {} instead of {}",
                pushed,
                to_push
            );
        }
    }
    fn pull_data(&mut self, data: *mut c_void, needed_samples: usize) {
        assert_eq!(needed_samples % self.output_channel_count(), 0);
        let needed_frames = needed_samples / self.output_channel_count();
        let to_pull = needed_frames * self.stored_channel_count();
        match &mut self.consumer {
            IntegerRingBufferConsumer(p) => {
                let input: &mut [i16] =
                    unsafe { slice::from_raw_parts_mut::<i16>(data as *mut i16, needed_samples) };
                let pulled = p.pop_slice(input);
                if pulled < to_pull {
                    cubeb_alog!(
                        "Underrun during input data pull: (needed: {}, available: {})",
                        to_pull,
                        pulled
                    );
                    for i in 0..(to_pull - pulled) {
                        input[pulled + i] = 0;
                    }
                }
                if needed_samples > to_pull {
                    // Mono upmix. This can happen with voice processing.
                    let mut write_idx = needed_samples;
                    for read_idx in (0..to_pull).rev() {
                        write_idx -= self.output_channel_count();
                        for offset in 0..self.output_channel_count() {
                            input[write_idx + offset] = input[read_idx];
                        }
                    }
                }
            }
            FloatRingBufferConsumer(p) => {
                let input: &mut [f32] =
                    unsafe { slice::from_raw_parts_mut::<f32>(data as *mut f32, needed_samples) };
                let pulled = p.pop_slice(input);
                if pulled < to_pull {
                    cubeb_alog!(
                        "Underrun during input data pull: (needed: {}, available: {})",
                        to_pull,
                        pulled
                    );
                    for i in 0..(to_pull - pulled) {
                        input[pulled + i] = 0.0;
                    }
                }
                if needed_samples > to_pull {
                    // Mono upmix. This can happen with voice processing.
                    let mut write_idx = needed_samples;
                    for read_idx in (0..to_pull).rev() {
                        write_idx -= self.output_channel_count();
                        for offset in 0..self.output_channel_count() {
                            input[write_idx + offset] = input[read_idx];
                        }
                    }
                }
            }
        }
    }
    pub fn get_linear_data(&mut self, frame_count: usize) -> *mut c_void {
        let output_sample_count = frame_count * self.output_channel_count();
        let p = match &mut self.linear_buffer {
            LinearBuffer::IntegerLinearBuffer(b) => {
                b.resize(output_sample_count, 0);
                b.as_mut_ptr() as *mut c_void
            }
            LinearBuffer::FloatLinearBuffer(b) => {
                b.resize(output_sample_count, 0.);
                b.as_mut_ptr() as *mut c_void
            }
        };
        self.pull_data(p, output_sample_count);

        p
    }
    pub fn available_frames(&self) -> usize {
        assert_ne!(self.stored_channel_count(), 0);
        let stored_samples = match &self.consumer {
            IntegerRingBufferConsumer(p) => p.len(),
            FloatRingBufferConsumer(p) => p.len(),
        };
        stored_samples / self.stored_channel_count()
    }
    pub fn trim(&mut self, final_frame_count: usize) {
        let final_sample_count = final_frame_count * self.stored_channel_count();
        match &mut self.consumer {
            IntegerRingBufferConsumer(c) => {
                let available = c.len();
                assert!(available >= final_sample_count);
                let to_pop = available - final_sample_count;
                c.discard(to_pop);
            }
            FloatRingBufferConsumer(c) => {
                let available = c.len();
                assert!(available >= final_sample_count);
                let to_pop = available - final_sample_count;
                c.discard(to_pop);
            }
        }
    }
}

impl fmt::Debug for BufferManager {
    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
        Ok(())
    }
}