summaryrefslogtreecommitdiffstats
path: root/third_party/rust/cubeb-coreaudio/src/backend/tests/parallel.rs
blob: 16063d00112b2f6275e50a6d65f7c042a2b23173 (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
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
use super::utils::{
    noop_data_callback, test_audiounit_get_buffer_frame_size, test_get_default_audiounit,
    test_get_default_device, test_ops_context_operation, PropertyScope, Scope,
};
use super::*;
use std::thread;

// Ignore the test by default to avoid overwritting the buffer frame size of the device that is
// currently used by other streams in other tests.
#[ignore]
#[test]
fn test_parallel_ops_init_streams_in_parallel_input() {
    const THREADS: u32 = 50;
    create_streams_by_ops_in_parallel_with_different_latency(
        THREADS,
        StreamType::Input,
        |streams| {
            // All the latency frames should be the same value as the first stream's one, since the
            // latency frames cannot be changed if another stream is operating in parallel.
            let mut latency_frames = vec![];
            let mut in_buffer_frame_sizes = vec![];

            for stream in streams {
                latency_frames.push(stream.latency_frames);

                assert!(!stream.core_stream_data.input_unit.is_null());
                let in_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                    stream.core_stream_data.input_unit,
                    Scope::Input,
                    PropertyScope::Output,
                )
                .unwrap();
                in_buffer_frame_sizes.push(in_buffer_frame_size);

                assert!(stream.core_stream_data.output_unit.is_null());
            }

            // Make sure all the latency frames are same as the first stream's one.
            for i in 0..latency_frames.len() - 1 {
                assert_eq!(latency_frames[i], latency_frames[i + 1]);
            }

            // Make sure all the buffer frame sizes on output scope of the input audiounit are same
            // as the defined latency of the first initial stream.
            for i in 0..in_buffer_frame_sizes.len() - 1 {
                assert_eq!(in_buffer_frame_sizes[i], in_buffer_frame_sizes[i + 1]);
            }
        },
    );
}

// Ignore the test by default to avoid overwritting the buffer frame size of the device that is
// currently used by other streams in other tests.
#[ignore]
#[test]
fn test_parallel_ops_init_streams_in_parallel_output() {
    const THREADS: u32 = 50;
    create_streams_by_ops_in_parallel_with_different_latency(
        THREADS,
        StreamType::Output,
        |streams| {
            // All the latency frames should be the same value as the first stream's one, since the
            // latency frames cannot be changed if another stream is operating in parallel.
            let mut latency_frames = vec![];
            let mut out_buffer_frame_sizes = vec![];

            for stream in streams {
                latency_frames.push(stream.latency_frames);

                assert!(stream.core_stream_data.input_unit.is_null());

                assert!(!stream.core_stream_data.output_unit.is_null());
                let out_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                    stream.core_stream_data.output_unit,
                    Scope::Output,
                    PropertyScope::Input,
                )
                .unwrap();
                out_buffer_frame_sizes.push(out_buffer_frame_size);
            }

            // Make sure all the latency frames are same as the first stream's one.
            for i in 0..latency_frames.len() - 1 {
                assert_eq!(latency_frames[i], latency_frames[i + 1]);
            }

            // Make sure all the buffer frame sizes on input scope of the output audiounit are same
            // as the defined latency of the first initial stream.
            for i in 0..out_buffer_frame_sizes.len() - 1 {
                assert_eq!(out_buffer_frame_sizes[i], out_buffer_frame_sizes[i + 1]);
            }
        },
    );
}

// Ignore the test by default to avoid overwritting the buffer frame size of the device that is
// currently used by other streams in other tests.
#[ignore]
#[test]
fn test_parallel_ops_init_streams_in_parallel_duplex() {
    const THREADS: u32 = 50;
    create_streams_by_ops_in_parallel_with_different_latency(
        THREADS,
        StreamType::Duplex,
        |streams| {
            // All the latency frames should be the same value as the first stream's one, since the
            // latency frames cannot be changed if another stream is operating in parallel.
            let mut latency_frames = vec![];
            let mut in_buffer_frame_sizes = vec![];
            let mut out_buffer_frame_sizes = vec![];

            for stream in streams {
                latency_frames.push(stream.latency_frames);

                assert!(!stream.core_stream_data.input_unit.is_null());
                let in_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                    stream.core_stream_data.input_unit,
                    Scope::Input,
                    PropertyScope::Output,
                )
                .unwrap();
                in_buffer_frame_sizes.push(in_buffer_frame_size);

                assert!(!stream.core_stream_data.output_unit.is_null());
                let out_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                    stream.core_stream_data.output_unit,
                    Scope::Output,
                    PropertyScope::Input,
                )
                .unwrap();
                out_buffer_frame_sizes.push(out_buffer_frame_size);
            }

            // Make sure all the latency frames are same as the first stream's one.
            for i in 0..latency_frames.len() - 1 {
                assert_eq!(latency_frames[i], latency_frames[i + 1]);
            }

            // Make sure all the buffer frame sizes on output scope of the input audiounit are same
            // as the defined latency of the first initial stream.
            for i in 0..in_buffer_frame_sizes.len() - 1 {
                assert_eq!(in_buffer_frame_sizes[i], in_buffer_frame_sizes[i + 1]);
            }

            // Make sure all the buffer frame sizes on input scope of the output audiounit are same
            // as the defined latency of the first initial stream.
            for i in 0..out_buffer_frame_sizes.len() - 1 {
                assert_eq!(out_buffer_frame_sizes[i], out_buffer_frame_sizes[i + 1]);
            }
        },
    );
}

fn create_streams_by_ops_in_parallel_with_different_latency<F>(
    amount: u32,
    stm_type: StreamType,
    callback: F,
) where
    F: FnOnce(Vec<&AudioUnitStream>),
{
    let default_input = test_get_default_device(Scope::Input);
    let default_output = test_get_default_device(Scope::Output);

    let has_input = stm_type == StreamType::Input || stm_type == StreamType::Duplex;
    let has_output = stm_type == StreamType::Output || stm_type == StreamType::Duplex;

    if has_input && default_input.is_none() {
        println!("No input device to perform the test.");
        return;
    }

    if has_output && default_output.is_none() {
        println!("No output device to perform the test.");
        return;
    }

    test_ops_context_operation("context: init and destroy", |context_ptr| {
        let context_ptr_value = context_ptr as usize;

        let mut join_handles = vec![];
        for i in 0..amount {
            // Make sure the parameters meet the requirements of AudioUnitContext::stream_init
            // (in the comments).
            let mut input_params = ffi::cubeb_stream_params::default();
            input_params.format = ffi::CUBEB_SAMPLE_FLOAT32NE;
            input_params.rate = 48_000;
            input_params.channels = 1;
            input_params.layout = ffi::CUBEB_LAYOUT_UNDEFINED;
            input_params.prefs = ffi::CUBEB_STREAM_PREF_NONE;

            let mut output_params = ffi::cubeb_stream_params::default();
            output_params.format = ffi::CUBEB_SAMPLE_FLOAT32NE;
            output_params.rate = 44100;
            output_params.channels = 2;
            output_params.layout = ffi::CUBEB_LAYOUT_UNDEFINED;
            output_params.prefs = ffi::CUBEB_STREAM_PREF_NONE;

            // Latency cannot be changed if another stream is operating in parallel. All the latecy
            // should be set to the same latency value of the first stream that is operating in the
            // context.
            let latency_frames = SAFE_MIN_LATENCY_FRAMES + i;
            assert!(latency_frames < SAFE_MAX_LATENCY_FRAMES);

            // Create many streams within the same context. The order of the stream creation
            // is random (The order of execution of the spawned threads is random.).assert!
            // It's super dangerous to pass `context_ptr_value` across threads and convert it back
            // to a pointer. However, it's the cheapest way to make sure the inside mutex works.
            let thread_name = format!("stream {} @ context {:?}", i, context_ptr);
            join_handles.push(
                thread::Builder::new()
                    .name(thread_name)
                    .spawn(move || {
                        let context_ptr = context_ptr_value as *mut ffi::cubeb;
                        let mut stream: *mut ffi::cubeb_stream = ptr::null_mut();
                        let stream_name = CString::new(format!("stream {}", i)).unwrap();
                        assert_eq!(
                            unsafe {
                                OPS.stream_init.unwrap()(
                                    context_ptr,
                                    &mut stream,
                                    stream_name.as_ptr(),
                                    ptr::null_mut(), // Use default input device.
                                    if has_input {
                                        &mut input_params
                                    } else {
                                        ptr::null_mut()
                                    },
                                    ptr::null_mut(), // Use default output device.
                                    if has_output {
                                        &mut output_params
                                    } else {
                                        ptr::null_mut()
                                    },
                                    latency_frames,
                                    Some(noop_data_callback),
                                    None,            // No state callback.
                                    ptr::null_mut(), // No user data pointer.
                                )
                            },
                            ffi::CUBEB_OK
                        );
                        assert!(!stream.is_null());
                        stream as usize
                    })
                    .unwrap(),
            );
        }

        let mut streams = vec![];
        // Wait for finishing the tasks on the different threads.
        for handle in join_handles {
            let stream_ptr_value = handle.join().unwrap();
            let stream = unsafe { Box::from_raw(stream_ptr_value as *mut AudioUnitStream) };
            streams.push(stream);
        }

        let stream_refs: Vec<&AudioUnitStream> = streams.iter().map(|stm| stm.as_ref()).collect();
        callback(stream_refs);
    });
}

// Ignore the test by default to avoid overwritting the buffer frame size of the device that is
// currently used by other streams in other tests.
#[ignore]
#[test]
fn test_parallel_init_streams_in_parallel_input() {
    const THREADS: u32 = 10;
    create_streams_in_parallel_with_different_latency(THREADS, StreamType::Input, |streams| {
        // All the latency frames should be the same value as the first stream's one, since the
        // latency frames cannot be changed if another stream is operating in parallel.
        let mut latency_frames = vec![];
        let mut in_buffer_frame_sizes = vec![];

        for stream in streams {
            latency_frames.push(stream.latency_frames);

            assert!(!stream.core_stream_data.input_unit.is_null());
            let in_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                stream.core_stream_data.input_unit,
                Scope::Input,
                PropertyScope::Output,
            )
            .unwrap();
            in_buffer_frame_sizes.push(in_buffer_frame_size);

            assert!(stream.core_stream_data.output_unit.is_null());
        }

        // Make sure all the latency frames are same as the first stream's one.
        for i in 0..latency_frames.len() - 1 {
            assert_eq!(latency_frames[i], latency_frames[i + 1]);
        }

        // Make sure all the buffer frame sizes on output scope of the input audiounit are same
        // as the defined latency of the first initial stream.
        for i in 0..in_buffer_frame_sizes.len() - 1 {
            assert_eq!(in_buffer_frame_sizes[i], in_buffer_frame_sizes[i + 1]);
        }
    });
}

// Ignore the test by default to avoid overwritting the buffer frame size of the device that is
// currently used by other streams in other tests.
#[ignore]
#[test]
fn test_parallel_init_streams_in_parallel_output() {
    const THREADS: u32 = 10;
    create_streams_in_parallel_with_different_latency(THREADS, StreamType::Output, |streams| {
        // All the latency frames should be the same value as the first stream's one, since the
        // latency frames cannot be changed if another stream is operating in parallel.
        let mut latency_frames = vec![];
        let mut out_buffer_frame_sizes = vec![];

        for stream in streams {
            latency_frames.push(stream.latency_frames);

            assert!(stream.core_stream_data.input_unit.is_null());

            assert!(!stream.core_stream_data.output_unit.is_null());
            let out_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                stream.core_stream_data.output_unit,
                Scope::Output,
                PropertyScope::Input,
            )
            .unwrap();
            out_buffer_frame_sizes.push(out_buffer_frame_size);
        }

        // Make sure all the latency frames are same as the first stream's one.
        for i in 0..latency_frames.len() - 1 {
            assert_eq!(latency_frames[i], latency_frames[i + 1]);
        }

        // Make sure all the buffer frame sizes on input scope of the output audiounit are same
        // as the defined latency of the first initial stream.
        for i in 0..out_buffer_frame_sizes.len() - 1 {
            assert_eq!(out_buffer_frame_sizes[i], out_buffer_frame_sizes[i + 1]);
        }
    });
}

// Ignore the test by default to avoid overwritting the buffer frame size of the device that is
// currently used by other streams in other tests.
#[ignore]
#[test]
fn test_parallel_init_streams_in_parallel_duplex() {
    const THREADS: u32 = 10;
    create_streams_in_parallel_with_different_latency(THREADS, StreamType::Duplex, |streams| {
        // All the latency frames should be the same value as the first stream's one, since the
        // latency frames cannot be changed if another stream is operating in parallel.
        let mut latency_frames = vec![];
        let mut in_buffer_frame_sizes = vec![];
        let mut out_buffer_frame_sizes = vec![];

        for stream in streams {
            latency_frames.push(stream.latency_frames);

            assert!(!stream.core_stream_data.input_unit.is_null());
            let in_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                stream.core_stream_data.input_unit,
                Scope::Input,
                PropertyScope::Output,
            )
            .unwrap();
            in_buffer_frame_sizes.push(in_buffer_frame_size);

            assert!(!stream.core_stream_data.output_unit.is_null());
            let out_buffer_frame_size = test_audiounit_get_buffer_frame_size(
                stream.core_stream_data.output_unit,
                Scope::Output,
                PropertyScope::Input,
            )
            .unwrap();
            out_buffer_frame_sizes.push(out_buffer_frame_size);
        }

        // Make sure all the latency frames are same as the first stream's one.
        for i in 0..latency_frames.len() - 1 {
            assert_eq!(latency_frames[i], latency_frames[i + 1]);
        }

        // Make sure all the buffer frame sizes on output scope of the input audiounit are same
        // as the defined latency of the first initial stream.
        for i in 0..in_buffer_frame_sizes.len() - 1 {
            assert_eq!(in_buffer_frame_sizes[i], in_buffer_frame_sizes[i + 1]);
        }

        // Make sure all the buffer frame sizes on input scope of the output audiounit are same
        // as the defined latency of the first initial stream.
        for i in 0..out_buffer_frame_sizes.len() - 1 {
            assert_eq!(out_buffer_frame_sizes[i], out_buffer_frame_sizes[i + 1]);
        }
    });
}

fn create_streams_in_parallel_with_different_latency<F>(
    amount: u32,
    stm_type: StreamType,
    callback: F,
) where
    F: FnOnce(Vec<&AudioUnitStream>),
{
    let default_input = test_get_default_device(Scope::Input);
    let default_output = test_get_default_device(Scope::Output);

    let has_input = stm_type == StreamType::Input || stm_type == StreamType::Duplex;
    let has_output = stm_type == StreamType::Output || stm_type == StreamType::Duplex;

    if has_input && default_input.is_none() {
        println!("No input device to perform the test.");
        return;
    }

    if has_output && default_output.is_none() {
        println!("No output device to perform the test.");
        return;
    }

    let mut context = AudioUnitContext::new();

    let context_ptr_value = &mut context as *mut AudioUnitContext as usize;

    let mut join_handles = vec![];
    for i in 0..amount {
        // Make sure the parameters meet the requirements of AudioUnitContext::stream_init
        // (in the comments).
        let mut input_params = ffi::cubeb_stream_params::default();
        input_params.format = ffi::CUBEB_SAMPLE_FLOAT32NE;
        input_params.rate = 48_000;
        input_params.channels = 1;
        input_params.layout = ffi::CUBEB_LAYOUT_UNDEFINED;
        input_params.prefs = ffi::CUBEB_STREAM_PREF_NONE;

        let mut output_params = ffi::cubeb_stream_params::default();
        output_params.format = ffi::CUBEB_SAMPLE_FLOAT32NE;
        output_params.rate = 44100;
        output_params.channels = 2;
        output_params.layout = ffi::CUBEB_LAYOUT_UNDEFINED;
        output_params.prefs = ffi::CUBEB_STREAM_PREF_NONE;

        // Latency cannot be changed if another stream is operating in parallel. All the latecy
        // should be set to the same latency value of the first stream that is operating in the
        // context.
        let latency_frames = SAFE_MIN_LATENCY_FRAMES + i;
        assert!(latency_frames < SAFE_MAX_LATENCY_FRAMES);

        // Create many streams within the same context. The order of the stream creation
        // is random. (The order of execution of the spawned threads is random.)
        // It's super dangerous to pass `context_ptr_value` across threads and convert it back
        // to a reference. However, it's the cheapest way to make sure the inside mutex works.
        let thread_name = format!("stream {} @ context {:?}", i, context_ptr_value);
        join_handles.push(
            thread::Builder::new()
                .name(thread_name)
                .spawn(move || {
                    let context = unsafe { &mut *(context_ptr_value as *mut AudioUnitContext) };
                    let input_params = unsafe { StreamParamsRef::from_ptr(&mut input_params) };
                    let output_params = unsafe { StreamParamsRef::from_ptr(&mut output_params) };
                    let stream = context
                        .stream_init(
                            None,
                            ptr::null_mut(), // Use default input device.
                            if has_input { Some(input_params) } else { None },
                            ptr::null_mut(), // Use default output device.
                            if has_output {
                                Some(output_params)
                            } else {
                                None
                            },
                            latency_frames,
                            Some(noop_data_callback),
                            None,            // No state callback.
                            ptr::null_mut(), // No user data pointer.
                        )
                        .unwrap();
                    assert!(!stream.as_ptr().is_null());
                    let stream_ptr_value = stream.as_ptr() as usize;
                    // Prevent the stream from being destroyed by leaking this stream.
                    mem::forget(stream);
                    stream_ptr_value
                })
                .unwrap(),
        );
    }

    let mut streams = vec![];
    // Wait for finishing the tasks on the different threads.
    for handle in join_handles {
        let stream_ptr_value = handle.join().unwrap();
        // Retake the leaked stream.
        let stream = unsafe { Box::from_raw(stream_ptr_value as *mut AudioUnitStream) };
        streams.push(stream);
    }

    let stream_refs: Vec<&AudioUnitStream> = streams.iter().map(|stm| stm.as_ref()).collect();
    callback(stream_refs);
}

#[derive(Debug, PartialEq)]
enum StreamType {
    Input,
    Output,
    Duplex,
}

// This is used to interfere other active streams.
// From this testing, it's ok to set the buffer frame size of a device that is currently used by
// other tests. It works on OSX 10.13, not sure if it works on other versions.
// However, other tests may check the buffer frame size they set at the same time,
// so we ignore this by default incase those checks fail.
#[ignore]
#[test]
fn test_set_buffer_frame_size_in_parallel() {
    test_set_buffer_frame_size_in_parallel_in_scope(Scope::Input);
    test_set_buffer_frame_size_in_parallel_in_scope(Scope::Output);
}

fn test_set_buffer_frame_size_in_parallel_in_scope(scope: Scope) {
    const THREADS: u32 = 100;

    let unit = test_get_default_audiounit(scope.clone());
    if unit.is_none() {
        println!("No unit for {:?}", scope);
        return;
    }

    let (unit_scope, unit_element, prop_scope) = match scope {
        Scope::Input => (kAudioUnitScope_Output, AU_IN_BUS, PropertyScope::Output),
        Scope::Output => (kAudioUnitScope_Input, AU_OUT_BUS, PropertyScope::Input),
    };

    let mut units = vec![];
    let mut join_handles = vec![];
    for i in 0..THREADS {
        let latency_frames = SAFE_MIN_LATENCY_FRAMES + i;
        assert!(latency_frames < SAFE_MAX_LATENCY_FRAMES);
        units.push(test_get_default_audiounit(scope.clone()).unwrap());
        let unit_value = units.last().unwrap().get_inner() as usize;
        join_handles.push(thread::spawn(move || {
            let status = audio_unit_set_property(
                unit_value as AudioUnit,
                kAudioDevicePropertyBufferFrameSize,
                unit_scope,
                unit_element,
                &latency_frames,
                mem::size_of::<u32>(),
            );
            (latency_frames, status)
        }));
    }

    let mut latencies = vec![];
    let mut statuses = vec![];
    for handle in join_handles {
        let (latency, status) = handle.join().unwrap();
        latencies.push(latency);
        statuses.push(status);
    }

    let mut buffer_frames_list = vec![];
    for unit in units.iter() {
        buffer_frames_list.push(unit.get_buffer_frame_size(scope.clone(), prop_scope.clone()));
    }

    for status in statuses {
        assert_eq!(status, NO_ERR);
    }

    for i in 0..buffer_frames_list.len() - 1 {
        assert_eq!(buffer_frames_list[i], buffer_frames_list[i + 1]);
    }
}