1 /*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <cassert>
18 #include <stdint.h>
19 #include <stdlib.h>
20
21 #include "aaudio/AAudioLoader.h"
22 #include "aaudio/AudioStreamAAudio.h"
23 #include "common/AudioClock.h"
24 #include "common/OboeDebug.h"
25 #include "oboe/Utilities.h"
26 #include "AAudioExtensions.h"
27
28 #ifdef __ANDROID__
29 #include <sys/system_properties.h>
30 #include <common/QuirksManager.h>
31
32 #endif
33
34 #ifndef OBOE_FIX_FORCE_STARTING_TO_STARTED
35 // Workaround state problems in AAudio
36 // TODO Which versions does this occur in? Verify fixed in Q.
37 #define OBOE_FIX_FORCE_STARTING_TO_STARTED 1
38 #endif // OBOE_FIX_FORCE_STARTING_TO_STARTED
39
40 using namespace oboe;
41 AAudioLoader *AudioStreamAAudio::mLibLoader = nullptr;
42
43 // 'C' wrapper for the data callback method
oboe_aaudio_data_callback_proc(AAudioStream * stream,void * userData,void * audioData,int32_t numFrames)44 static aaudio_data_callback_result_t oboe_aaudio_data_callback_proc(
45 AAudioStream *stream,
46 void *userData,
47 void *audioData,
48 int32_t numFrames) {
49
50 AudioStreamAAudio *oboeStream = reinterpret_cast<AudioStreamAAudio*>(userData);
51 if (oboeStream != nullptr) {
52 return static_cast<aaudio_data_callback_result_t>(
53 oboeStream->callOnAudioReady(stream, audioData, numFrames));
54
55 } else {
56 return static_cast<aaudio_data_callback_result_t>(DataCallbackResult::Stop);
57 }
58 }
59
60 // This runs in its own thread.
61 // Only one of these threads will be launched from internalErrorCallback().
62 // It calls app error callbacks from a static function in case the stream gets deleted.
oboe_aaudio_error_thread_proc(AudioStreamAAudio * oboeStream,Result error)63 static void oboe_aaudio_error_thread_proc(AudioStreamAAudio *oboeStream,
64 Result error) {
65 LOGD("%s(,%d) - entering >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", __func__, error);
66 AudioStreamErrorCallback *errorCallback = oboeStream->getErrorCallback();
67 if (errorCallback == nullptr) return; // should be impossible
68 bool isErrorHandled = errorCallback->onError(oboeStream, error);
69
70 if (!isErrorHandled) {
71 oboeStream->requestStop();
72 errorCallback->onErrorBeforeClose(oboeStream, error);
73 oboeStream->close();
74 // Warning, oboeStream may get deleted by this callback.
75 errorCallback->onErrorAfterClose(oboeStream, error);
76 }
77 LOGD("%s() - exiting <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", __func__);
78 }
79
80 // This runs in its own thread.
81 // Only one of these threads will be launched from internalErrorCallback().
82 // Prevents deletion of the stream if the app is using AudioStreamBuilder::openSharedStream()
oboe_aaudio_error_thread_proc_shared(std::shared_ptr<AudioStream> sharedStream,Result error)83 static void oboe_aaudio_error_thread_proc_shared(std::shared_ptr<AudioStream> sharedStream,
84 Result error) {
85 AudioStreamAAudio *oboeStream = reinterpret_cast<AudioStreamAAudio*>(sharedStream.get());
86 oboe_aaudio_error_thread_proc(oboeStream, error);
87 }
88
89 namespace oboe {
90
91 /*
92 * Create a stream that uses Oboe Audio API.
93 */
AudioStreamAAudio(const AudioStreamBuilder & builder)94 AudioStreamAAudio::AudioStreamAAudio(const AudioStreamBuilder &builder)
95 : AudioStream(builder)
96 , mAAudioStream(nullptr) {
97 mCallbackThreadEnabled.store(false);
98 mLibLoader = AAudioLoader::getInstance();
99 }
100
isSupported()101 bool AudioStreamAAudio::isSupported() {
102 mLibLoader = AAudioLoader::getInstance();
103 int openResult = mLibLoader->open();
104 return openResult == 0;
105 }
106
107 // Static method for the error callback.
108 // We use a method so we can access protected methods on the stream.
109 // Launch a thread to handle the error.
110 // That other thread can safely stop, close and delete the stream.
internalErrorCallback(AAudioStream * stream,void * userData,aaudio_result_t error)111 void AudioStreamAAudio::internalErrorCallback(
112 AAudioStream *stream,
113 void *userData,
114 aaudio_result_t error) {
115 oboe::Result oboeResult = static_cast<Result>(error);
116 AudioStreamAAudio *oboeStream = reinterpret_cast<AudioStreamAAudio*>(userData);
117
118 // Coerce the error code if needed to workaround a regression in RQ1A that caused
119 // the wrong code to be passed when headsets plugged in. See b/173928197.
120 if (OboeGlobals::areWorkaroundsEnabled()
121 && getSdkVersion() == __ANDROID_API_R__
122 && oboeResult == oboe::Result::ErrorTimeout) {
123 oboeResult = oboe::Result::ErrorDisconnected;
124 LOGD("%s() ErrorTimeout changed to ErrorDisconnected to fix b/173928197", __func__);
125 }
126
127 oboeStream->mErrorCallbackResult = oboeResult;
128
129 // Prevents deletion of the stream if the app is using AudioStreamBuilder::openStream(shared_ptr)
130 std::shared_ptr<AudioStream> sharedStream = oboeStream->lockWeakThis();
131
132 // These checks should be enough because we assume that the stream close()
133 // will join() any active callback threads and will not allow new callbacks.
134 if (oboeStream->wasErrorCallbackCalled()) { // block extra error callbacks
135 LOGE("%s() multiple error callbacks called!", __func__);
136 } else if (stream != oboeStream->getUnderlyingStream()) {
137 LOGW("%s() stream already closed or closing", __func__); // might happen if there are bugs
138 } else if (sharedStream) {
139 // Handle error on a separate thread using shared pointer.
140 std::thread t(oboe_aaudio_error_thread_proc_shared, sharedStream, oboeResult);
141 t.detach();
142 } else {
143 // Handle error on a separate thread.
144 std::thread t(oboe_aaudio_error_thread_proc, oboeStream, oboeResult);
145 t.detach();
146 }
147 }
148
logUnsupportedAttributes()149 void AudioStreamAAudio::logUnsupportedAttributes() {
150 int sdkVersion = getSdkVersion();
151
152 // These attributes are not supported pre Android "P"
153 if (sdkVersion < __ANDROID_API_P__) {
154 if (mUsage != Usage::Media) {
155 LOGW("Usage [AudioStreamBuilder::setUsage()] "
156 "is not supported on AAudio streams running on pre-Android P versions.");
157 }
158
159 if (mContentType != ContentType::Music) {
160 LOGW("ContentType [AudioStreamBuilder::setContentType()] "
161 "is not supported on AAudio streams running on pre-Android P versions.");
162 }
163
164 if (mSessionId != SessionId::None) {
165 LOGW("SessionId [AudioStreamBuilder::setSessionId()] "
166 "is not supported on AAudio streams running on pre-Android P versions.");
167 }
168 }
169 }
170
open()171 Result AudioStreamAAudio::open() {
172 Result result = Result::OK;
173
174 if (mAAudioStream != nullptr) {
175 return Result::ErrorInvalidState;
176 }
177
178 result = AudioStream::open();
179 if (result != Result::OK) {
180 return result;
181 }
182
183 AAudioStreamBuilder *aaudioBuilder;
184 result = static_cast<Result>(mLibLoader->createStreamBuilder(&aaudioBuilder));
185 if (result != Result::OK) {
186 return result;
187 }
188
189 // Do not set INPUT capacity below 4096 because that prevents us from getting a FAST track
190 // when using the Legacy data path.
191 // If the app requests > 4096 then we allow it but we are less likely to get LowLatency.
192 // See internal bug b/80308183 for more details.
193 // Fixed in Q but let's still clip the capacity because high input capacity
194 // does not increase latency.
195 int32_t capacity = mBufferCapacityInFrames;
196 constexpr int kCapacityRequiredForFastLegacyTrack = 4096; // matches value in AudioFinger
197 if (OboeGlobals::areWorkaroundsEnabled()
198 && mDirection == oboe::Direction::Input
199 && capacity != oboe::Unspecified
200 && capacity < kCapacityRequiredForFastLegacyTrack
201 && mPerformanceMode == oboe::PerformanceMode::LowLatency) {
202 capacity = kCapacityRequiredForFastLegacyTrack;
203 LOGD("AudioStreamAAudio.open() capacity changed from %d to %d for lower latency",
204 static_cast<int>(mBufferCapacityInFrames), capacity);
205 }
206 mLibLoader->builder_setBufferCapacityInFrames(aaudioBuilder, capacity);
207
208 // Channel mask was added in SC_V2. Given the corresponding channel count of selected channel
209 // mask may be different from selected channel count, the last set value will be respected.
210 // If channel count is set after channel mask, the previously set channel mask will be cleared.
211 // If channel mask is set after channel count, the channel count will be automatically
212 // calculated from selected channel mask. In that case, only set channel mask when the API
213 // is available and the channel mask is specified.
214 if (mLibLoader->builder_setChannelMask != nullptr && mChannelMask != ChannelMask::Unspecified) {
215 mLibLoader->builder_setChannelMask(aaudioBuilder,
216 static_cast<aaudio_channel_mask_t>(mChannelMask));
217 } else {
218 mLibLoader->builder_setChannelCount(aaudioBuilder, mChannelCount);
219 }
220 mLibLoader->builder_setDeviceId(aaudioBuilder, mDeviceId);
221 mLibLoader->builder_setDirection(aaudioBuilder, static_cast<aaudio_direction_t>(mDirection));
222 mLibLoader->builder_setFormat(aaudioBuilder, static_cast<aaudio_format_t>(mFormat));
223 mLibLoader->builder_setSampleRate(aaudioBuilder, mSampleRate);
224 mLibLoader->builder_setSharingMode(aaudioBuilder,
225 static_cast<aaudio_sharing_mode_t>(mSharingMode));
226 mLibLoader->builder_setPerformanceMode(aaudioBuilder,
227 static_cast<aaudio_performance_mode_t>(mPerformanceMode));
228
229 // These were added in P so we have to check for the function pointer.
230 if (mLibLoader->builder_setUsage != nullptr) {
231 mLibLoader->builder_setUsage(aaudioBuilder,
232 static_cast<aaudio_usage_t>(mUsage));
233 }
234
235 if (mLibLoader->builder_setContentType != nullptr) {
236 mLibLoader->builder_setContentType(aaudioBuilder,
237 static_cast<aaudio_content_type_t>(mContentType));
238 }
239
240 if (mLibLoader->builder_setInputPreset != nullptr) {
241 aaudio_input_preset_t inputPreset = mInputPreset;
242 if (getSdkVersion() <= __ANDROID_API_P__ && inputPreset == InputPreset::VoicePerformance) {
243 LOGD("InputPreset::VoicePerformance not supported before Q. Using VoiceRecognition.");
244 inputPreset = InputPreset::VoiceRecognition; // most similar preset
245 }
246 mLibLoader->builder_setInputPreset(aaudioBuilder,
247 static_cast<aaudio_input_preset_t>(inputPreset));
248 }
249
250 if (mLibLoader->builder_setSessionId != nullptr) {
251 mLibLoader->builder_setSessionId(aaudioBuilder,
252 static_cast<aaudio_session_id_t>(mSessionId));
253 }
254
255 // These were added in S so we have to check for the function pointer.
256 if (mLibLoader->builder_setPackageName != nullptr && !mPackageName.empty()) {
257 mLibLoader->builder_setPackageName(aaudioBuilder,
258 mPackageName.c_str());
259 }
260
261 if (mLibLoader->builder_setAttributionTag != nullptr && !mAttributionTag.empty()) {
262 mLibLoader->builder_setAttributionTag(aaudioBuilder,
263 mAttributionTag.c_str());
264 }
265
266 if (isDataCallbackSpecified()) {
267 mLibLoader->builder_setDataCallback(aaudioBuilder, oboe_aaudio_data_callback_proc, this);
268 mLibLoader->builder_setFramesPerDataCallback(aaudioBuilder, getFramesPerDataCallback());
269
270 if (!isErrorCallbackSpecified()) {
271 // The app did not specify a callback so we should specify
272 // our own so the stream gets closed and stopped.
273 mErrorCallback = &mDefaultErrorCallback;
274 }
275 mLibLoader->builder_setErrorCallback(aaudioBuilder, internalErrorCallback, this);
276 }
277 // Else if the data callback is not being used then the write method will return an error
278 // and the app can stop and close the stream.
279
280 // ============= OPEN THE STREAM ================
281 {
282 AAudioStream *stream = nullptr;
283 result = static_cast<Result>(mLibLoader->builder_openStream(aaudioBuilder, &stream));
284 mAAudioStream.store(stream);
285 }
286 if (result != Result::OK) {
287 // Warn developer because ErrorInternal is not very informative.
288 if (result == Result::ErrorInternal && mDirection == Direction::Input) {
289 LOGW("AudioStreamAAudio.open() may have failed due to lack of "
290 "audio recording permission.");
291 }
292 goto error2;
293 }
294
295 // Query and cache the stream properties
296 mDeviceId = mLibLoader->stream_getDeviceId(mAAudioStream);
297 mChannelCount = mLibLoader->stream_getChannelCount(mAAudioStream);
298 mSampleRate = mLibLoader->stream_getSampleRate(mAAudioStream);
299 mFormat = static_cast<AudioFormat>(mLibLoader->stream_getFormat(mAAudioStream));
300 mSharingMode = static_cast<SharingMode>(mLibLoader->stream_getSharingMode(mAAudioStream));
301 mPerformanceMode = static_cast<PerformanceMode>(
302 mLibLoader->stream_getPerformanceMode(mAAudioStream));
303 mBufferCapacityInFrames = mLibLoader->stream_getBufferCapacity(mAAudioStream);
304 mBufferSizeInFrames = mLibLoader->stream_getBufferSize(mAAudioStream);
305 mFramesPerBurst = mLibLoader->stream_getFramesPerBurst(mAAudioStream);
306
307 // These were added in P so we have to check for the function pointer.
308 if (mLibLoader->stream_getUsage != nullptr) {
309 mUsage = static_cast<Usage>(mLibLoader->stream_getUsage(mAAudioStream));
310 }
311 if (mLibLoader->stream_getContentType != nullptr) {
312 mContentType = static_cast<ContentType>(mLibLoader->stream_getContentType(mAAudioStream));
313 }
314 if (mLibLoader->stream_getInputPreset != nullptr) {
315 mInputPreset = static_cast<InputPreset>(mLibLoader->stream_getInputPreset(mAAudioStream));
316 }
317 if (mLibLoader->stream_getSessionId != nullptr) {
318 mSessionId = static_cast<SessionId>(mLibLoader->stream_getSessionId(mAAudioStream));
319 } else {
320 mSessionId = SessionId::None;
321 }
322
323 if (mLibLoader->stream_getChannelMask != nullptr) {
324 mChannelMask = static_cast<ChannelMask>(mLibLoader->stream_getChannelMask(mAAudioStream));
325 }
326
327 LOGD("AudioStreamAAudio.open() format=%d, sampleRate=%d, capacity = %d",
328 static_cast<int>(mFormat), static_cast<int>(mSampleRate),
329 static_cast<int>(mBufferCapacityInFrames));
330
331 calculateDefaultDelayBeforeCloseMillis();
332
333 error2:
334 mLibLoader->builder_delete(aaudioBuilder);
335 LOGD("AudioStreamAAudio.open: AAudioStream_Open() returned %s",
336 mLibLoader->convertResultToText(static_cast<aaudio_result_t>(result)));
337 return result;
338 }
339
close()340 Result AudioStreamAAudio::close() {
341 // Prevent two threads from closing the stream at the same time and crashing.
342 // This could occur, for example, if an application called close() at the same
343 // time that an onError callback was being executed because of a disconnect.
344 std::lock_guard<std::mutex> lock(mLock);
345
346 AudioStream::close();
347
348 AAudioStream *stream = nullptr;
349 {
350 // Wait for any methods using mAAudioStream to finish.
351 std::unique_lock<std::shared_mutex> lock2(mAAudioStreamLock);
352 // Closing will delete *mAAudioStream so we need to null out the pointer atomically.
353 stream = mAAudioStream.exchange(nullptr);
354 }
355 if (stream != nullptr) {
356 if (OboeGlobals::areWorkaroundsEnabled()) {
357 // Make sure we are really stopped. Do it under mLock
358 // so another thread cannot call requestStart() right before the close.
359 requestStop_l(stream);
360 sleepBeforeClose();
361 }
362 return static_cast<Result>(mLibLoader->stream_close(stream));
363 } else {
364 return Result::ErrorClosed;
365 }
366 }
367
oboe_stop_thread_proc(AudioStream * oboeStream)368 static void oboe_stop_thread_proc(AudioStream *oboeStream) {
369 if (oboeStream != nullptr) {
370 oboeStream->requestStop();
371 }
372 }
373
launchStopThread()374 void AudioStreamAAudio::launchStopThread() {
375 // Prevent multiple stop threads from being launched.
376 if (mStopThreadAllowed.exchange(false)) {
377 // Stop this stream on a separate thread
378 std::thread t(oboe_stop_thread_proc, this);
379 t.detach();
380 }
381 }
382
callOnAudioReady(AAudioStream *,void * audioData,int32_t numFrames)383 DataCallbackResult AudioStreamAAudio::callOnAudioReady(AAudioStream * /*stream*/,
384 void *audioData,
385 int32_t numFrames) {
386 DataCallbackResult result = fireDataCallback(audioData, numFrames);
387 if (result == DataCallbackResult::Continue) {
388 return result;
389 } else {
390 if (result == DataCallbackResult::Stop) {
391 LOGD("Oboe callback returned DataCallbackResult::Stop");
392 } else {
393 LOGE("Oboe callback returned unexpected value = %d", result);
394 }
395
396 // Returning Stop caused various problems before S. See #1230
397 if (OboeGlobals::areWorkaroundsEnabled() && getSdkVersion() <= __ANDROID_API_R__) {
398 launchStopThread();
399 return DataCallbackResult::Continue;
400 } else {
401 return DataCallbackResult::Stop; // OK >= API_S
402 }
403 }
404 }
405
requestStart()406 Result AudioStreamAAudio::requestStart() {
407 std::lock_guard<std::mutex> lock(mLock);
408 AAudioStream *stream = mAAudioStream.load();
409 if (stream != nullptr) {
410 // Avoid state machine errors in O_MR1.
411 if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
412 StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
413 if (state == StreamState::Starting || state == StreamState::Started) {
414 // WARNING: On P, AAudio is returning ErrorInvalidState for Output and OK for Input.
415 return Result::OK;
416 }
417 }
418 if (isDataCallbackSpecified()) {
419 setDataCallbackEnabled(true);
420 }
421 mStopThreadAllowed = true;
422 return static_cast<Result>(mLibLoader->stream_requestStart(stream));
423 } else {
424 return Result::ErrorClosed;
425 }
426 }
427
requestPause()428 Result AudioStreamAAudio::requestPause() {
429 std::lock_guard<std::mutex> lock(mLock);
430 AAudioStream *stream = mAAudioStream.load();
431 if (stream != nullptr) {
432 // Avoid state machine errors in O_MR1.
433 if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
434 StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
435 if (state == StreamState::Pausing || state == StreamState::Paused) {
436 return Result::OK;
437 }
438 }
439 return static_cast<Result>(mLibLoader->stream_requestPause(stream));
440 } else {
441 return Result::ErrorClosed;
442 }
443 }
444
requestFlush()445 Result AudioStreamAAudio::requestFlush() {
446 std::lock_guard<std::mutex> lock(mLock);
447 AAudioStream *stream = mAAudioStream.load();
448 if (stream != nullptr) {
449 // Avoid state machine errors in O_MR1.
450 if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
451 StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
452 if (state == StreamState::Flushing || state == StreamState::Flushed) {
453 return Result::OK;
454 }
455 }
456 return static_cast<Result>(mLibLoader->stream_requestFlush(stream));
457 } else {
458 return Result::ErrorClosed;
459 }
460 }
461
requestStop()462 Result AudioStreamAAudio::requestStop() {
463 std::lock_guard<std::mutex> lock(mLock);
464 AAudioStream *stream = mAAudioStream.load();
465 if (stream != nullptr) {
466 return requestStop_l(stream);
467 } else {
468 return Result::ErrorClosed;
469 }
470 }
471
472 // Call under mLock
requestStop_l(AAudioStream * stream)473 Result AudioStreamAAudio::requestStop_l(AAudioStream *stream) {
474 // Avoid state machine errors in O_MR1.
475 if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
476 StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
477 if (state == StreamState::Stopping || state == StreamState::Stopped) {
478 return Result::OK;
479 }
480 }
481 return static_cast<Result>(mLibLoader->stream_requestStop(stream));
482 }
483
write(const void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)484 ResultWithValue<int32_t> AudioStreamAAudio::write(const void *buffer,
485 int32_t numFrames,
486 int64_t timeoutNanoseconds) {
487 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
488 AAudioStream *stream = mAAudioStream.load();
489 if (stream != nullptr) {
490 int32_t result = mLibLoader->stream_write(mAAudioStream, buffer,
491 numFrames, timeoutNanoseconds);
492 return ResultWithValue<int32_t>::createBasedOnSign(result);
493 } else {
494 return ResultWithValue<int32_t>(Result::ErrorClosed);
495 }
496 }
497
read(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)498 ResultWithValue<int32_t> AudioStreamAAudio::read(void *buffer,
499 int32_t numFrames,
500 int64_t timeoutNanoseconds) {
501 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
502 AAudioStream *stream = mAAudioStream.load();
503 if (stream != nullptr) {
504 int32_t result = mLibLoader->stream_read(mAAudioStream, buffer,
505 numFrames, timeoutNanoseconds);
506 return ResultWithValue<int32_t>::createBasedOnSign(result);
507 } else {
508 return ResultWithValue<int32_t>(Result::ErrorClosed);
509 }
510 }
511
512
513 // AAudioStream_waitForStateChange() can crash if it is waiting on a stream and that stream
514 // is closed from another thread. We do not want to lock the stream for the duration of the call.
515 // So we call AAudioStream_waitForStateChange() with a timeout of zero so that it will not block.
516 // Then we can do our own sleep with the lock unlocked.
waitForStateChange(StreamState currentState,StreamState * nextState,int64_t timeoutNanoseconds)517 Result AudioStreamAAudio::waitForStateChange(StreamState currentState,
518 StreamState *nextState,
519 int64_t timeoutNanoseconds) {
520 Result oboeResult = Result::ErrorTimeout;
521 int64_t sleepTimeNanos = 20 * kNanosPerMillisecond; // arbitrary
522 aaudio_stream_state_t currentAAudioState = static_cast<aaudio_stream_state_t>(currentState);
523
524 aaudio_result_t result = AAUDIO_OK;
525 int64_t timeLeftNanos = timeoutNanoseconds;
526
527 mLock.lock();
528 while (true) {
529 // Do we still have an AAudio stream? If not then stream must have been closed.
530 AAudioStream *stream = mAAudioStream.load();
531 if (stream == nullptr) {
532 if (nextState != nullptr) {
533 *nextState = StreamState::Closed;
534 }
535 oboeResult = Result::ErrorClosed;
536 break;
537 }
538
539 // Update and query state change with no blocking.
540 aaudio_stream_state_t aaudioNextState;
541 result = mLibLoader->stream_waitForStateChange(
542 mAAudioStream,
543 currentAAudioState,
544 &aaudioNextState,
545 0); // timeout=0 for non-blocking
546 // AAudio will return AAUDIO_ERROR_TIMEOUT if timeout=0 and the state does not change.
547 if (result != AAUDIO_OK && result != AAUDIO_ERROR_TIMEOUT) {
548 oboeResult = static_cast<Result>(result);
549 break;
550 }
551 #if OBOE_FIX_FORCE_STARTING_TO_STARTED
552 if (OboeGlobals::areWorkaroundsEnabled()
553 && aaudioNextState == static_cast<aaudio_stream_state_t >(StreamState::Starting)) {
554 aaudioNextState = static_cast<aaudio_stream_state_t >(StreamState::Started);
555 }
556 #endif // OBOE_FIX_FORCE_STARTING_TO_STARTED
557 if (nextState != nullptr) {
558 *nextState = static_cast<StreamState>(aaudioNextState);
559 }
560 if (currentAAudioState != aaudioNextState) { // state changed?
561 oboeResult = Result::OK;
562 break;
563 }
564
565 // Did we timeout or did user ask for non-blocking?
566 if (timeLeftNanos <= 0) {
567 break;
568 }
569
570 // No change yet so sleep.
571 mLock.unlock(); // Don't sleep while locked.
572 if (sleepTimeNanos > timeLeftNanos) {
573 sleepTimeNanos = timeLeftNanos; // last little bit
574 }
575 AudioClock::sleepForNanos(sleepTimeNanos);
576 timeLeftNanos -= sleepTimeNanos;
577 mLock.lock();
578 }
579
580 mLock.unlock();
581 return oboeResult;
582 }
583
setBufferSizeInFrames(int32_t requestedFrames)584 ResultWithValue<int32_t> AudioStreamAAudio::setBufferSizeInFrames(int32_t requestedFrames) {
585 int32_t adjustedFrames = requestedFrames;
586 if (adjustedFrames > mBufferCapacityInFrames) {
587 adjustedFrames = mBufferCapacityInFrames;
588 }
589 // This calls getBufferSize() so avoid recursive lock.
590 adjustedFrames = QuirksManager::getInstance().clipBufferSize(*this, adjustedFrames);
591
592 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
593 AAudioStream *stream = mAAudioStream.load();
594 if (stream != nullptr) {
595 int32_t newBufferSize = mLibLoader->stream_setBufferSize(mAAudioStream, adjustedFrames);
596 // Cache the result if it's valid
597 if (newBufferSize > 0) mBufferSizeInFrames = newBufferSize;
598 return ResultWithValue<int32_t>::createBasedOnSign(newBufferSize);
599 } else {
600 return ResultWithValue<int32_t>(Result::ErrorClosed);
601 }
602 }
603
getState()604 StreamState AudioStreamAAudio::getState() {
605 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
606 AAudioStream *stream = mAAudioStream.load();
607 if (stream != nullptr) {
608 aaudio_stream_state_t aaudioState = mLibLoader->stream_getState(stream);
609 #if OBOE_FIX_FORCE_STARTING_TO_STARTED
610 if (OboeGlobals::areWorkaroundsEnabled()
611 && aaudioState == AAUDIO_STREAM_STATE_STARTING) {
612 aaudioState = AAUDIO_STREAM_STATE_STARTED;
613 }
614 #endif // OBOE_FIX_FORCE_STARTING_TO_STARTED
615 return static_cast<StreamState>(aaudioState);
616 } else {
617 return StreamState::Closed;
618 }
619 }
620
getBufferSizeInFrames()621 int32_t AudioStreamAAudio::getBufferSizeInFrames() {
622 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
623 AAudioStream *stream = mAAudioStream.load();
624 if (stream != nullptr) {
625 mBufferSizeInFrames = mLibLoader->stream_getBufferSize(stream);
626 }
627 return mBufferSizeInFrames;
628 }
629
updateFramesRead()630 void AudioStreamAAudio::updateFramesRead() {
631 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
632 AAudioStream *stream = mAAudioStream.load();
633 // Set to 1 for debugging race condition #1180 with mAAudioStream.
634 // See also DEBUG_CLOSE_RACE in OboeTester.
635 // This was left in the code so that we could test the fix again easily in the future.
636 // We could not trigger the race condition without adding these get calls and the sleeps.
637 #define DEBUG_CLOSE_RACE 0
638 #if DEBUG_CLOSE_RACE
639 // This is used when testing race conditions with close().
640 // See DEBUG_CLOSE_RACE in OboeTester
641 AudioClock::sleepForNanos(400 * kNanosPerMillisecond);
642 #endif // DEBUG_CLOSE_RACE
643 if (stream != nullptr) {
644 mFramesRead = mLibLoader->stream_getFramesRead(stream);
645 }
646 }
647
updateFramesWritten()648 void AudioStreamAAudio::updateFramesWritten() {
649 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
650 AAudioStream *stream = mAAudioStream.load();
651 if (stream != nullptr) {
652 mFramesWritten = mLibLoader->stream_getFramesWritten(stream);
653 }
654 }
655
getXRunCount()656 ResultWithValue<int32_t> AudioStreamAAudio::getXRunCount() {
657 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
658 AAudioStream *stream = mAAudioStream.load();
659 if (stream != nullptr) {
660 return ResultWithValue<int32_t>::createBasedOnSign(mLibLoader->stream_getXRunCount(stream));
661 } else {
662 return ResultWithValue<int32_t>(Result::ErrorNull);
663 }
664 }
665
getTimestamp(clockid_t clockId,int64_t * framePosition,int64_t * timeNanoseconds)666 Result AudioStreamAAudio::getTimestamp(clockid_t clockId,
667 int64_t *framePosition,
668 int64_t *timeNanoseconds) {
669 if (getState() != StreamState::Started) {
670 return Result::ErrorInvalidState;
671 }
672 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
673 AAudioStream *stream = mAAudioStream.load();
674 if (stream != nullptr) {
675 return static_cast<Result>(mLibLoader->stream_getTimestamp(stream, clockId,
676 framePosition, timeNanoseconds));
677 } else {
678 return Result::ErrorNull;
679 }
680 }
681
calculateLatencyMillis()682 ResultWithValue<double> AudioStreamAAudio::calculateLatencyMillis() {
683 // Get the time that a known audio frame was presented.
684 int64_t hardwareFrameIndex;
685 int64_t hardwareFrameHardwareTime;
686 auto result = getTimestamp(CLOCK_MONOTONIC,
687 &hardwareFrameIndex,
688 &hardwareFrameHardwareTime);
689 if (result != oboe::Result::OK) {
690 return ResultWithValue<double>(static_cast<Result>(result));
691 }
692
693 // Get counter closest to the app.
694 bool isOutput = (getDirection() == oboe::Direction::Output);
695 int64_t appFrameIndex = isOutput ? getFramesWritten() : getFramesRead();
696
697 // Assume that the next frame will be processed at the current time
698 using namespace std::chrono;
699 int64_t appFrameAppTime =
700 duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count();
701
702 // Calculate the number of frames between app and hardware
703 int64_t frameIndexDelta = appFrameIndex - hardwareFrameIndex;
704
705 // Calculate the time which the next frame will be or was presented
706 int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / getSampleRate();
707 int64_t appFrameHardwareTime = hardwareFrameHardwareTime + frameTimeDelta;
708
709 // The current latency is the difference in time between when the current frame is at
710 // the app and when it is at the hardware.
711 double latencyNanos = static_cast<double>(isOutput
712 ? (appFrameHardwareTime - appFrameAppTime) // hardware is later
713 : (appFrameAppTime - appFrameHardwareTime)); // hardware is earlier
714 double latencyMillis = latencyNanos / kNanosPerMillisecond;
715
716 return ResultWithValue<double>(latencyMillis);
717 }
718
isMMapUsed()719 bool AudioStreamAAudio::isMMapUsed() {
720 std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
721 AAudioStream *stream = mAAudioStream.load();
722 if (stream != nullptr) {
723 return AAudioExtensions::getInstance().isMMapUsed(stream);
724 } else {
725 return false;
726 }
727 }
728
729 } // namespace oboe
730