• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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 #define LOG_TAG "AAudioStream"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 
21 #include <atomic>
22 #include <stdint.h>
23 
24 #include <linux/futex.h>
25 #include <media/MediaMetricsItem.h>
26 #include <sys/syscall.h>
27 
28 #include <aaudio/AAudio.h>
29 
30 #include "AudioStreamBuilder.h"
31 #include "AudioStream.h"
32 #include "AudioClock.h"
33 #include "AudioGlobal.h"
34 
35 namespace aaudio {
36 
37 // Sequential number assigned to streams solely for debugging purposes.
AAudio_getNextStreamId()38 static aaudio_stream_id_t AAudio_getNextStreamId() {
39     static std::atomic <aaudio_stream_id_t> nextStreamId{1};
40     return nextStreamId++;
41 }
42 
AudioStream()43 AudioStream::AudioStream()
44         : mPlayerBase(new MyPlayerBase())
45         , mStreamId(AAudio_getNextStreamId())
46         {
47     setPeriodNanoseconds(0);
48 }
49 
~AudioStream()50 AudioStream::~AudioStream() {
51     // Please preserve these logs because there have been several bugs related to
52     // AudioStream deletion and late callbacks.
53     ALOGD("%s(s#%u) mPlayerBase strongCount = %d",
54             __func__, getId(), mPlayerBase->getStrongCount());
55 
56     ALOGE_IF(pthread_equal(pthread_self(), mThread),
57             "%s() destructor running in callback", __func__);
58 
59     ALOGE_IF(mHasThread, "%s() callback thread never join()ed", __func__);
60 
61     // If the stream is deleted when OPEN or in use then audio resources will leak.
62     // This would indicate an internal error. So we want to find this ASAP.
63     LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
64                           || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED),
65                         "~AudioStream() - still in use, state = %s disconnected = %d",
66                         AudioGlobal_convertStreamStateToText(getState()), isDisconnected());
67 }
68 
open(const AudioStreamBuilder & builder)69 aaudio_result_t AudioStream::open(const AudioStreamBuilder& builder)
70 {
71     // Call here as well because the AAudioService will call this without calling build().
72     aaudio_result_t result = builder.validate();
73     if (result != AAUDIO_OK) {
74         return result;
75     }
76 
77     // Copy parameters from the Builder because the Builder may be deleted after this call.
78     // TODO AudioStream should be a subclass of AudioStreamParameters
79     mSamplesPerFrame = builder.getSamplesPerFrame();
80     mChannelMask = builder.getChannelMask();
81     mSampleRate = builder.getSampleRate();
82     mDeviceId = builder.getDeviceId();
83     mFormat = builder.getFormat();
84     mSharingMode = builder.getSharingMode();
85     mSharingModeMatchRequired = builder.isSharingModeMatchRequired();
86     mPerformanceMode = builder.getPerformanceMode();
87 
88     mUsage = builder.getUsage();
89     if (mUsage == AAUDIO_UNSPECIFIED) {
90         mUsage = AAUDIO_USAGE_MEDIA;
91     }
92     mContentType = builder.getContentType();
93     if (mContentType == AAUDIO_UNSPECIFIED) {
94         mContentType = AAUDIO_CONTENT_TYPE_MUSIC;
95     }
96     mSpatializationBehavior = builder.getSpatializationBehavior();
97     // for consistency with other properties, note UNSPECIFIED is the same as AUTO
98     if (mSpatializationBehavior == AAUDIO_UNSPECIFIED) {
99         mSpatializationBehavior = AAUDIO_SPATIALIZATION_BEHAVIOR_AUTO;
100     }
101     mIsContentSpatialized = builder.isContentSpatialized();
102     mInputPreset = builder.getInputPreset();
103     if (mInputPreset == AAUDIO_UNSPECIFIED) {
104         mInputPreset = AAUDIO_INPUT_PRESET_VOICE_RECOGNITION;
105     }
106     mAllowedCapturePolicy = builder.getAllowedCapturePolicy();
107     if (mAllowedCapturePolicy == AAUDIO_UNSPECIFIED) {
108         mAllowedCapturePolicy = AAUDIO_ALLOW_CAPTURE_BY_ALL;
109     }
110     mIsPrivacySensitive = builder.isPrivacySensitive();
111 
112     // callbacks
113     mFramesPerDataCallback = builder.getFramesPerDataCallback();
114     mDataCallbackProc = builder.getDataCallbackProc();
115     mErrorCallbackProc = builder.getErrorCallbackProc();
116     mDataCallbackUserData = builder.getDataCallbackUserData();
117     mErrorCallbackUserData = builder.getErrorCallbackUserData();
118 
119     return AAUDIO_OK;
120 }
121 
logOpenActual()122 void AudioStream::logOpenActual() {
123     if (mMetricsId.size() > 0) {
124         android::mediametrics::LogItem item(mMetricsId);
125         item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
126             .set(AMEDIAMETRICS_PROP_PERFORMANCEMODEACTUAL,
127                     AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
128             .set(AMEDIAMETRICS_PROP_SHARINGMODEACTUAL,
129                     AudioGlobal_convertSharingModeToText(getSharingMode()))
130             .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, getBufferCapacity())
131             .set(AMEDIAMETRICS_PROP_BURSTFRAMES, getFramesPerBurst())
132             .set(AMEDIAMETRICS_PROP_DIRECTION,
133                     AudioGlobal_convertDirectionToText(getDirection()))
134             .set(AMEDIAMETRICS_PROP_ENCODINGHARDWARE,
135                     android::toString(getHardwareFormat()).c_str())
136             .set(AMEDIAMETRICS_PROP_CHANNELCOUNTHARDWARE, (int32_t)getHardwareSamplesPerFrame())
137             .set(AMEDIAMETRICS_PROP_SAMPLERATEHARDWARE, (int32_t)getHardwareSampleRate());
138 
139         if (getDirection() == AAUDIO_DIRECTION_OUTPUT) {
140             item.set(AMEDIAMETRICS_PROP_PLAYERIID, mPlayerBase->getPlayerIId());
141         }
142         item.record();
143     }
144 }
145 
logReleaseBufferState()146 void AudioStream::logReleaseBufferState() {
147     if (mMetricsId.size() > 0) {
148         android::mediametrics::LogItem(mMetricsId)
149                 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_RELEASE)
150                 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t) getBufferSize())
151                 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getXRunCount())
152                 .record();
153     }
154 }
155 
systemStart()156 aaudio_result_t AudioStream::systemStart() {
157     if (collidesWithCallback()) {
158         ALOGE("%s cannot be called from a callback!", __func__);
159         return AAUDIO_ERROR_INVALID_STATE;
160     }
161 
162     std::lock_guard<std::mutex> lock(mStreamLock);
163 
164     if (isDisconnected()) {
165         ALOGW("%s() stream is disconnected", __func__);
166         return AAUDIO_ERROR_INVALID_STATE;
167     }
168 
169     switch (getState()) {
170         // Is this a good time to start?
171         case AAUDIO_STREAM_STATE_OPEN:
172         case AAUDIO_STREAM_STATE_PAUSING:
173         case AAUDIO_STREAM_STATE_PAUSED:
174         case AAUDIO_STREAM_STATE_STOPPING:
175         case AAUDIO_STREAM_STATE_STOPPED:
176         case AAUDIO_STREAM_STATE_FLUSHING:
177         case AAUDIO_STREAM_STATE_FLUSHED:
178             break; // Proceed with starting.
179 
180         // Already started?
181         case AAUDIO_STREAM_STATE_STARTING:
182         case AAUDIO_STREAM_STATE_STARTED:
183             ALOGW("%s() stream was already started, state = %s", __func__,
184                   AudioGlobal_convertStreamStateToText(getState()));
185             return AAUDIO_ERROR_INVALID_STATE;
186 
187         case AAUDIO_STREAM_STATE_DISCONNECTED:
188             // This must not happen after deprecating AAUDIO_STREAM_STATE_DISCONNECTED, trying to
189             // start will finally return ERROR_DISCONNECTED.
190             ALOGE("%s, unexpected state = AAUDIO_STREAM_STATE_DISCONNECTED", __func__);
191             return AAUDIO_ERROR_INTERNAL;
192 
193         // Don't start when the stream is dead!
194         case AAUDIO_STREAM_STATE_CLOSING:
195         case AAUDIO_STREAM_STATE_CLOSED:
196         default:
197             ALOGW("%s() stream is dead, state = %s", __func__,
198                   AudioGlobal_convertStreamStateToText(getState()));
199             return AAUDIO_ERROR_INVALID_STATE;
200     }
201 
202     aaudio_result_t result = requestStart_l();
203     if (result == AAUDIO_OK) {
204         // We only call this for logging in "dumpsys audio". So ignore return code.
205         (void) mPlayerBase->startWithStatus(getDeviceId());
206     }
207     return result;
208 }
209 
systemPause()210 aaudio_result_t AudioStream::systemPause() {
211 
212     if (!isPauseSupported()) {
213         return AAUDIO_ERROR_UNIMPLEMENTED;
214     }
215 
216     if (collidesWithCallback()) {
217         ALOGE("%s cannot be called from a callback!", __func__);
218         return AAUDIO_ERROR_INVALID_STATE;
219     }
220 
221     std::lock_guard<std::mutex> lock(mStreamLock);
222     switch (getState()) {
223         // Proceed with pausing.
224         case AAUDIO_STREAM_STATE_STARTING:
225         case AAUDIO_STREAM_STATE_STARTED:
226             break;
227 
228         case AAUDIO_STREAM_STATE_DISCONNECTED:
229             // This must not happen after deprecating AAUDIO_STREAM_STATE_DISCONNECTED
230             ALOGE("%s, unexpected state = AAUDIO_STREAM_STATE_DISCONNECTED", __func__);
231             break;
232 
233             // Transition from one inactive state to another.
234         case AAUDIO_STREAM_STATE_OPEN:
235         case AAUDIO_STREAM_STATE_STOPPED:
236         case AAUDIO_STREAM_STATE_FLUSHED:
237             setState(AAUDIO_STREAM_STATE_PAUSED);
238             return AAUDIO_OK;
239 
240             // Redundant?
241         case AAUDIO_STREAM_STATE_PAUSING:
242         case AAUDIO_STREAM_STATE_PAUSED:
243             return AAUDIO_OK;
244 
245             // Don't interfere with transitional states or when closed.
246         case AAUDIO_STREAM_STATE_STOPPING:
247         case AAUDIO_STREAM_STATE_FLUSHING:
248         case AAUDIO_STREAM_STATE_CLOSING:
249         case AAUDIO_STREAM_STATE_CLOSED:
250         default:
251             ALOGW("%s() stream not running, state = %s",
252                   __func__, AudioGlobal_convertStreamStateToText(getState()));
253             return AAUDIO_ERROR_INVALID_STATE;
254     }
255 
256     aaudio_result_t result = requestPause_l();
257     if (result == AAUDIO_OK) {
258         // We only call this for logging in "dumpsys audio". So ignore return code.
259         (void) mPlayerBase->pauseWithStatus();
260     }
261     return result;
262 }
263 
safeFlush()264 aaudio_result_t AudioStream::safeFlush() {
265     if (!isFlushSupported()) {
266         ALOGE("flush not supported for this stream");
267         return AAUDIO_ERROR_UNIMPLEMENTED;
268     }
269 
270     if (collidesWithCallback()) {
271         ALOGE("stream cannot be flushed from a callback!");
272         return AAUDIO_ERROR_INVALID_STATE;
273     }
274 
275     std::lock_guard<std::mutex> lock(mStreamLock);
276     aaudio_result_t result = AAudio_isFlushAllowed(getState());
277     if (result != AAUDIO_OK) {
278         return result;
279     }
280 
281     return requestFlush_l();
282 }
283 
systemStopInternal()284 aaudio_result_t AudioStream::systemStopInternal() {
285     std::lock_guard<std::mutex> lock(mStreamLock);
286     aaudio_result_t result = safeStop_l();
287     if (result == AAUDIO_OK) {
288         // We only call this for logging in "dumpsys audio". So ignore return code.
289         (void) mPlayerBase->stopWithStatus();
290     }
291     return result;
292 }
293 
systemStopFromApp()294 aaudio_result_t AudioStream::systemStopFromApp() {
295     // This check can and should be done outside the lock.
296     if (collidesWithCallback()) {
297         ALOGE("stream cannot be stopped by calling from a callback!");
298         return AAUDIO_ERROR_INVALID_STATE;
299     }
300     return systemStopInternal();
301 }
302 
safeStop_l()303 aaudio_result_t AudioStream::safeStop_l() {
304 
305     switch (getState()) {
306         // Proceed with stopping.
307         case AAUDIO_STREAM_STATE_STARTING:
308         case AAUDIO_STREAM_STATE_STARTED:
309             break;
310         case AAUDIO_STREAM_STATE_DISCONNECTED:
311             // This must not happen after deprecating AAUDIO_STREAM_STATE_DISCONNECTED
312             ALOGE("%s, unexpected state = AAUDIO_STREAM_STATE_DISCONNECTED", __func__);
313             break;
314 
315         // Transition from one inactive state to another.
316         case AAUDIO_STREAM_STATE_OPEN:
317         case AAUDIO_STREAM_STATE_PAUSED:
318         case AAUDIO_STREAM_STATE_FLUSHED:
319             setState(AAUDIO_STREAM_STATE_STOPPED);
320             return AAUDIO_OK;
321 
322         // Redundant?
323         case AAUDIO_STREAM_STATE_STOPPING:
324         case AAUDIO_STREAM_STATE_STOPPED:
325             return AAUDIO_OK;
326 
327         // Don't interfere with transitional states or when closed.
328         case AAUDIO_STREAM_STATE_PAUSING:
329         case AAUDIO_STREAM_STATE_FLUSHING:
330         case AAUDIO_STREAM_STATE_CLOSING:
331         case AAUDIO_STREAM_STATE_CLOSED:
332         default:
333             ALOGW("%s() stream not running, state = %s", __func__,
334                   AudioGlobal_convertStreamStateToText(getState()));
335             return AAUDIO_ERROR_INVALID_STATE;
336     }
337 
338     return requestStop_l();
339 }
340 
safeRelease()341 aaudio_result_t AudioStream::safeRelease() {
342     if (collidesWithCallback()) {
343         ALOGE("%s cannot be called from a callback!", __func__);
344         return AAUDIO_ERROR_INVALID_STATE;
345     }
346     // This may get temporarily unlocked in the MMAP release() when joining callback threads.
347     std::lock_guard<std::mutex> lock(mStreamLock);
348     if (getState() == AAUDIO_STREAM_STATE_CLOSING) { // already released?
349         return AAUDIO_OK;
350     }
351     return release_l();
352 }
353 
safeReleaseClose()354 aaudio_result_t AudioStream::safeReleaseClose() {
355     if (collidesWithCallback()) {
356         ALOGE("%s cannot be called from a callback!", __func__);
357         return AAUDIO_ERROR_INVALID_STATE;
358     }
359     return safeReleaseCloseInternal();
360 }
361 
safeReleaseCloseInternal()362 aaudio_result_t AudioStream::safeReleaseCloseInternal() {
363     // This get temporarily unlocked in the MMAP release() when joining callback threads.
364     std::lock_guard<std::mutex> lock(mStreamLock);
365     releaseCloseFinal_l();
366     return AAUDIO_OK;
367 }
368 
close_l()369 void AudioStream::close_l() {
370     // Releasing the stream will set the state to CLOSING.
371     assert(getState() == AAUDIO_STREAM_STATE_CLOSING);
372     // setState() prevents a transition from CLOSING to any state other than CLOSED.
373     // State is checked by destructor.
374     setState(AAUDIO_STREAM_STATE_CLOSED);
375 
376     if (!mMetricsId.empty()) {
377         android::mediametrics::LogItem(mMetricsId)
378                 .set(AMEDIAMETRICS_PROP_FRAMESTRANSFERRED,
379                         getDirection() == AAUDIO_DIRECTION_INPUT ? getFramesWritten()
380                                                                  : getFramesRead())
381                 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_ENDAAUDIOSTREAM)
382                 .record();
383     }
384 }
385 
setState(aaudio_stream_state_t state)386 void AudioStream::setState(aaudio_stream_state_t state) {
387     aaudio_stream_state_t oldState = mState.load();
388     ALOGD("%s(s#%d) from %d to %d", __func__, getId(), oldState, state);
389     if (state == oldState) {
390         return; // no change
391     }
392     LOG_ALWAYS_FATAL_IF(state == AAUDIO_STREAM_STATE_DISCONNECTED,
393                         "Disconnected state must be separated from mState");
394     // CLOSED is a final state
395     if (oldState == AAUDIO_STREAM_STATE_CLOSED) {
396         ALOGW("%s(%d) tried to set to %d but already CLOSED", __func__, getId(), state);
397 
398     // Once CLOSING, we can only move to CLOSED state.
399     } else if (oldState == AAUDIO_STREAM_STATE_CLOSING
400                && state != AAUDIO_STREAM_STATE_CLOSED) {
401         ALOGW("%s(%d) tried to set to %d but already CLOSING", __func__, getId(), state);
402 
403     } else {
404         mState.store(state);
405         // Wake up a wakeForStateChange thread if it exists.
406         syscall(SYS_futex, &mState, FUTEX_WAKE_PRIVATE, INT_MAX, NULL, NULL, 0);
407     }
408 }
409 
setDisconnected()410 void AudioStream::setDisconnected() {
411     const bool old = isDisconnected();
412     ALOGD("%s setting disconnected, current disconnected: %d, current state: %d",
413           __func__, old, getState());
414     if (old) {
415         return; // no change, the stream is already disconnected
416     }
417     mDisconnected.store(true);
418     // Wake up a wakeForStateChange thread if it exists.
419     syscall(SYS_futex, &mState, FUTEX_WAKE_PRIVATE, INT_MAX, NULL, NULL, 0);
420     // Track transition to DISCONNECTED state.
421     android::mediametrics::LogItem(mMetricsId)
422             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
423             .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
424             .record();
425 }
426 
waitForStateChange(aaudio_stream_state_t currentState,aaudio_stream_state_t * nextState,int64_t timeoutNanoseconds)427 aaudio_result_t AudioStream::waitForStateChange(aaudio_stream_state_t currentState,
428                                                 aaudio_stream_state_t *nextState,
429                                                 int64_t timeoutNanoseconds)
430 {
431     aaudio_result_t result = updateStateMachine();
432     if (result != AAUDIO_OK) {
433         return result;
434     }
435 
436     int64_t durationNanos = 20 * AAUDIO_NANOS_PER_MILLISECOND; // arbitrary
437     aaudio_stream_state_t state = getStateExternal();
438     while (state == currentState && timeoutNanoseconds > 0) {
439         if (durationNanos > timeoutNanoseconds) {
440             durationNanos = timeoutNanoseconds;
441         }
442         struct timespec time;
443         time.tv_sec = durationNanos / AAUDIO_NANOS_PER_SECOND;
444         // Add the fractional nanoseconds.
445         time.tv_nsec = durationNanos - (time.tv_sec * AAUDIO_NANOS_PER_SECOND);
446 
447         // Sleep for durationNanos. If mState changes from the callback
448         // thread, this thread will wake up earlier.
449         syscall(SYS_futex, &mState, FUTEX_WAIT_PRIVATE, currentState, &time, NULL, 0);
450         timeoutNanoseconds -= durationNanos;
451         aaudio_result_t result = updateStateMachine();
452         if (result != AAUDIO_OK) {
453             return result;
454         }
455 
456         state = getStateExternal();
457     }
458     if (nextState != nullptr) {
459         *nextState = state;
460     }
461     return (state == currentState) ? AAUDIO_ERROR_TIMEOUT : AAUDIO_OK;
462 }
463 
464 // This registers the callback thread with the server before
465 // passing control to the app. This gives the server an opportunity to boost
466 // the thread's performance characteristics.
wrapUserThread()467 void* AudioStream::wrapUserThread() {
468     void* procResult = nullptr;
469     mThreadRegistrationResult = registerThread();
470     if (mThreadRegistrationResult == AAUDIO_OK) {
471         // Run callback loop. This may take a very long time.
472         procResult = mThreadProc(mThreadArg);
473         mThreadRegistrationResult = unregisterThread();
474     }
475     return procResult;
476 }
477 
478 
479 // This is the entry point for the new thread created by createThread_l().
480 // It converts the 'C' function call to a C++ method call.
AudioStream_internalThreadProc(void * threadArg)481 static void* AudioStream_internalThreadProc(void* threadArg) {
482     AudioStream *audioStream = (AudioStream *) threadArg;
483     // Prevent the stream from being deleted while being used.
484     // This is just for extra safety. It is probably not needed because
485     // this callback should be joined before the stream is closed.
486     android::sp<AudioStream> protectedStream(audioStream);
487     // Balance the incStrong() in createThread_l().
488     protectedStream->decStrong(nullptr);
489     return protectedStream->wrapUserThread();
490 }
491 
492 // This is not exposed in the API.
493 // But it is still used internally to implement callbacks for MMAP mode.
createThread_l(int64_t periodNanoseconds,aaudio_audio_thread_proc_t threadProc,void * threadArg)494 aaudio_result_t AudioStream::createThread_l(int64_t periodNanoseconds,
495                                             aaudio_audio_thread_proc_t threadProc,
496                                             void* threadArg)
497 {
498     if (mHasThread) {
499         ALOGD("%s() - previous thread was not joined, join now to be safe", __func__);
500         joinThread_l(nullptr);
501     }
502     if (threadProc == nullptr) {
503         return AAUDIO_ERROR_NULL;
504     }
505     // Pass input parameters to the background thread.
506     mThreadProc = threadProc;
507     mThreadArg = threadArg;
508     setPeriodNanoseconds(periodNanoseconds);
509     mHasThread = true;
510     // Prevent this object from getting deleted before the thread has a chance to create
511     // its strong pointer. Assume the thread will call decStrong().
512     this->incStrong(nullptr);
513     int err = pthread_create(&mThread, nullptr, AudioStream_internalThreadProc, this);
514     if (err != 0) {
515         android::status_t status = -errno;
516         ALOGE("%s() - pthread_create() failed, %d", __func__, status);
517         this->decStrong(nullptr); // Because the thread won't do it.
518         mHasThread = false;
519         return AAudioConvert_androidToAAudioResult(status);
520     } else {
521         // TODO Use AAudioThread or maybe AndroidThread
522         // Name the thread with an increasing index, "AAudio_#", for debugging.
523         static std::atomic<uint32_t> nextThreadIndex{1};
524         char name[16]; // max length for a pthread_name
525         uint32_t index = nextThreadIndex++;
526         // Wrap the index so that we do not hit the 16 char limit
527         // and to avoid hard-to-read large numbers.
528         index = index % 100000;  // arbitrary
529         snprintf(name, sizeof(name), "AAudio_%u", index);
530         err = pthread_setname_np(mThread, name);
531         ALOGW_IF((err != 0), "Could not set name of AAudio thread. err = %d", err);
532 
533         return AAUDIO_OK;
534     }
535 }
536 
joinThread(void ** returnArg)537 aaudio_result_t AudioStream::joinThread(void** returnArg) {
538     // This may get temporarily unlocked in the MMAP release() when joining callback threads.
539     std::lock_guard<std::mutex> lock(mStreamLock);
540     return joinThread_l(returnArg);
541 }
542 
543 // This must be called under mStreamLock.
joinThread_l(void ** returnArg)544 aaudio_result_t AudioStream::joinThread_l(void** returnArg) {
545     if (!mHasThread) {
546         ALOGD("joinThread() - but has no thread or already join()ed");
547         return AAUDIO_ERROR_INVALID_STATE;
548     }
549     aaudio_result_t result = AAUDIO_OK;
550     // If the callback is stopping the stream because the app passed back STOP
551     // then we don't need to join(). The thread is already about to exit.
552     if (!pthread_equal(pthread_self(), mThread)) {
553         // Called from an app thread. Not the callback.
554         // Unlock because the callback may be trying to stop the stream but is blocked.
555         mStreamLock.unlock();
556         int err = pthread_join(mThread, returnArg);
557         mStreamLock.lock();
558         if (err) {
559             ALOGE("%s() pthread_join() returns err = %d", __func__, err);
560             result = AAudioConvert_androidToAAudioResult(-err);
561         } else {
562             ALOGD("%s() pthread_join succeeded", __func__);
563             // Prevent joining a second time, which has undefined behavior.
564             mHasThread = false;
565         }
566     } else {
567         ALOGD("%s() pthread_join() called on itself!", __func__);
568     }
569     return (result != AAUDIO_OK) ? result : mThreadRegistrationResult;
570 }
571 
maybeCallDataCallback(void * audioData,int32_t numFrames)572 aaudio_data_callback_result_t AudioStream::maybeCallDataCallback(void *audioData,
573                                                                  int32_t numFrames) {
574     aaudio_data_callback_result_t result = AAUDIO_CALLBACK_RESULT_STOP;
575     AAudioStream_dataCallback dataCallback = getDataCallbackProc();
576     if (dataCallback != nullptr) {
577         // Store thread ID of caller to detect stop() and close() calls from callback.
578         pid_t expected = CALLBACK_THREAD_NONE;
579         if (mDataCallbackThread.compare_exchange_strong(expected, gettid())) {
580             result = (*dataCallback)(
581                     (AAudioStream *) this,
582                     getDataCallbackUserData(),
583                     audioData,
584                     numFrames);
585             mDataCallbackThread.store(CALLBACK_THREAD_NONE);
586         } else {
587             ALOGW("%s() data callback already running!", __func__);
588         }
589     }
590     return result;
591 }
592 
maybeCallErrorCallback(aaudio_result_t result)593 void AudioStream::maybeCallErrorCallback(aaudio_result_t result) {
594     AAudioStream_errorCallback errorCallback = getErrorCallbackProc();
595     if (errorCallback != nullptr) {
596         // Store thread ID of caller to detect stop() and close() calls from callback.
597         pid_t expected = CALLBACK_THREAD_NONE;
598         if (mErrorCallbackThread.compare_exchange_strong(expected, gettid())) {
599             (*errorCallback)(
600                     (AAudioStream *) this,
601                     getErrorCallbackUserData(),
602                     result);
603             mErrorCallbackThread.store(CALLBACK_THREAD_NONE);
604         } else {
605             ALOGW("%s() error callback already running!", __func__);
606         }
607     }
608 }
609 
610 // Is this running on the same thread as a callback?
611 // Note: This cannot be implemented using a thread_local because that would
612 // require using a thread_local variable that is shared between streams.
613 // So a thread_local variable would prevent stopping or closing stream A from
614 // a callback on stream B, which is currently legal and not so terrible.
collidesWithCallback() const615 bool AudioStream::collidesWithCallback() const {
616     pid_t thisThread = gettid();
617     // Compare the current thread ID with the thread ID of the callback
618     // threads to see it they match. If so then this code is being
619     // called from one of the stream callback functions.
620     return ((mErrorCallbackThread.load() == thisThread)
621             || (mDataCallbackThread.load() == thisThread));
622 }
623 
624 #if AAUDIO_USE_VOLUME_SHAPER
applyVolumeShaper(const::android::media::VolumeShaper::Configuration & configuration,const::android::media::VolumeShaper::Operation & operation)625 ::android::binder::Status AudioStream::MyPlayerBase::applyVolumeShaper(
626         const ::android::media::VolumeShaper::Configuration& configuration,
627         const ::android::media::VolumeShaper::Operation& operation) {
628     android::sp<AudioStream> audioStream;
629     {
630         std::lock_guard<std::mutex> lock(mParentLock);
631         audioStream = mParent.promote();
632     }
633     if (audioStream) {
634         return audioStream->applyVolumeShaper(configuration, operation);
635     }
636     return android::NO_ERROR;
637 }
638 #endif
639 
setDuckAndMuteVolume(float duckAndMuteVolume)640 void AudioStream::setDuckAndMuteVolume(float duckAndMuteVolume) {
641     ALOGD("%s() to %f", __func__, duckAndMuteVolume);
642     std::lock_guard<std::mutex> lock(mStreamLock);
643     mDuckAndMuteVolume = duckAndMuteVolume;
644     doSetVolume(); // apply this change
645 }
646 
getStateExternal() const647 aaudio_stream_state_t AudioStream::getStateExternal() const {
648     if (isDisconnected()) {
649         return AAUDIO_STREAM_STATE_DISCONNECTED;
650     }
651     return getState();
652 }
653 
registerWithAudioManager(const android::sp<AudioStream> & parent)654 void AudioStream::MyPlayerBase::registerWithAudioManager(const android::sp<AudioStream>& parent) {
655     std::lock_guard<std::mutex> lock(mParentLock);
656     mParent = parent;
657     if (!mRegistered) {
658         init(android::PLAYER_TYPE_AAUDIO, AAudioConvert_usageToInternal(parent->getUsage()),
659             (audio_session_t)parent->getSessionId());
660         mRegistered = true;
661     }
662 }
663 
unregisterWithAudioManager()664 void AudioStream::MyPlayerBase::unregisterWithAudioManager() {
665     std::lock_guard<std::mutex> lock(mParentLock);
666     if (mRegistered) {
667         baseDestroy();
668         mRegistered = false;
669     }
670 }
671 
playerSetVolume()672 android::status_t AudioStream::MyPlayerBase::playerSetVolume() {
673     android::sp<AudioStream> audioStream;
674     {
675         std::lock_guard<std::mutex> lock(mParentLock);
676         audioStream = mParent.promote();
677     }
678     if (audioStream) {
679         // No pan and only left volume is taken into account from IPLayer interface
680         audioStream->setDuckAndMuteVolume(mVolumeMultiplierL  /* mPanMultiplierL */);
681     }
682     return android::NO_ERROR;
683 }
684 
destroy()685 void AudioStream::MyPlayerBase::destroy() {
686     unregisterWithAudioManager();
687 }
688 
689 }  // namespace aaudio
690