Debian Codegraph @

third_party/rust/cubeb-sys/libcubeb/src/cubeb_aaudio.cpp

raw
1 /* ex: set tabstop=2 shiftwidth=2 expandtab:
2 * Copyright © 2019 Jan Kelling
3 *
4 * This program is made available under an ISC-style license. See the
5 * accompanying file LICENSE for details.
6 */
7 #include "cubeb-internal.h"
8 #include "cubeb/cubeb.h"
9 #include "cubeb_android.h"
10 #include "cubeb_log.h"
11 #include "cubeb_resampler.h"
12 #include "cubeb_triple_buffer.h"
13 #include <aaudio/AAudio.h>
14 #include <atomic>
15 #include <cassert>
16 #include <chrono>
17 #include <condition_variable>
18 #include <cstdint>
19 #include <cstring>
20 #include <dlfcn.h>
21 #include <inttypes.h>
22 #include <limits>
23 #include <memory>
24 #include <mutex>
25 #include <thread>
26 #include <vector>
27
28 using namespace std;
29
30 #ifdef DISABLE_LIBAAUDIO_DLOPEN
31 #define WRAP(x) x
32 #else
33 #define WRAP(x) (*cubeb_##x)
34 #define LIBAAUDIO_API_VISIT(X) \
35 X(AAudio_convertResultToText) \
36 X(AAudio_convertStreamStateToText) \
37 X(AAudio_createStreamBuilder) \
38 X(AAudioStreamBuilder_openStream) \
39 X(AAudioStreamBuilder_setChannelCount) \
40 X(AAudioStreamBuilder_setBufferCapacityInFrames) \
41 X(AAudioStreamBuilder_setDirection) \
42 X(AAudioStreamBuilder_setFormat) \
43 X(AAudioStreamBuilder_setSharingMode) \
44 X(AAudioStreamBuilder_setPerformanceMode) \
45 X(AAudioStreamBuilder_setSampleRate) \
46 X(AAudioStreamBuilder_delete) \
47 X(AAudioStreamBuilder_setDataCallback) \
48 X(AAudioStreamBuilder_setErrorCallback) \
49 X(AAudioStream_close) \
50 X(AAudioStream_read) \
51 X(AAudioStream_requestStart) \
52 X(AAudioStream_requestPause) \
53 X(AAudioStream_setBufferSizeInFrames) \
54 X(AAudioStream_getTimestamp) \
55 X(AAudioStream_requestFlush) \
56 X(AAudioStream_requestStop) \
57 X(AAudioStream_getPerformanceMode) \
58 X(AAudioStream_getSharingMode) \
59 X(AAudioStream_getBufferSizeInFrames) \
60 X(AAudioStream_getBufferCapacityInFrames) \
61 X(AAudioStream_getSampleRate) \
62 X(AAudioStream_waitForStateChange) \
63 X(AAudioStream_getFramesRead) \
64 X(AAudioStream_getState) \
65 X(AAudioStream_getFramesWritten) \
66 X(AAudioStream_getFramesPerBurst) \
67 X(AAudioStreamBuilder_setInputPreset) \
68 X(AAudioStreamBuilder_setUsage) \
69 X(AAudioStreamBuilder_setFramesPerDataCallback)
70
71 // not needed or added later on
72 // X(AAudioStreamBuilder_setDeviceId) \
73 // X(AAudioStreamBuilder_setSamplesPerFrame) \
74 // X(AAudioStream_getSamplesPerFrame) \
75 // X(AAudioStream_getDeviceId) \
76 // X(AAudioStream_write) \
77 // X(AAudioStream_getChannelCount) \
78 // X(AAudioStream_getFormat) \
79 // X(AAudioStream_getXRunCount) \
80 // X(AAudioStream_isMMapUsed) \
81 // X(AAudioStreamBuilder_setContentType) \
82 // X(AAudioStreamBuilder_setSessionId) \
83 // X(AAudioStream_getUsage) \
84 // X(AAudioStream_getContentType) \
85 // X(AAudioStream_getInputPreset) \
86 // X(AAudioStream_getSessionId) \
87 // END: not needed or added later on
88
89 #define MAKE_TYPEDEF(x) static decltype(x) * cubeb_##x;
90 LIBAAUDIO_API_VISIT(MAKE_TYPEDEF)
91 #undef MAKE_TYPEDEF
92 #endif
93
94 const uint8_t MAX_STREAMS = 16;
95 const int64_t NS_PER_S = static_cast<int64_t>(1e9);
96
97 static void
98 aaudio_stream_destroy(cubeb_stream * stm);
99 static int
100 aaudio_stream_start(cubeb_stream * stm);
101 static int
102 aaudio_stream_stop(cubeb_stream * stm);
103
104 static int
105 aaudio_stream_init_impl(cubeb_stream * stm, lock_guard<mutex> & lock);
106 static int
107 aaudio_stream_stop_locked(cubeb_stream * stm, lock_guard<mutex> & lock);
108 static void
109 aaudio_stream_destroy_locked(cubeb_stream * stm, lock_guard<mutex> & lock);
110 static int
111 aaudio_stream_start_locked(cubeb_stream * stm, lock_guard<mutex> & lock);
112
113 static void
114 reinitialize_stream(cubeb_stream * stm);
115
116 enum class stream_state {
117 INIT = 0,
118 STOPPED,
119 STOPPING,
120 STARTED,
121 STARTING,
122 DRAINING,
123 ERROR,
124 SHUTDOWN,
125 };
126
127 struct AAudioTimingInfo {
128 // The timestamp at which the audio engine last called the calback.
129 uint64_t tstamp;
130 // The number of output frames sent to the engine.
131 uint64_t output_frame_index;
132 // The current output latency in frames. 0 if there is no output stream.
133 uint32_t output_latency;
134 // The current input latency in frames. 0 if there is no input stream.
135 uint32_t input_latency;
136 };
137
138 struct cubeb_stream {
139 /* Note: Must match cubeb_stream layout in cubeb.c. */
140 cubeb * context{};
141 void * user_ptr{};
142
143 std::atomic<bool> in_use{false};
144 std::atomic<bool> latency_metrics_available{false};
145 std::atomic<stream_state> state{stream_state::INIT};
146 std::atomic<bool> in_data_callback{false};
147 triple_buffer<AAudioTimingInfo> timing_info;
148
149 AAudioStream * ostream{};
150 AAudioStream * istream{};
151 cubeb_data_callback data_callback{};
152 cubeb_state_callback state_callback{};
153 cubeb_resampler * resampler{};
154
155 // mutex synchronizes access to the stream from the state thread
156 // and user-called functions. Everything that is accessed in the
157 // aaudio data (or error) callback is synchronized only via atomics.
158 // This lock is acquired for the entirety of the reinitialization period, when
159 // changing device.
160 std::mutex mutex;
161
162 std::vector<uint8_t> in_buf;
163 unsigned in_frame_size{}; // size of one input frame
164
165 unique_ptr<cubeb_stream_params> output_stream_params;
166 unique_ptr<cubeb_stream_params> input_stream_params;
167 uint32_t latency_frames{};
168 cubeb_sample_format out_format{};
169 uint32_t sample_rate{};
170 std::atomic<float> volume{1.f};
171 unsigned out_channels{};
172 unsigned out_frame_size{};
173 bool voice_input{};
174 bool voice_output{};
175 uint64_t previous_clock{};
176 };
177
178 struct cubeb {
179 struct cubeb_ops const * ops{};
180 void * libaaudio{};
181
182 struct {
183 // The state thread: it waits for state changes and stops
184 // drained streams.
185 std::thread thread;
186 std::thread notifier;
187 std::mutex mutex;
188 std::condition_variable cond;
189 std::atomic<bool> join{false};
190 std::atomic<bool> waiting{false};
191 } state;
192
193 // streams[i].in_use signals whether a stream is used
194 struct cubeb_stream streams[MAX_STREAMS];
195 };
196
197 struct AutoInCallback {
198 AutoInCallback(cubeb_stream * stm) : stm(stm)
199 {
200 stm->in_data_callback.store(true);
201 }
202 ~AutoInCallback() { stm->in_data_callback.store(false); }
203 cubeb_stream * stm;
204 };
205
206 // Returns when aaudio_stream's state is equal to desired_state.
207 // poll_frequency_ns is the duration that is slept in between asking for
208 // state updates and getting the new state.
209 // When waiting for a stream to stop, it is best to pick a value similar
210 // to the callback time because STOPPED will happen after
211 // draining.
212 static int
213 wait_for_state_change(AAudioStream * aaudio_stream,
214 aaudio_stream_state_t desired_state,
215 int64_t poll_frequency_ns)
216 {
217 aaudio_stream_state_t new_state;
218 do {
219 aaudio_result_t res = WRAP(AAudioStream_waitForStateChange)(
220 aaudio_stream, AAUDIO_STREAM_STATE_UNKNOWN, &new_state,
221 poll_frequency_ns);
222 if (res != AAUDIO_OK) {
223 LOG("AAudioStream_waitForStateChanged: %s",
224 WRAP(AAudio_convertResultToText)(res));
225 return CUBEB_ERROR;
226 }
227 } while (new_state != desired_state);
228
229 LOG("wait_for_state_change: current state now: %s",
230 cubeb_AAudio_convertStreamStateToText(new_state));
231
232 return CUBEB_OK;
233 }
234
235 // Only allowed from state thread, while mutex on stm is locked
236 static void
237 shutdown_with_error(cubeb_stream * stm)
238 {
239 if (stm->istream) {
240 WRAP(AAudioStream_requestStop)(stm->istream);
241 }
242 if (stm->ostream) {
243 WRAP(AAudioStream_requestStop)(stm->ostream);
244 }
245
246 int64_t poll_frequency_ns = NS_PER_S * stm->out_frame_size / stm->sample_rate;
247 int rv;
248 if (stm->istream) {
249 rv = wait_for_state_change(stm->istream, AAUDIO_STREAM_STATE_STOPPED,
250 poll_frequency_ns);
251 if (rv != CUBEB_OK) {
252 LOG("Failure when waiting for stream change on the input side when "
253 "shutting down in error");
254 // Not much we can do, carry on
255 }
256 }
257 if (stm->ostream) {
258 rv = wait_for_state_change(stm->ostream, AAUDIO_STREAM_STATE_STOPPED,
259 poll_frequency_ns);
260 if (rv != CUBEB_OK) {
261 LOG("Failure when waiting for stream change on the output side when "
262 "shutting down in error");
263 // Not much we can do, carry on
264 }
265 }
266
267 assert(!stm->in_data_callback.load());
268 stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
269 stm->state.store(stream_state::SHUTDOWN);
270 }
271
272 // Returns whether the given state is one in which we wait for
273 // an asynchronous change
274 static bool
275 waiting_state(stream_state state)
276 {
277 switch (state) {
278 case stream_state::DRAINING:
279 case stream_state::STARTING:
280 case stream_state::STOPPING:
281 return true;
282 default:
283 return false;
284 }
285 }
286
287 static void
288 update_state(cubeb_stream * stm)
289 {
290 // Fast path for streams that don't wait for state change or are invalid
291 enum stream_state old_state = stm->state.load();
292 if (old_state == stream_state::INIT || old_state == stream_state::STARTED ||
293 old_state == stream_state::STOPPED ||
294 old_state == stream_state::SHUTDOWN) {
295 return;
296 }
297
298 // If the main thread currently operates on this thread, we don't
299 // have to wait for it
300 unique_lock lock(stm->mutex, std::try_to_lock);
301 if (!lock.owns_lock()) {
302 return;
303 }
304
305 // check again: if this is true now, the stream was destroyed or
306 // changed between our fast path check and locking the mutex
307 old_state = stm->state.load();
308 if (old_state == stream_state::INIT || old_state == stream_state::STARTED ||
309 old_state == stream_state::STOPPED ||
310 old_state == stream_state::SHUTDOWN) {
311 return;
312 }
313
314 // We compute the new state the stream has and then compare_exchange it
315 // if it has changed. This way we will never just overwrite state
316 // changes that were set from the audio thread in the meantime,
317 // such as a DRAINING or error state.
318 enum stream_state new_state;
319 do {
320 if (old_state == stream_state::SHUTDOWN) {
321 return;
322 }
323
324 if (old_state == stream_state::ERROR) {
325 shutdown_with_error(stm);
326 return;
327 }
328
329 new_state = old_state;
330
331 aaudio_stream_state_t istate = 0;
332 aaudio_stream_state_t ostate = 0;
333
334 // We use waitForStateChange (with zero timeout) instead of just
335 // getState since only the former internally updates the state.
336 // See the docs of aaudio getState/waitForStateChange for details,
337 // why we are passing STATE_UNKNOWN.
338 aaudio_result_t res;
339 if (stm->istream) {
340 res = WRAP(AAudioStream_waitForStateChange)(
341 stm->istream, AAUDIO_STREAM_STATE_UNKNOWN, &istate, 0);
342 if (res != AAUDIO_OK) {
343 LOG("AAudioStream_waitForStateChanged: %s",
344 WRAP(AAudio_convertResultToText)(res));
345 return;
346 }
347 assert(istate);
348 }
349
350 if (stm->ostream) {
351 res = WRAP(AAudioStream_waitForStateChange)(
352 stm->ostream, AAUDIO_STREAM_STATE_UNKNOWN, &ostate, 0);
353 if (res != AAUDIO_OK) {
354 LOG("AAudioStream_waitForStateChanged: %s",
355 WRAP(AAudio_convertResultToText)(res));
356 return;
357 }
358 assert(ostate);
359 }
360
361 // handle invalid stream states
362 if (istate == AAUDIO_STREAM_STATE_PAUSING ||
363 istate == AAUDIO_STREAM_STATE_PAUSED ||
364 istate == AAUDIO_STREAM_STATE_FLUSHING ||
365 istate == AAUDIO_STREAM_STATE_FLUSHED ||
366 istate == AAUDIO_STREAM_STATE_UNKNOWN ||
367 istate == AAUDIO_STREAM_STATE_DISCONNECTED) {
368 LOG("Unexpected android input stream state %s",
369 WRAP(AAudio_convertStreamStateToText)(istate));
370 shutdown_with_error(stm);
371 return;
372 }
373
374 if (ostate == AAUDIO_STREAM_STATE_PAUSING ||
375 ostate == AAUDIO_STREAM_STATE_PAUSED ||
376 ostate == AAUDIO_STREAM_STATE_FLUSHING ||
377 ostate == AAUDIO_STREAM_STATE_FLUSHED ||
378 ostate == AAUDIO_STREAM_STATE_UNKNOWN ||
379 ostate == AAUDIO_STREAM_STATE_DISCONNECTED) {
380 LOG("Unexpected android output stream state %s",
381 WRAP(AAudio_convertStreamStateToText)(istate));
382 shutdown_with_error(stm);
383 return;
384 }
385
386 switch (old_state) {
387 case stream_state::STARTING:
388 if ((!istate || istate == AAUDIO_STREAM_STATE_STARTED) &&
389 (!ostate || ostate == AAUDIO_STREAM_STATE_STARTED)) {
390 stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_STARTED);
391 new_state = stream_state::STARTED;
392 }
393 break;
394 case stream_state::DRAINING:
395 // The DRAINING state means that we want to stop the streams but
396 // may not have done so yet.
397 // The aaudio docs state that returning STOP from the callback isn't
398 // enough, the stream has to be stopped from another thread
399 // afterwards.
400 // No callbacks are triggered anymore when requestStop returns.
401 // That is important as we otherwise might read from a closed istream
402 // for a duplex stream.
403 // Therefor it is important to close ostream first.
404 if (ostate && ostate != AAUDIO_STREAM_STATE_STOPPING &&
405 ostate != AAUDIO_STREAM_STATE_STOPPED) {
406 res = WRAP(AAudioStream_requestStop)(stm->ostream);
407 if (res != AAUDIO_OK) {
408 LOG("AAudioStream_requestStop: %s",
409 WRAP(AAudio_convertResultToText)(res));
410 return;
411 }
412 }
413 if (istate && istate != AAUDIO_STREAM_STATE_STOPPING &&
414 istate != AAUDIO_STREAM_STATE_STOPPED) {
415 res = WRAP(AAudioStream_requestStop)(stm->istream);
416 if (res != AAUDIO_OK) {
417 LOG("AAudioStream_requestStop: %s",
418 WRAP(AAudio_convertResultToText)(res));
419 return;
420 }
421 }
422
423 // we always wait until both streams are stopped until we
424 // send CUBEB_STATE_DRAINED. Then we can directly transition
425 // our logical state to STOPPED, not triggering
426 // an additional CUBEB_STATE_STOPPED callback (which might
427 // be unexpected for the user).
428 if ((!ostate || ostate == AAUDIO_STREAM_STATE_STOPPED) &&
429 (!istate || istate == AAUDIO_STREAM_STATE_STOPPED)) {
430 new_state = stream_state::STOPPED;
431 stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
432 }
433 break;
434 case stream_state::STOPPING:
435 assert(!istate || istate == AAUDIO_STREAM_STATE_STOPPING ||
436 istate == AAUDIO_STREAM_STATE_STOPPED);
437 assert(!ostate || ostate == AAUDIO_STREAM_STATE_STOPPING ||
438 ostate == AAUDIO_STREAM_STATE_STOPPED);
439 if ((!istate || istate == AAUDIO_STREAM_STATE_STOPPED) &&
440 (!ostate || ostate == AAUDIO_STREAM_STATE_STOPPED)) {
441 stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_STOPPED);
442 new_state = stream_state::STOPPED;
443 }
444 break;
445 default:
446 assert(false && "Unreachable: invalid state");
447 }
448 } while (old_state != new_state &&
449 !stm->state.compare_exchange_strong(old_state, new_state));
450 }
451
452 // See https://nyorain.github.io/lock-free-wakeup.html for a note
453 // why this is needed. The audio thread notifies the state thread about
454 // state changes and must not block. The state thread on the other hand should
455 // sleep until there is work to be done. So we need a lockfree producer
456 // and blocking producer. This can only be achieved safely with a new thread
457 // that only serves as notifier backup (in case the notification happens
458 // right between the state thread checking and going to sleep in which case
459 // this thread will kick in and signal it right again).
460 static void
461 notifier_thread(cubeb * ctx)
462 {
463 unique_lock lock(ctx->state.mutex);
464
465 while (!ctx->state.join.load()) {
466 ctx->state.cond.wait(lock);
467 if (ctx->state.waiting.load()) {
468 // This must signal our state thread since there is no other
469 // thread currently waiting on the condition variable.
470 // The state change thread is guaranteed to be waiting since
471 // we hold the mutex it locks when awake.
472 ctx->state.cond.notify_one();
473 }
474 }
475
476 // make sure other thread joins as well
477 ctx->state.cond.notify_one();
478 LOG("Exiting notifier thread");
479 }
480
481 static void
482 state_thread(cubeb * ctx)
483 {
484 unique_lock lock(ctx->state.mutex);
485
486 bool waiting = false;
487 while (!ctx->state.join.load()) {
488 waiting |= ctx->state.waiting.load();
489 if (waiting) {
490 ctx->state.waiting.store(false);
491 waiting = false;
492 for (auto & stream : ctx->streams) {
493 cubeb_stream * stm = &stream;
494 update_state(stm);
495 waiting |= waiting_state(atomic_load(&stm->state));
496 }
497
498 // state changed from another thread, update again immediately
499 if (ctx->state.waiting.load()) {
500 waiting = true;
501 continue;
502 }
503
504 // Not waiting for any change anymore: we can wait on the
505 // condition variable without timeout
506 if (!waiting) {
507 continue;
508 }
509
510 // while any stream is waiting for state change we sleep with regular
511 // timeouts. But we wake up immediately if signaled.
512 // This might seem like a poor man's implementation of state change
513 // waiting but (as of october 2020), the implementation of
514 // AAudioStream_waitForStateChange is just sleeping with regular
515 // timeouts as well:
516 // https://android.googlesource.com/platform/frameworks/av/+/refs/heads/master/media/libaaudio/src/core/AudioStream.cpp
517 auto dur = std::chrono::milliseconds(5);
518 ctx->state.cond.wait_for(lock, dur);
519 } else {
520 ctx->state.cond.wait(lock);
521 }
522 }
523
524 // make sure other thread joins as well
525 ctx->state.cond.notify_one();
526 LOG("Exiting state thread");
527 }
528
529 static char const *
530 aaudio_get_backend_id(cubeb * /* ctx */)
531 {
532 return "aaudio";
533 }
534
535 static int
536 aaudio_get_max_channel_count(cubeb * ctx, uint32_t * max_channels)
537 {
538 assert(ctx && max_channels);
539 // NOTE: we might get more, AAudio docs don't specify anything.
540 *max_channels = 2;
541 return CUBEB_OK;
542 }
543
544 static void
545 aaudio_destroy(cubeb * ctx)
546 {
547 assert(ctx);
548
549 #ifndef NDEBUG
550 // make sure all streams were destroyed
551 for (auto & stream : ctx->streams) {
552 assert(!stream.in_use.load());
553 }
554 #endif
555
556 // broadcast joining to both threads
557 // they will additionally signal each other before joining
558 ctx->state.join.store(true);
559 ctx->state.cond.notify_all();
560
561 if (ctx->state.thread.joinable()) {
562 ctx->state.thread.join();
563 }
564 if (ctx->state.notifier.joinable()) {
565 ctx->state.notifier.join();
566 }
567 #ifndef DISABLE_LIBAAUDIO_DLOPEN
568 if (ctx->libaaudio) {
569 dlclose(ctx->libaaudio);
570 }
571 #endif
572 delete ctx;
573 }
574
575 static void
576 apply_volume(cubeb_stream * stm, void * audio_data, uint32_t num_frames)
577 {
578 float volume = stm->volume.load();
579 // optimization: we don't have to change anything in this case
580 if (volume == 1.f) {
581 return;
582 }
583
584 switch (stm->out_format) {
585 case CUBEB_SAMPLE_S16NE: {
586 int16_t * integer_data = static_cast<int16_t *>(audio_data);
587 for (uint32_t i = 0u; i < num_frames * stm->out_channels; ++i) {
588 integer_data[i] =
589 static_cast<int16_t>(static_cast<float>(integer_data[i]) * volume);
590 }
591 break;
592 }
593 case CUBEB_SAMPLE_FLOAT32NE:
594 for (uint32_t i = 0u; i < num_frames * stm->out_channels; ++i) {
595 (static_cast<float *>(audio_data))[i] *= volume;
596 }
597 break;
598 default:
599 assert(false && "Unreachable: invalid stream out_format");
600 }
601 }
602
603 uint64_t
604 now_ns()
605 {
606 using namespace std::chrono;
607 return duration_cast<nanoseconds>(steady_clock::now().time_since_epoch())
608 .count();
609 }
610
611 // To be called from the real-time audio callback
612 uint64_t
613 aaudio_get_latency(cubeb_stream * stm, aaudio_direction_t direction,
614 uint64_t tstamp_ns)
615 {
616 bool is_output = direction == AAUDIO_DIRECTION_OUTPUT;
617 int64_t hw_frame_index;
618 int64_t hw_tstamp;
619 AAudioStream * stream = is_output ? stm->ostream : stm->istream;
620 // For an output stream (resp. input stream), get the number of frames
621 // written to (resp read from) the hardware.
622 int64_t app_frame_index = is_output
623 ? WRAP(AAudioStream_getFramesWritten)(stream)
624 : WRAP(AAudioStream_getFramesRead)(stream);
625
626 assert(tstamp_ns < std::numeric_limits<uint64_t>::max());
627 int64_t signed_tstamp_ns = static_cast<int64_t>(tstamp_ns);
628
629 // Get a timestamp for a particular frame index written to or read from the
630 // hardware.
631 auto result = WRAP(AAudioStream_getTimestamp)(stream, CLOCK_MONOTONIC,
632 &hw_frame_index, &hw_tstamp);
633 if (result != AAUDIO_OK) {
634 LOG("AAudioStream_getTimestamp failure for %s: %s",
635 is_output ? "output" : "input",
636 WRAP(AAudio_convertResultToText)(result));
637 return 0;
638 }
639
640 // Compute the difference between the app and the hardware indices.
641 int64_t frame_index_delta = app_frame_index - hw_frame_index;
642 // Convert to ns
643 int64_t frame_time_delta = (frame_index_delta * NS_PER_S) / stm->sample_rate;
644 // Extrapolate from the known timestamp for a particular frame presented.
645 int64_t app_frame_hw_time = hw_tstamp + frame_time_delta;
646 // For an output stream, the latency is positive, for an input stream, it's
647 // negative.
648 int64_t latency_ns = is_output ? app_frame_hw_time - signed_tstamp_ns
649 : signed_tstamp_ns - app_frame_hw_time;
650 int64_t latency_frames = stm->sample_rate * latency_ns / NS_PER_S;
651
652 LOGV("Latency in frames (%s): %d (%dms)", is_output ? "output" : "input",
653 latency_frames, latency_ns / 1e6);
654
655 return latency_frames;
656 }
657
658 void
659 compute_and_report_latency_metrics(cubeb_stream * stm)
660 {
661 AAudioTimingInfo info = {};
662
663 info.tstamp = now_ns();
664
665 if (stm->ostream) {
666 uint64_t latency_frames =
667 aaudio_get_latency(stm, AAUDIO_DIRECTION_OUTPUT, info.tstamp);
668 if (latency_frames) {
669 info.output_latency = latency_frames;
670 info.output_frame_index =
671 WRAP(AAudioStream_getFramesWritten)(stm->ostream);
672 }
673 }
674 if (stm->istream) {
675 uint64_t latency_frames =
676 aaudio_get_latency(stm, AAUDIO_DIRECTION_INPUT, info.tstamp);
677 if (latency_frames) {
678 info.input_latency = latency_frames;
679 }
680 }
681
682 if (info.output_latency || info.input_latency) {
683 stm->latency_metrics_available = true;
684 stm->timing_info.write(info);
685 }
686 }
687
688 // Returning AAUDIO_CALLBACK_RESULT_STOP seems to put the stream in
689 // an invalid state. Seems like an AAudio bug/bad documentation.
690 // We therefore only return it on error.
691
692 static aaudio_data_callback_result_t
693 aaudio_duplex_data_cb(AAudioStream * astream, void * user_data,
694 void * audio_data, int32_t num_frames)
695 {
696 cubeb_stream * stm = (cubeb_stream *)user_data;
697 AutoInCallback aic(stm);
698 assert(stm->ostream == astream);
699 assert(stm->istream);
700 assert(num_frames >= 0);
701
702 stream_state state = atomic_load(&stm->state);
703 int istate = WRAP(AAudioStream_getState)(stm->istream);
704 int ostate = WRAP(AAudioStream_getState)(stm->ostream);
705
706 // all other states may happen since the callback might be called
707 // from within requestStart
708 assert(state != stream_state::SHUTDOWN);
709
710 // This might happen when we started draining but not yet actually
711 // stopped the stream from the state thread.
712 if (state == stream_state::DRAINING) {
713 LOG("Draining in duplex callback");
714 std::memset(audio_data, 0x0, num_frames * stm->out_frame_size);
715 return AAUDIO_CALLBACK_RESULT_CONTINUE;
716 }
717
718 if (num_frames * stm->in_frame_size > stm->in_buf.size()) {
719 LOG("Resizing input buffer in duplex callback");
720 stm->in_buf.resize(num_frames * stm->in_frame_size);
721 }
722 // The aaudio docs state that AAudioStream_read must not be called on
723 // the stream associated with a callback. But we call it on the input stream
724 // while this callback is for the output stream so this is ok.
725 // We also pass timeout 0, giving us strong non-blocking guarantees.
726 // This is exactly how it's done in the aaudio duplex example code snippet.
727 long in_num_frames =
728 WRAP(AAudioStream_read)(stm->istream, stm->in_buf.data(), num_frames, 0);
729 if (in_num_frames < 0) { // error
730 if (in_num_frames == AAUDIO_STREAM_STATE_DISCONNECTED) {
731 LOG("AAudioStream_read: %s (reinitializing)",
732 WRAP(AAudio_convertResultToText)(in_num_frames));
733 reinitialize_stream(stm);
734 } else {
735 stm->state.store(stream_state::ERROR);
736 }
737 LOG("AAudioStream_read: %s",
738 WRAP(AAudio_convertResultToText)(in_num_frames));
739 return AAUDIO_CALLBACK_RESULT_STOP;
740 }
741
742 ALOGV("aaudio duplex data cb on stream %p: state %ld (in: %d, out: %d), "
743 "num_frames: %ld, read: %ld",
744 (void *)stm, state, istate, ostate, num_frames, in_num_frames);
745
746 compute_and_report_latency_metrics(stm);
747
748 // This can happen shortly after starting the stream. AAudio might immediately
749 // begin to buffer output but not have any input ready yet. We could
750 // block AAudioStream_read (passing a timeout > 0) but that leads to issues
751 // since blocking in this callback is a bad idea in general and it might break
752 // the stream when it is stopped by another thread shortly after being
753 // started. We therefore simply send silent input to the application, as shown
754 // in the AAudio duplex stream code example.
755 if (in_num_frames < num_frames) {
756 // LOG("AAudioStream_read returned not enough frames: %ld instead of %d",
757 // in_num_frames, num_frames);
758 unsigned left = num_frames - in_num_frames;
759 uint8_t * buf = stm->in_buf.data() + in_num_frames * stm->in_frame_size;
760 std::memset(buf, 0x0, left * stm->in_frame_size);
761 in_num_frames = num_frames;
762 }
763
764 long done_frames =
765 cubeb_resampler_fill(stm->resampler, stm->in_buf.data(), &in_num_frames,
766 audio_data, num_frames);
767
768 if (done_frames < 0 || done_frames > num_frames) {
769 LOG("Error in data callback or resampler: %ld", done_frames);
770 stm->state.store(stream_state::ERROR);
771 return AAUDIO_CALLBACK_RESULT_STOP;
772 }
773 if (done_frames < num_frames) {
774 stm->state.store(stream_state::DRAINING);
775 stm->context->state.waiting.store(true);
776 stm->context->state.cond.notify_one();
777
778 char * begin =
779 static_cast<char *>(audio_data) + done_frames * stm->out_frame_size;
780 std::memset(begin, 0x0, (num_frames - done_frames) * stm->out_frame_size);
781 }
782
783 apply_volume(stm, audio_data, done_frames);
784 return AAUDIO_CALLBACK_RESULT_CONTINUE;
785 }
786
787 static aaudio_data_callback_result_t
788 aaudio_output_data_cb(AAudioStream * astream, void * user_data,
789 void * audio_data, int32_t num_frames)
790 {
791 cubeb_stream * stm = (cubeb_stream *)user_data;
792 AutoInCallback aic(stm);
793 assert(stm->ostream == astream);
794 assert(!stm->istream);
795 assert(num_frames >= 0);
796
797 stream_state state = stm->state.load();
798 int ostate = WRAP(AAudioStream_getState)(stm->ostream);
799 ALOGV("aaudio output data cb on stream %p: state %ld (%d), num_frames: %ld",
800 stm, state, ostate, num_frames);
801
802 // all other states may happen since the callback might be called
803 // from within requestStart
804 assert(state != stream_state::SHUTDOWN);
805
806 // This might happen when we started draining but not yet actually
807 // stopped the stream from the state thread.
808 if (state == stream_state::DRAINING) {
809 std::memset(audio_data, 0x0, num_frames * stm->out_frame_size);
810 return AAUDIO_CALLBACK_RESULT_CONTINUE;
811 }
812
813 compute_and_report_latency_metrics(stm);
814
815 long done_frames = cubeb_resampler_fill(stm->resampler, nullptr, nullptr,
816 audio_data, num_frames);
817 if (done_frames < 0 || done_frames > num_frames) {
818 LOG("Error in data callback or resampler: %ld", done_frames);
819 stm->state.store(stream_state::ERROR);
820 return AAUDIO_CALLBACK_RESULT_STOP;
821 }
822
823 if (done_frames < num_frames) {
824 stm->state.store(stream_state::DRAINING);
825 stm->context->state.waiting.store(true);
826 stm->context->state.cond.notify_one();
827
828 char * begin =
829 static_cast<char *>(audio_data) + done_frames * stm->out_frame_size;
830 std::memset(begin, 0x0, (num_frames - done_frames) * stm->out_frame_size);
831 }
832
833 apply_volume(stm, audio_data, done_frames);
834 return AAUDIO_CALLBACK_RESULT_CONTINUE;
835 }
836
837 static aaudio_data_callback_result_t
838 aaudio_input_data_cb(AAudioStream * astream, void * user_data,
839 void * audio_data, int32_t num_frames)
840 {
841 cubeb_stream * stm = (cubeb_stream *)user_data;
842 AutoInCallback aic(stm);
843 assert(stm->istream == astream);
844 assert(!stm->ostream);
845 assert(num_frames >= 0);
846
847 stream_state state = stm->state.load();
848 int istate = WRAP(AAudioStream_getState)(stm->istream);
849 ALOGV("aaudio input data cb on stream %p: state %ld (%d), num_frames: %ld",
850 stm, state, istate, num_frames);
851
852 // all other states may happen since the callback might be called
853 // from within requestStart
854 assert(state != stream_state::SHUTDOWN);
855
856 // This might happen when we started draining but not yet actually
857 // STOPPED the stream from the state thread.
858 if (state == stream_state::DRAINING) {
859 return AAUDIO_CALLBACK_RESULT_CONTINUE;
860 }
861
862 compute_and_report_latency_metrics(stm);
863
864 long input_frame_count = num_frames;
865 long done_frames = cubeb_resampler_fill(stm->resampler, audio_data,
866 &input_frame_count, nullptr, 0);
867
868 if (done_frames < 0 || done_frames > num_frames) {
869 LOG("Error in data callback or resampler: %ld", done_frames);
870 stm->state.store(stream_state::ERROR);
871 return AAUDIO_CALLBACK_RESULT_STOP;
872 }
873
874 if (done_frames < input_frame_count) {
875 // we don't really drain an input stream, just have to
876 // stop it from the state thread. That is signaled via the
877 // DRAINING state.
878 stm->state.store(stream_state::DRAINING);
879 stm->context->state.waiting.store(true);
880 stm->context->state.cond.notify_one();
881 }
882
883 return AAUDIO_CALLBACK_RESULT_CONTINUE;
884 }
885
886 static void
887 reinitialize_stream(cubeb_stream * stm)
888 {
889 // This cannot be done from within the error callback, bounce to another
890 // thread.
891 // In this situation, the lock is acquired for the entire duration of the
892 // function, so that this reinitialization period is atomic.
893 std::thread([stm] {
894 lock_guard lock(stm->mutex);
895 stream_state state = stm->state.load();
896 bool was_playing = state == stream_state::STARTED ||
897 state == stream_state::STARTING ||
898 state == stream_state::DRAINING;
899 int err = aaudio_stream_stop_locked(stm, lock);
900 // error ignored.
901 aaudio_stream_destroy_locked(stm, lock);
902 err = aaudio_stream_init_impl(stm, lock);
903
904 assert(stm->in_use.load());
905
906 if (err != CUBEB_OK) {
907 aaudio_stream_destroy_locked(stm, lock);
908 LOG("aaudio_stream_init_impl error while reiniting: %s",
909 WRAP(AAudio_convertResultToText)(err));
910 stm->state.store(stream_state::ERROR);
911 return;
912 }
913
914 if (was_playing) {
915 err = aaudio_stream_start_locked(stm, lock);
916 if (err != CUBEB_OK) {
917 aaudio_stream_destroy_locked(stm, lock);
918 LOG("aaudio_stream_start error while reiniting: %s",
919 WRAP(AAudio_convertResultToText)(err));
920 stm->state.store(stream_state::ERROR);
921 return;
922 }
923 }
924 }).detach();
925 }
926
927 static void
928 aaudio_error_cb(AAudioStream * astream, void * user_data, aaudio_result_t error)
929 {
930 cubeb_stream * stm = static_cast<cubeb_stream *>(user_data);
931 assert(stm->ostream == astream || stm->istream == astream);
932
933 // Device change -- reinitialize on the new default device.
934 if (error == AAUDIO_ERROR_DISCONNECTED || error == AAUDIO_ERROR_TIMEOUT) {
935 LOG("Audio device change, reinitializing stream");
936 reinitialize_stream(stm);
937 return;
938 }
939
940 LOG("AAudio error callback: %s", WRAP(AAudio_convertResultToText)(error));
941 stm->state.store(stream_state::ERROR);
942 }
943
944 static int
945 realize_stream(AAudioStreamBuilder * sb, const cubeb_stream_params * params,
946 AAudioStream ** stream, unsigned * frame_size)
947 {
948 aaudio_result_t res;
949 assert(params->rate);
950 assert(params->channels);
951
952 WRAP(AAudioStreamBuilder_setSampleRate)
953 (sb, static_cast<int32_t>(params->rate));
954 WRAP(AAudioStreamBuilder_setChannelCount)
955 (sb, static_cast<int32_t>(params->channels));
956
957 aaudio_format_t fmt;
958 switch (params->format) {
959 case CUBEB_SAMPLE_S16NE:
960 fmt = AAUDIO_FORMAT_PCM_I16;
961 *frame_size = sizeof(int16_t) * params->channels;
962 break;
963 case CUBEB_SAMPLE_FLOAT32NE:
964 fmt = AAUDIO_FORMAT_PCM_FLOAT;
965 *frame_size = sizeof(float) * params->channels;
966 break;
967 default:
968 return CUBEB_ERROR_INVALID_FORMAT;
969 }
970
971 WRAP(AAudioStreamBuilder_setFormat)(sb, fmt);
972 res = WRAP(AAudioStreamBuilder_openStream)(sb, stream);
973 if (res == AAUDIO_ERROR_INVALID_FORMAT) {
974 LOG("AAudio device doesn't support output format %d", fmt);
975 return CUBEB_ERROR_INVALID_FORMAT;
976 }
977
978 if (params->rate && res == AAUDIO_ERROR_INVALID_RATE) {
979 // The requested rate is not supported.
980 // Just try again with default rate, we create a resampler anyways
981 WRAP(AAudioStreamBuilder_setSampleRate)(sb, AAUDIO_UNSPECIFIED);
982 res = WRAP(AAudioStreamBuilder_openStream)(sb, stream);
983 LOG("Requested rate of %u is not supported, inserting resampler",
984 params->rate);
985 }
986
987 // When the app has no permission to record audio
988 // (android.permission.RECORD_AUDIO) but requested and input stream, this will
989 // return INVALID_ARGUMENT.
990 if (res != AAUDIO_OK) {
991 LOG("AAudioStreamBuilder_openStream: %s",
992 WRAP(AAudio_convertResultToText)(res));
993 return CUBEB_ERROR;
994 }
995
996 return CUBEB_OK;
997 }
998
999 static void
1000 aaudio_stream_destroy(cubeb_stream * stm)
1001 {
1002 lock_guard lock(stm->mutex);
1003 stm->in_use.store(false);
1004 aaudio_stream_destroy_locked(stm, lock);
1005 }
1006
1007 static void
1008 aaudio_stream_destroy_locked(cubeb_stream * stm, lock_guard<mutex> & lock)
1009 {
1010 assert(stm->state == stream_state::STOPPED ||
1011 stm->state == stream_state::STOPPING ||
1012 stm->state == stream_state::INIT ||
1013 stm->state == stream_state::DRAINING ||
1014 stm->state == stream_state::ERROR ||
1015 stm->state == stream_state::SHUTDOWN);
1016
1017 aaudio_result_t res;
1018
1019 // No callbacks are triggered anymore when requestStop returns.
1020 // That is important as we otherwise might read from a closed istream
1021 // for a duplex stream.
1022 if (stm->ostream) {
1023 if (stm->state != stream_state::STOPPED &&
1024 stm->state != stream_state::STOPPING &&
1025 stm->state != stream_state::SHUTDOWN) {
1026 res = WRAP(AAudioStream_requestStop)(stm->ostream);
1027 if (res != AAUDIO_OK) {
1028 LOG("AAudioStreamBuilder_requestStop: %s",
1029 WRAP(AAudio_convertResultToText)(res));
1030 }
1031 }
1032
1033 WRAP(AAudioStream_close)(stm->ostream);
1034 stm->ostream = nullptr;
1035 }
1036
1037 if (stm->istream) {
1038 if (stm->state != stream_state::STOPPED &&
1039 stm->state != stream_state::STOPPING &&
1040 stm->state != stream_state::SHUTDOWN) {
1041 res = WRAP(AAudioStream_requestStop)(stm->istream);
1042 if (res != AAUDIO_OK) {
1043 LOG("AAudioStreamBuilder_requestStop: %s",
1044 WRAP(AAudio_convertResultToText)(res));
1045 }
1046 }
1047
1048 WRAP(AAudioStream_close)(stm->istream);
1049 stm->istream = nullptr;
1050 }
1051
1052 if (stm->resampler) {
1053 cubeb_resampler_destroy(stm->resampler);
1054 stm->resampler = nullptr;
1055 }
1056
1057 stm->in_buf = {};
1058 stm->in_frame_size = {};
1059 stm->out_format = {};
1060 stm->out_channels = {};
1061 stm->out_frame_size = {};
1062
1063 stm->state.store(stream_state::INIT);
1064 }
1065
1066 static int
1067 aaudio_stream_init_impl(cubeb_stream * stm, lock_guard<mutex> & lock)
1068 {
1069 assert(stm->state.load() == stream_state::INIT);
1070
1071 cubeb_async_log_reset_threads();
1072
1073 aaudio_result_t res;
1074 AAudioStreamBuilder * sb;
1075 res = WRAP(AAudio_createStreamBuilder)(&sb);
1076 if (res != AAUDIO_OK) {
1077 LOG("AAudio_createStreamBuilder: %s",
1078 WRAP(AAudio_convertResultToText)(res));
1079 return CUBEB_ERROR;
1080 }
1081
1082 // make sure the builder is always destroyed
1083 struct StreamBuilderDestructor {
1084 void operator()(AAudioStreamBuilder * sb)
1085 {
1086 WRAP(AAudioStreamBuilder_delete)(sb);
1087 }
1088 };
1089
1090 std::unique_ptr<AAudioStreamBuilder, StreamBuilderDestructor> sbPtr(sb);
1091
1092 WRAP(AAudioStreamBuilder_setErrorCallback)(sb, aaudio_error_cb, stm);
1093 WRAP(AAudioStreamBuilder_setBufferCapacityInFrames)
1094 (sb, static_cast<int32_t>(stm->latency_frames));
1095
1096 AAudioStream_dataCallback in_data_callback{};
1097 AAudioStream_dataCallback out_data_callback{};
1098 if (stm->output_stream_params && stm->input_stream_params) {
1099 out_data_callback = aaudio_duplex_data_cb;
1100 in_data_callback = nullptr;
1101 } else if (stm->input_stream_params) {
1102 in_data_callback = aaudio_input_data_cb;
1103 } else if (stm->output_stream_params) {
1104 out_data_callback = aaudio_output_data_cb;
1105 } else {
1106 LOG("Tried to open stream without input or output parameters");
1107 return CUBEB_ERROR;
1108 }
1109
1110 #ifdef CUBEB_AAUDIO_EXCLUSIVE_STREAM
1111 LOG("AAudio setting exclusive share mode for stream");
1112 WRAP(AAudioStreamBuilder_setSharingMode)(sb, AAUDIO_SHARING_MODE_EXCLUSIVE);
1113 #endif
1114
1115 if (stm->latency_frames <= POWERSAVE_LATENCY_FRAMES_THRESHOLD) {
1116 LOG("AAudio setting low latency mode for stream");
1117 WRAP(AAudioStreamBuilder_setPerformanceMode)
1118 (sb, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
1119 } else {
1120 LOG("AAudio setting power saving mode for stream");
1121 WRAP(AAudioStreamBuilder_setPerformanceMode)
1122 (sb, AAUDIO_PERFORMANCE_MODE_POWER_SAVING);
1123 }
1124
1125 unsigned frame_size;
1126
1127 // initialize streams
1128 // output
1129 cubeb_stream_params out_params;
1130 if (stm->output_stream_params) {
1131 int output_preset = stm->voice_output ? AAUDIO_USAGE_VOICE_COMMUNICATION
1132 : AAUDIO_USAGE_MEDIA;
1133 WRAP(AAudioStreamBuilder_setUsage)(sb, output_preset);
1134 WRAP(AAudioStreamBuilder_setDirection)(sb, AAUDIO_DIRECTION_OUTPUT);
1135 WRAP(AAudioStreamBuilder_setDataCallback)(sb, out_data_callback, stm);
1136 assert(stm->latency_frames < std::numeric_limits<int32_t>::max());
1137 LOG("Frames per callback set to %d for output", stm->latency_frames);
1138 WRAP(AAudioStreamBuilder_setFramesPerDataCallback)
1139 (sb, static_cast<int32_t>(stm->latency_frames));
1140
1141 int res_err = realize_stream(sb, stm->output_stream_params.get(),
1142 &stm->ostream, &frame_size);
1143 if (res_err) {
1144 return res_err;
1145 }
1146
1147 int32_t output_burst_size =
1148 WRAP(AAudioStream_getFramesPerBurst)(stm->ostream);
1149 LOG("AAudio output burst size: %d", output_burst_size);
1150 // 3 times the burst size seems to be robust.
1151 res = WRAP(AAudioStream_setBufferSizeInFrames)(stm->ostream,
1152 output_burst_size * 3);
1153 if (res < 0) {
1154 LOG("AAudioStream_setBufferSizeInFrames error (ostream): %s",
1155 WRAP(AAudio_convertResultToText)(res));
1156 // Not fatal
1157 }
1158
1159 int rate = WRAP(AAudioStream_getSampleRate)(stm->ostream);
1160 LOG("AAudio output stream sharing mode: %d",
1161 WRAP(AAudioStream_getSharingMode)(stm->ostream));
1162 LOG("AAudio output stream performance mode: %d",
1163 WRAP(AAudioStream_getPerformanceMode)(stm->ostream));
1164 LOG("AAudio output stream buffer capacity: %d",
1165 WRAP(AAudioStream_getBufferCapacityInFrames)(stm->ostream));
1166 LOG("AAudio output stream buffer size: %d",
1167 WRAP(AAudioStream_getBufferSizeInFrames)(stm->ostream));
1168 LOG("AAudio output stream sample-rate: %d", rate);
1169
1170 stm->sample_rate = stm->output_stream_params->rate;
1171 out_params = *stm->output_stream_params;
1172 out_params.rate = rate;
1173
1174 stm->out_channels = stm->output_stream_params->channels;
1175 stm->out_format = stm->output_stream_params->format;
1176 stm->out_frame_size = frame_size;
1177 stm->volume.store(1.f);
1178 }
1179
1180 // input
1181 cubeb_stream_params in_params;
1182 if (stm->input_stream_params) {
1183 // Match what the OpenSL backend does for now, we could use UNPROCESSED and
1184 // VOICE_COMMUNICATION here, but we'd need to make it clear that
1185 // application-level AEC and other voice processing should be disabled
1186 // there.
1187 int input_preset = stm->voice_input ? AAUDIO_INPUT_PRESET_VOICE_RECOGNITION
1188 : AAUDIO_INPUT_PRESET_CAMCORDER;
1189 WRAP(AAudioStreamBuilder_setInputPreset)(sb, input_preset);
1190 WRAP(AAudioStreamBuilder_setDirection)(sb, AAUDIO_DIRECTION_INPUT);
1191 WRAP(AAudioStreamBuilder_setDataCallback)(sb, in_data_callback, stm);
1192 assert(stm->latency_frames < std::numeric_limits<int32_t>::max());
1193 LOG("Frames per callback set to %d for input", stm->latency_frames);
1194 WRAP(AAudioStreamBuilder_setFramesPerDataCallback)
1195 (sb, static_cast<int32_t>(stm->latency_frames));
1196 int res_err = realize_stream(sb, stm->input_stream_params.get(),
1197 &stm->istream, &frame_size);
1198 if (res_err) {
1199 return res_err;
1200 }
1201
1202 int32_t input_burst_size =
1203 WRAP(AAudioStream_getFramesPerBurst)(stm->istream);
1204 LOG("AAudio input burst size: %d", input_burst_size);
1205 // 3 times the burst size seems to be robust.
1206 res = WRAP(AAudioStream_setBufferSizeInFrames)(stm->istream,
1207 input_burst_size * 3);
1208 if (res < AAUDIO_OK) {
1209 LOG("AAudioStream_setBufferSizeInFrames error (istream): %s",
1210 WRAP(AAudio_convertResultToText)(res));
1211 // Not fatal
1212 }
1213
1214 int bcap = WRAP(AAudioStream_getBufferCapacityInFrames)(stm->istream);
1215 int rate = WRAP(AAudioStream_getSampleRate)(stm->istream);
1216 LOG("AAudio input stream sharing mode: %d",
1217 WRAP(AAudioStream_getSharingMode)(stm->istream));
1218 LOG("AAudio input stream performance mode: %d",
1219 WRAP(AAudioStream_getPerformanceMode)(stm->istream));
1220 LOG("AAudio input stream buffer capacity: %d", bcap);
1221 LOG("AAudio input stream buffer size: %d",
1222 WRAP(AAudioStream_getBufferSizeInFrames)(stm->istream));
1223 LOG("AAudio input stream buffer rate: %d", rate);
1224
1225 stm->in_buf.resize(bcap * frame_size);
1226 assert(!stm->sample_rate ||
1227 stm->sample_rate == stm->input_stream_params->rate);
1228
1229 stm->sample_rate = stm->input_stream_params->rate;
1230 in_params = *stm->input_stream_params;
1231 in_params.rate = rate;
1232 stm->in_frame_size = frame_size;
1233 }
1234
1235 // initialize resampler
1236 stm->resampler = cubeb_resampler_create(
1237 stm, stm->input_stream_params ? &in_params : nullptr,
1238 stm->output_stream_params ? &out_params : nullptr, stm->sample_rate,
1239 stm->data_callback, stm->user_ptr, CUBEB_RESAMPLER_QUALITY_DEFAULT,
1240 CUBEB_RESAMPLER_RECLOCK_NONE);
1241
1242 if (!stm->resampler) {
1243 LOG("Failed to create resampler");
1244 return CUBEB_ERROR;
1245 }
1246
1247 // the stream isn't started initially. We don't need to differentiate
1248 // between a stream that was just initialized and one that played
1249 // already but was stopped.
1250 stm->state.store(stream_state::STOPPED);
1251 LOG("Cubeb stream (%p) INIT success", (void *)stm);
1252 return CUBEB_OK;
1253 }
1254
1255 static int
1256 aaudio_stream_init(cubeb * ctx, cubeb_stream ** stream,
1257 char const * /* stream_name */, cubeb_devid input_device,
1258 cubeb_stream_params * input_stream_params,
1259 cubeb_devid output_device,
1260 cubeb_stream_params * output_stream_params,
1261 unsigned int latency_frames,
1262 cubeb_data_callback data_callback,
1263 cubeb_state_callback state_callback, void * user_ptr)
1264 {
1265 assert(!input_device);
1266 assert(!output_device);
1267
1268 // atomically find a free stream.
1269 cubeb_stream * stm = nullptr;
1270 unique_lock<mutex> lock;
1271 for (auto & stream : ctx->streams) {
1272 // This check is only an optimization, we don't strictly need it
1273 // since we check again after locking the mutex.
1274 if (stream.in_use.load()) {
1275 continue;
1276 }
1277
1278 // if this fails, another thread initialized this stream
1279 // between our check of in_use and this.
1280 lock = unique_lock(stream.mutex, std::try_to_lock);
1281 if (!lock.owns_lock()) {
1282 continue;
1283 }
1284
1285 if (stream.in_use.load()) {
1286 lock = {};
1287 continue;
1288 }
1289
1290 stm = &stream;
1291 break;
1292 }
1293
1294 if (!stm) {
1295 LOG("Error: maximum number of streams reached");
1296 return CUBEB_ERROR;
1297 }
1298
1299 stm->in_use.store(true);
1300 stm->context = ctx;
1301 stm->user_ptr = user_ptr;
1302 stm->data_callback = data_callback;
1303 stm->state_callback = state_callback;
1304 stm->voice_input = input_stream_params &&
1305 !!(input_stream_params->prefs & CUBEB_STREAM_PREF_VOICE);
1306 stm->voice_output = output_stream_params &&
1307 !!(output_stream_params->prefs & CUBEB_STREAM_PREF_VOICE);
1308 stm->previous_clock = 0;
1309 stm->latency_frames = latency_frames;
1310 if (output_stream_params) {
1311 stm->output_stream_params = std::make_unique<cubeb_stream_params>();
1312 *(stm->output_stream_params) = *output_stream_params;
1313 }
1314 if (input_stream_params) {
1315 stm->input_stream_params = std::make_unique<cubeb_stream_params>();
1316 *(stm->input_stream_params) = *input_stream_params;
1317 }
1318
1319 LOG("cubeb stream prefs: voice_input: %s voice_output: %s",
1320 stm->voice_input ? "true" : "false",
1321 stm->voice_output ? "true" : "false");
1322
1323 // This is ok: the thread is marked as being in use
1324 lock.unlock();
1325 int err;
1326
1327 {
1328 lock_guard guard(stm->mutex);
1329 err = aaudio_stream_init_impl(stm, guard);
1330 }
1331
1332 if (err != CUBEB_OK) {
1333 aaudio_stream_destroy(stm);
1334 return err;
1335 }
1336
1337 *stream = stm;
1338 return CUBEB_OK;
1339 }
1340
1341 static int
1342 aaudio_stream_start(cubeb_stream * stm)
1343 {
1344 lock_guard lock(stm->mutex);
1345 return aaudio_stream_start_locked(stm, lock);
1346 }
1347
1348 static int
1349 aaudio_stream_start_locked(cubeb_stream * stm, lock_guard<mutex> & lock)
1350 {
1351 assert(stm && stm->in_use.load());
1352 stream_state state = stm->state.load();
1353 int istate = stm->istream ? WRAP(AAudioStream_getState)(stm->istream) : 0;
1354 int ostate = stm->ostream ? WRAP(AAudioStream_getState)(stm->ostream) : 0;
1355 LOGV("STARTING stream %p: %d (%d %d)", (void *)stm, state, istate, ostate);
1356
1357 switch (state) {
1358 case stream_state::STARTED:
1359 case stream_state::STARTING:
1360 LOG("cubeb stream %p already STARTING/STARTED", (void *)stm);
1361 return CUBEB_OK;
1362 case stream_state::ERROR:
1363 case stream_state::SHUTDOWN:
1364 return CUBEB_ERROR;
1365 case stream_state::INIT:
1366 assert(false && "Invalid stream");
1367 return CUBEB_ERROR;
1368 case stream_state::STOPPED:
1369 case stream_state::STOPPING:
1370 case stream_state::DRAINING:
1371 break;
1372 }
1373
1374 aaudio_result_t res;
1375
1376 // Important to start istream before ostream.
1377 // As soon as we start ostream, the callbacks might be triggered an we
1378 // might read from istream (on duplex). If istream wasn't started yet
1379 // this is a problem.
1380 if (stm->istream) {
1381 res = WRAP(AAudioStream_requestStart)(stm->istream);
1382 if (res != AAUDIO_OK) {
1383 LOG("AAudioStream_requestStart (istream): %s",
1384 WRAP(AAudio_convertResultToText)(res));
1385 stm->state.store(stream_state::ERROR);
1386 return CUBEB_ERROR;
1387 }
1388 }
1389
1390 if (stm->ostream) {
1391 res = WRAP(AAudioStream_requestStart)(stm->ostream);
1392 if (res != AAUDIO_OK) {
1393 LOG("AAudioStream_requestStart (ostream): %s",
1394 WRAP(AAudio_convertResultToText)(res));
1395 stm->state.store(stream_state::ERROR);
1396 return CUBEB_ERROR;
1397 }
1398 }
1399
1400 int ret = CUBEB_OK;
1401 bool success;
1402
1403 while (!(success = stm->state.compare_exchange_strong(
1404 state, stream_state::STARTING))) {
1405 // we land here only if the state has changed in the meantime
1406 switch (state) {
1407 // If an error ocurred in the meantime, we can't change that.
1408 // The stream will be stopped when shut down.
1409 case stream_state::ERROR:
1410 ret = CUBEB_ERROR;
1411 break;
1412 // The only situation in which the state could have switched to draining
1413 // is if the callback was already fired and requested draining. Don't
1414 // overwrite that. It's not an error either though.
1415 case stream_state::DRAINING:
1416 break;
1417
1418 // If the state switched [DRAINING -> STOPPING] or [DRAINING/STOPPING ->
1419 // STOPPED] in the meantime, we can simply overwrite that since we
1420 // restarted the stream.
1421 case stream_state::STOPPING:
1422 case stream_state::STOPPED:
1423 continue;
1424
1425 // There is no situation in which the state could have been valid before
1426 // but now in shutdown mode, since we hold the streams mutex.
1427 // There is also no way that it switched *into* STARTING or
1428 // STARTED mode.
1429 default:
1430 assert(false && "Invalid state change");
1431 ret = CUBEB_ERROR;
1432 break;
1433 }
1434
1435 break;
1436 }
1437
1438 if (success) {
1439 stm->context->state.waiting.store(true);
1440 stm->context->state.cond.notify_one();
1441 }
1442
1443 return ret;
1444 }
1445
1446 static int
1447 aaudio_stream_stop(cubeb_stream * stm)
1448 {
1449 assert(stm && stm->in_use.load());
1450 lock_guard lock(stm->mutex);
1451 return aaudio_stream_stop_locked(stm, lock);
1452 }
1453
1454 static int
1455 aaudio_stream_stop_locked(cubeb_stream * stm, lock_guard<mutex> & lock)
1456 {
1457 assert(stm && stm->in_use.load());
1458
1459 stream_state state = stm->state.load();
1460 int istate = stm->istream ? WRAP(AAudioStream_getState)(stm->istream) : 0;
1461 int ostate = stm->ostream ? WRAP(AAudioStream_getState)(stm->ostream) : 0;
1462 LOG("STOPPING stream %p: %d (%d %d)", (void *)stm, state, istate, ostate);
1463
1464 switch (state) {
1465 case stream_state::STOPPED:
1466 case stream_state::STOPPING:
1467 case stream_state::DRAINING:
1468 LOG("cubeb stream %p already STOPPING/STOPPED", (void *)stm);
1469 return CUBEB_OK;
1470 case stream_state::ERROR:
1471 case stream_state::SHUTDOWN:
1472 return CUBEB_ERROR;
1473 case stream_state::INIT:
1474 assert(false && "Invalid stream");
1475 return CUBEB_ERROR;
1476 case stream_state::STARTED:
1477 case stream_state::STARTING:
1478 break;
1479 }
1480
1481 aaudio_result_t res;
1482
1483 // No callbacks are triggered anymore when requestStop returns.
1484 // That is important as we otherwise might read from a closed istream
1485 // for a duplex stream.
1486 // Therefor it is important to close ostream first.
1487 if (stm->ostream) {
1488 // Could use pause + flush here as well, the public cubeb interface
1489 // doesn't state behavior.
1490 res = WRAP(AAudioStream_requestStop)(stm->ostream);
1491 if (res != AAUDIO_OK) {
1492 LOG("AAudioStream_requestStop (ostream): %s",
1493 WRAP(AAudio_convertResultToText)(res));
1494 stm->state.store(stream_state::ERROR);
1495 return CUBEB_ERROR;
1496 }
1497 }
1498
1499 if (stm->istream) {
1500 res = WRAP(AAudioStream_requestStop)(stm->istream);
1501 if (res != AAUDIO_OK) {
1502 LOG("AAudioStream_requestStop (istream): %s",
1503 WRAP(AAudio_convertResultToText)(res));
1504 stm->state.store(stream_state::ERROR);
1505 return CUBEB_ERROR;
1506 }
1507 }
1508
1509 int ret = CUBEB_OK;
1510 bool success;
1511 while (!(success = atomic_compare_exchange_strong(&stm->state, &state,
1512 stream_state::STOPPING))) {
1513 // we land here only if the state has changed in the meantime
1514 switch (state) {
1515 // If an error ocurred in the meantime, we can't change that.
1516 // The stream will be STOPPED when shut down.
1517 case stream_state::ERROR:
1518 ret = CUBEB_ERROR;
1519 break;
1520 // If it was switched to DRAINING in the meantime, it was or
1521 // will be STOPPED soon anyways. We don't interfere with
1522 // the DRAINING process, no matter in which state.
1523 // Not an error
1524 case stream_state::DRAINING:
1525 case stream_state::STOPPING:
1526 case stream_state::STOPPED:
1527 break;
1528
1529 // If the state switched from STARTING to STARTED in the meantime
1530 // we can simply overwrite that since we just STOPPED it.
1531 case stream_state::STARTED:
1532 continue;
1533
1534 // There is no situation in which the state could have been valid before
1535 // but now in shutdown mode, since we hold the streams mutex.
1536 // There is also no way that it switched *into* STARTING mode.
1537 default:
1538 assert(false && "Invalid state change");
1539 ret = CUBEB_ERROR;
1540 break;
1541 }
1542
1543 break;
1544 }
1545
1546 if (success) {
1547 stm->context->state.waiting.store(true);
1548 stm->context->state.cond.notify_one();
1549 }
1550
1551 return ret;
1552 }
1553
1554 static int
1555 aaudio_stream_get_position(cubeb_stream * stm, uint64_t * position)
1556 {
1557 assert(stm && stm->in_use.load());
1558 lock_guard lock(stm->mutex);
1559
1560 stream_state state = stm->state.load();
1561 AAudioStream * stream = stm->ostream ? stm->ostream : stm->istream;
1562 switch (state) {
1563 case stream_state::ERROR:
1564 case stream_state::SHUTDOWN:
1565 return CUBEB_ERROR;
1566 case stream_state::DRAINING:
1567 case stream_state::STOPPED:
1568 case stream_state::STOPPING:
1569 // getTimestamp is only valid when the stream is playing.
1570 // Simply return the number of frames passed to aaudio
1571 *position = WRAP(AAudioStream_getFramesRead)(stream);
1572 if (*position < stm->previous_clock) {
1573 *position = stm->previous_clock;
1574 } else {
1575 stm->previous_clock = *position;
1576 }
1577 return CUBEB_OK;
1578 case stream_state::INIT:
1579 assert(false && "Invalid stream");
1580 return CUBEB_ERROR;
1581 case stream_state::STARTED:
1582 case stream_state::STARTING:
1583 break;
1584 }
1585
1586 // No callback yet, the stream hasn't really started.
1587 if (stm->previous_clock == 0 && !stm->timing_info.updated()) {
1588 LOG("Not timing info yet");
1589 *position = 0;
1590 return CUBEB_OK;
1591 }
1592
1593 AAudioTimingInfo info = stm->timing_info.read();
1594 LOGV("AAudioTimingInfo idx:%lu tstamp:%lu latency:%u",
1595 info.output_frame_index, info.tstamp, info.output_latency);
1596 // Interpolate client side since the last callback.
1597 uint64_t interpolation =
1598 stm->sample_rate * (now_ns() - info.tstamp) / NS_PER_S;
1599 *position = info.output_frame_index + interpolation - info.output_latency;
1600 if (*position < stm->previous_clock) {
1601 *position = stm->previous_clock;
1602 } else {
1603 stm->previous_clock = *position;
1604 }
1605
1606 LOG("aaudio_stream_get_position: %" PRIu64 " frames", *position);
1607
1608 return CUBEB_OK;
1609 }
1610
1611 static int
1612 aaudio_stream_get_latency(cubeb_stream * stm, uint32_t * latency)
1613 {
1614 if (!stm->ostream) {
1615 LOG("error: aaudio_stream_get_latency on input-only stream");
1616 return CUBEB_ERROR;
1617 }
1618
1619 if (!stm->latency_metrics_available) {
1620 LOG("Not timing info yet (output)");
1621 return CUBEB_OK;
1622 }
1623
1624 AAudioTimingInfo info = stm->timing_info.read();
1625
1626 *latency = info.output_latency;
1627 LOG("aaudio_stream_get_latency, %u frames", *latency);
1628
1629 return CUBEB_OK;
1630 }
1631
1632 static int
1633 aaudio_stream_get_input_latency(cubeb_stream * stm, uint32_t * latency)
1634 {
1635 if (!stm->istream) {
1636 LOG("error: aaudio_stream_get_input_latency on an output-only stream");
1637 return CUBEB_ERROR;
1638 }
1639
1640 if (!stm->latency_metrics_available) {
1641 LOG("Not timing info yet (input)");
1642 return CUBEB_OK;
1643 }
1644
1645 AAudioTimingInfo info = stm->timing_info.read();
1646
1647 *latency = info.input_latency;
1648 LOG("aaudio_stream_get_latency, %u frames", *latency);
1649
1650 return CUBEB_OK;
1651 }
1652
1653 static int
1654 aaudio_stream_set_volume(cubeb_stream * stm, float volume)
1655 {
1656 assert(stm && stm->in_use.load() && stm->ostream);
1657 stm->volume.store(volume);
1658 return CUBEB_OK;
1659 }
1660
1661 aaudio_data_callback_result_t
1662 dummy_callback(AAudioStream * stream, void * userData, void * audioData,
1663 int32_t numFrames)
1664 {
1665 return AAUDIO_CALLBACK_RESULT_STOP;
1666 }
1667
1668 // Returns a dummy stream with all default settings
1669 static AAudioStream *
1670 init_dummy_stream()
1671 {
1672 AAudioStreamBuilder * streamBuilder;
1673 aaudio_result_t res;
1674 res = WRAP(AAudio_createStreamBuilder)(&streamBuilder);
1675 if (res != AAUDIO_OK) {
1676 LOG("init_dummy_stream: AAudio_createStreamBuilder: %s",
1677 WRAP(AAudio_convertResultToText)(res));
1678 return nullptr;
1679 }
1680 WRAP(AAudioStreamBuilder_setDataCallback)
1681 (streamBuilder, dummy_callback, nullptr);
1682 WRAP(AAudioStreamBuilder_setPerformanceMode)
1683 (streamBuilder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
1684
1685 AAudioStream * stream;
1686 res = WRAP(AAudioStreamBuilder_openStream)(streamBuilder, &stream);
1687 if (res != AAUDIO_OK) {
1688 LOG("init_dummy_stream: AAudioStreamBuilder_openStream %s",
1689 WRAP(AAudio_convertResultToText)(res));
1690 return nullptr;
1691 }
1692 WRAP(AAudioStreamBuilder_delete)(streamBuilder);
1693
1694 return stream;
1695 }
1696
1697 static void
1698 destroy_dummy_stream(AAudioStream * stream)
1699 {
1700 WRAP(AAudioStream_close)(stream);
1701 }
1702
1703 static int
1704 aaudio_get_min_latency(cubeb * ctx, cubeb_stream_params params,
1705 uint32_t * latency_frames)
1706 {
1707 AAudioStream * stream = init_dummy_stream();
1708
1709 if (!stream) {
1710 return CUBEB_ERROR;
1711 }
1712
1713 // https://android.googlesource.com/platform/compatibility/cdd/+/refs/heads/master/5_multimedia/5_6_audio-latency.md
1714 *latency_frames = WRAP(AAudioStream_getFramesPerBurst)(stream);
1715
1716 LOG("aaudio_get_min_latency: %u frames", *latency_frames);
1717
1718 destroy_dummy_stream(stream);
1719
1720 return CUBEB_OK;
1721 }
1722
1723 int
1724 aaudio_get_preferred_sample_rate(cubeb * ctx, uint32_t * rate)
1725 {
1726 AAudioStream * stream = init_dummy_stream();
1727
1728 if (!stream) {
1729 return CUBEB_ERROR;
1730 }
1731
1732 *rate = WRAP(AAudioStream_getSampleRate)(stream);
1733
1734 LOG("aaudio_get_preferred_sample_rate %uHz", *rate);
1735
1736 destroy_dummy_stream(stream);
1737
1738 return CUBEB_OK;
1739 }
1740
1741 extern "C" int
1742 aaudio_init(cubeb ** context, char const * context_name);
1743
1744 const static struct cubeb_ops aaudio_ops = {
1745 /*.init =*/aaudio_init,
1746 /*.get_backend_id =*/aaudio_get_backend_id,
1747 /*.get_max_channel_count =*/aaudio_get_max_channel_count,
1748 /* .get_min_latency =*/aaudio_get_min_latency,
1749 /*.get_preferred_sample_rate =*/aaudio_get_preferred_sample_rate,
1750 /*.get_supported_input_processing_params =*/nullptr,
1751 /*.enumerate_devices =*/nullptr,
1752 /*.device_collection_destroy =*/nullptr,
1753 /*.destroy =*/aaudio_destroy,
1754 /*.stream_init =*/aaudio_stream_init,
1755 /*.stream_destroy =*/aaudio_stream_destroy,
1756 /*.stream_start =*/aaudio_stream_start,
1757 /*.stream_stop =*/aaudio_stream_stop,
1758 /*.stream_get_position =*/aaudio_stream_get_position,
1759 /*.stream_get_latency =*/aaudio_stream_get_latency,
1760 /*.stream_get_input_latency =*/aaudio_stream_get_input_latency,
1761 /*.stream_set_volume =*/aaudio_stream_set_volume,
1762 /*.stream_set_name =*/nullptr,
1763 /*.stream_get_current_device =*/nullptr,
1764 /*.stream_set_input_mute =*/nullptr,
1765 /*.stream_set_input_processing_params =*/nullptr,
1766 /*.stream_device_destroy =*/nullptr,
1767 /*.stream_register_device_changed_callback =*/nullptr,
1768 /*.register_device_collection_changed =*/nullptr};
1769
1770 extern "C" /*static*/ int
1771 aaudio_init(cubeb ** context, char const * /* context_name */)
1772 {
1773 // load api
1774 void * libaaudio = nullptr;
1775 #ifndef DISABLE_LIBAAUDIO_DLOPEN
1776 libaaudio = dlopen("libaaudio.so", RTLD_NOW);
1777 if (!libaaudio) {
1778 return CUBEB_ERROR;
1779 }
1780
1781 #define LOAD(x) \
1782 { \
1783 cubeb_##x = (decltype(x) *)(dlsym(libaaudio, #x)); \
1784 if (!WRAP(x)) { \
1785 LOG("AAudio: Failed to load %s", #x); \
1786 dlclose(libaaudio); \
1787 return CUBEB_ERROR; \
1788 } \
1789 }
1790
1791 LIBAAUDIO_API_VISIT(LOAD);
1792 #undef LOAD
1793 #endif
1794
1795 cubeb * ctx = new cubeb;
1796 ctx->ops = &aaudio_ops;
1797 ctx->libaaudio = libaaudio;
1798
1799 ctx->state.thread = std::thread(state_thread, ctx);
1800
1801 // NOTE: using platform-specific APIs we could set the priority of the
1802 // notifier thread lower than the priority of the state thread.
1803 // This way, it's more likely that the state thread will be woken up
1804 // by the condition variable signal when both are currently waiting
1805 ctx->state.notifier = std::thread(notifier_thread, ctx);
1806
1807 *context = ctx;
1808 return CUBEB_OK;
1809 }