• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 #define LOG_TAG "AAudioServiceStreamBase"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 
21 #include <iomanip>
22 #include <iostream>
23 #include <mutex>
24 
25 #include <media/MediaMetricsItem.h>
26 #include <media/TypeConverter.h>
27 #include <mediautils/SchedulingPolicyService.h>
28 
29 #include "binding/IAAudioService.h"
30 #include "binding/AAudioServiceMessage.h"
31 #include "core/AudioGlobal.h"
32 #include "utility/AudioClock.h"
33 
34 #include "AAudioEndpointManager.h"
35 #include "AAudioService.h"
36 #include "AAudioServiceEndpoint.h"
37 #include "AAudioServiceStreamBase.h"
38 #include "TimestampScheduler.h"
39 
40 using namespace android;  // TODO just import names needed
41 using namespace aaudio;   // TODO just import names needed
42 
43 /**
44  * Base class for streams in the service.
45  * @return
46  */
47 
AAudioServiceStreamBase(AAudioService & audioService)48 AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
49         : mUpMessageQueue(nullptr)
50         , mTimestampThread("AATime")
51         , mAtomicStreamTimestamp()
52         , mAudioService(audioService) {
53     mMmapClient.clientUid = -1;
54     mMmapClient.clientPid = -1;
55     mMmapClient.packageName = String16("");
56 }
57 
~AAudioServiceStreamBase()58 AAudioServiceStreamBase::~AAudioServiceStreamBase() {
59     // May not be set if open failed.
60     if (mMetricsId.size() > 0) {
61         mediametrics::LogItem(mMetricsId)
62                 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
63                 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
64                 .record();
65     }
66 
67     // If the stream is deleted when OPEN or in use then audio resources will leak.
68     // This would indicate an internal error. So we want to find this ASAP.
69     LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
70                         || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED
71                         || getState() == AAUDIO_STREAM_STATE_DISCONNECTED),
72                         "service stream %p still open, state = %d",
73                         this, getState());
74 }
75 
dumpHeader()76 std::string AAudioServiceStreamBase::dumpHeader() {
77     return std::string("    T   Handle   UId   Port Run State Format Burst Chan Capacity");
78 }
79 
dump() const80 std::string AAudioServiceStreamBase::dump() const {
81     std::stringstream result;
82 
83     result << "    0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
84            << std::dec << std::setfill(' ') ;
85     result << std::setw(6) << mMmapClient.clientUid;
86     result << std::setw(7) << mClientHandle;
87     result << std::setw(4) << (isRunning() ? "yes" : " no");
88     result << std::setw(6) << getState();
89     result << std::setw(7) << getFormat();
90     result << std::setw(6) << mFramesPerBurst;
91     result << std::setw(5) << getSamplesPerFrame();
92     result << std::setw(9) << getBufferCapacity();
93 
94     return result.str();
95 }
96 
logOpen(aaudio_handle_t streamHandle)97 void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
98     // This is the first log sent from the AAudio Service for a stream.
99     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
100             + std::to_string(streamHandle);
101 
102     audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
103 
104     // Once this item is logged by the server, the client with the same PID, UID
105     // can also log properties.
106     mediametrics::LogItem(mMetricsId)
107         .setPid(getOwnerProcessId())
108         .setUid(getOwnerUserId())
109         .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
110         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
111         // the following are immutable
112         .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
113         .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
114         .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
115         .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
116         .set(AMEDIAMETRICS_PROP_DIRECTION,
117                 AudioGlobal_convertDirectionToText(getDirection()))
118         .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
119         .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
120         .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
121         .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
122         .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
123         .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
124         .record();
125 }
126 
open(const aaudio::AAudioStreamRequest & request)127 aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
128     AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
129     aaudio_result_t result = AAUDIO_OK;
130 
131     mMmapClient.clientUid = request.getUserId();
132     mMmapClient.clientPid = request.getProcessId();
133     mMmapClient.packageName.setTo(String16("")); // TODO What should we do here?
134 
135     // Limit scope of lock to avoid recursive lock in close().
136     {
137         std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
138         if (mUpMessageQueue != nullptr) {
139             ALOGE("%s() called twice", __func__);
140             return AAUDIO_ERROR_INVALID_STATE;
141         }
142 
143         mUpMessageQueue = new SharedRingBuffer();
144         result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
145                                            QUEUE_UP_CAPACITY_COMMANDS);
146         if (result != AAUDIO_OK) {
147             goto error;
148         }
149 
150         // This is not protected by a lock because the stream cannot be
151         // referenced until the service returns a handle to the client.
152         // So only one thread can open a stream.
153         mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
154                                                          request);
155         if (mServiceEndpoint == nullptr) {
156             result = AAUDIO_ERROR_UNAVAILABLE;
157             goto error;
158         }
159         // Save a weak pointer that we will use to access the endpoint.
160         mServiceEndpointWeak = mServiceEndpoint;
161 
162         mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
163         copyFrom(*mServiceEndpoint);
164     }
165     return result;
166 
167 error:
168     close();
169     return result;
170 }
171 
close()172 aaudio_result_t AAudioServiceStreamBase::close() {
173     std::lock_guard<std::mutex> lock(mLock);
174     return close_l();
175 }
176 
close_l()177 aaudio_result_t AAudioServiceStreamBase::close_l() {
178     if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
179         return AAUDIO_OK;
180     }
181 
182     stop_l();
183 
184     aaudio_result_t result = AAUDIO_OK;
185     sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
186     if (endpoint == nullptr) {
187         result = AAUDIO_ERROR_INVALID_STATE;
188     } else {
189         endpoint->unregisterStream(this);
190         AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
191         endpointManager.closeEndpoint(endpoint);
192 
193         // AAudioService::closeStream() prevents two threads from closing at the same time.
194         mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
195     }
196 
197     {
198         std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
199         stopTimestampThread();
200         delete mUpMessageQueue;
201         mUpMessageQueue = nullptr;
202     }
203 
204     setState(AAUDIO_STREAM_STATE_CLOSED);
205 
206     mediametrics::LogItem(mMetricsId)
207         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
208         .record();
209     return result;
210 }
211 
startDevice()212 aaudio_result_t AAudioServiceStreamBase::startDevice() {
213     mClientHandle = AUDIO_PORT_HANDLE_NONE;
214     sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
215     if (endpoint == nullptr) {
216         ALOGE("%s() has no endpoint", __func__);
217         return AAUDIO_ERROR_INVALID_STATE;
218     }
219     return endpoint->startStream(this, &mClientHandle);
220 }
221 
222 /**
223  * Start the flow of audio data.
224  *
225  * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
226  */
start()227 aaudio_result_t AAudioServiceStreamBase::start() {
228     std::lock_guard<std::mutex> lock(mLock);
229 
230     const int64_t beginNs = AudioClock::getNanoseconds();
231     aaudio_result_t result = AAUDIO_OK;
232 
233     if (auto state = getState();
234         state == AAUDIO_STREAM_STATE_CLOSED || state == AAUDIO_STREAM_STATE_DISCONNECTED) {
235         ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
236                 __func__, getHandle());
237         return AAUDIO_ERROR_INVALID_STATE;
238     }
239 
240     mediametrics::Defer defer([&] {
241         mediametrics::LogItem(mMetricsId)
242             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
243             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
244             .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
245             .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
246             .record(); });
247 
248     if (isRunning()) {
249         return result;
250     }
251 
252     setFlowing(false);
253     setSuspended(false);
254 
255     // Start with fresh presentation timestamps.
256     mAtomicStreamTimestamp.clear();
257 
258     mClientHandle = AUDIO_PORT_HANDLE_NONE;
259     result = startDevice();
260     if (result != AAUDIO_OK) goto error;
261 
262     // This should happen at the end of the start.
263     sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
264     setState(AAUDIO_STREAM_STATE_STARTED);
265     mThreadEnabled.store(true);
266     result = mTimestampThread.start(this);
267     if (result != AAUDIO_OK) goto error;
268 
269     return result;
270 
271 error:
272     disconnect_l();
273     return result;
274 }
275 
pause()276 aaudio_result_t AAudioServiceStreamBase::pause() {
277     std::lock_guard<std::mutex> lock(mLock);
278     return pause_l();
279 }
280 
pause_l()281 aaudio_result_t AAudioServiceStreamBase::pause_l() {
282     aaudio_result_t result = AAUDIO_OK;
283     if (!isRunning()) {
284         return result;
285     }
286     const int64_t beginNs = AudioClock::getNanoseconds();
287 
288     mediametrics::Defer defer([&] {
289         mediametrics::LogItem(mMetricsId)
290             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
291             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
292             .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
293             .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
294             .record(); });
295 
296     result = stopTimestampThread();
297     if (result != AAUDIO_OK) {
298         disconnect_l();
299         return result;
300     }
301 
302     sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
303     if (endpoint == nullptr) {
304         ALOGE("%s() has no endpoint", __func__);
305         result =  AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
306         return result;
307     }
308     result = endpoint->stopStream(this, mClientHandle);
309     if (result != AAUDIO_OK) {
310         ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
311         disconnect_l(); // TODO should we return or pause Base first?
312     }
313 
314     sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
315     setState(AAUDIO_STREAM_STATE_PAUSED);
316     return result;
317 }
318 
stop()319 aaudio_result_t AAudioServiceStreamBase::stop() {
320     std::lock_guard<std::mutex> lock(mLock);
321     return stop_l();
322 }
323 
stop_l()324 aaudio_result_t AAudioServiceStreamBase::stop_l() {
325     aaudio_result_t result = AAUDIO_OK;
326     if (!isRunning()) {
327         return result;
328     }
329     const int64_t beginNs = AudioClock::getNanoseconds();
330 
331     mediametrics::Defer defer([&] {
332         mediametrics::LogItem(mMetricsId)
333             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
334             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
335             .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
336             .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
337             .record(); });
338 
339     setState(AAUDIO_STREAM_STATE_STOPPING);
340 
341     // Temporarily unlock because we are joining the timestamp thread and it may try
342     // to acquire mLock.
343     mLock.unlock();
344     result = stopTimestampThread();
345     mLock.lock();
346 
347     if (result != AAUDIO_OK) {
348         disconnect_l();
349         return result;
350     }
351 
352     sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
353     if (endpoint == nullptr) {
354         ALOGE("%s() has no endpoint", __func__);
355         result =  AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
356         return result;
357     }
358     // TODO wait for data to be played out
359     result = endpoint->stopStream(this, mClientHandle);
360     if (result != AAUDIO_OK) {
361         ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
362         disconnect_l();
363         // TODO what to do with result here?
364     }
365 
366     sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
367     setState(AAUDIO_STREAM_STATE_STOPPED);
368     return result;
369 }
370 
stopTimestampThread()371 aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
372     aaudio_result_t result = AAUDIO_OK;
373     // clear flag that tells thread to loop
374     if (mThreadEnabled.exchange(false)) {
375         result = mTimestampThread.stop();
376     }
377     return result;
378 }
379 
flush()380 aaudio_result_t AAudioServiceStreamBase::flush() {
381     std::lock_guard<std::mutex> lock(mLock);
382     aaudio_result_t result = AAudio_isFlushAllowed(getState());
383     if (result != AAUDIO_OK) {
384         return result;
385     }
386     const int64_t beginNs = AudioClock::getNanoseconds();
387 
388     mediametrics::Defer defer([&] {
389         mediametrics::LogItem(mMetricsId)
390             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
391             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
392             .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
393             .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
394             .record(); });
395 
396     // Data will get flushed when the client receives the FLUSHED event.
397     sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
398     setState(AAUDIO_STREAM_STATE_FLUSHED);
399     return AAUDIO_OK;
400 }
401 
402 // implement Runnable, periodically send timestamps to client
403 __attribute__((no_sanitize("integer")))
run()404 void AAudioServiceStreamBase::run() {
405     ALOGD("%s() %s entering >>>>>>>>>>>>>> TIMESTAMPS", __func__, getTypeText());
406     TimestampScheduler timestampScheduler;
407     timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
408     timestampScheduler.start(AudioClock::getNanoseconds());
409     int64_t nextTime = timestampScheduler.nextAbsoluteTime();
410     int32_t loopCount = 0;
411     aaudio_result_t result = AAUDIO_OK;
412     while(mThreadEnabled.load()) {
413         loopCount++;
414         if (AudioClock::getNanoseconds() >= nextTime) {
415             result = sendCurrentTimestamp();
416             if (result != AAUDIO_OK) {
417                 ALOGE("%s() timestamp thread got result = %d", __func__, result);
418                 break;
419             }
420             nextTime = timestampScheduler.nextAbsoluteTime();
421         } else  {
422             // Sleep until it is time to send the next timestamp.
423             // TODO Wait for a signal with a timeout so that we can stop more quickly.
424             AudioClock::sleepUntilNanoTime(nextTime);
425         }
426     }
427     // This was moved from the calls in stop_l() and pause_l(), which could cause a deadlock
428     // if it resulted in a call to disconnect.
429     if (result == AAUDIO_OK) {
430         (void) sendCurrentTimestamp();
431     }
432     ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< TIMESTAMPS",
433           __func__, getTypeText(), loopCount);
434 }
435 
disconnect()436 void AAudioServiceStreamBase::disconnect() {
437     std::lock_guard<std::mutex> lock(mLock);
438     disconnect_l();
439 }
440 
disconnect_l()441 void AAudioServiceStreamBase::disconnect_l() {
442     if (getState() != AAUDIO_STREAM_STATE_DISCONNECTED
443         && getState() != AAUDIO_STREAM_STATE_CLOSED) {
444 
445         mediametrics::LogItem(mMetricsId)
446             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
447             .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
448             .record();
449 
450         sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
451         setState(AAUDIO_STREAM_STATE_DISCONNECTED);
452     }
453 }
454 
registerAudioThread(pid_t clientThreadId,int priority)455 aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId,
456         int priority) {
457     std::lock_guard<std::mutex> lock(mLock);
458     aaudio_result_t result = AAUDIO_OK;
459     if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
460         ALOGE("AAudioService::registerAudioThread(), thread already registered");
461         result = AAUDIO_ERROR_INVALID_STATE;
462     } else {
463         const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
464         setRegisteredThread(clientThreadId);
465         int err = android::requestPriority(ownerPid, clientThreadId,
466                                            priority, true /* isForApp */);
467         if (err != 0) {
468             ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
469                   clientThreadId, errno, priority);
470             result = AAUDIO_ERROR_INTERNAL;
471         }
472     }
473     return result;
474 }
475 
unregisterAudioThread(pid_t clientThreadId)476 aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
477     std::lock_guard<std::mutex> lock(mLock);
478     aaudio_result_t result = AAUDIO_OK;
479     if (getRegisteredThread() != clientThreadId) {
480         ALOGE("%s(), wrong thread", __func__);
481         result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
482     } else {
483         setRegisteredThread(0);
484     }
485     return result;
486 }
487 
setState(aaudio_stream_state_t state)488 void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
489     // CLOSED is a final state.
490     if (mState != AAUDIO_STREAM_STATE_CLOSED) {
491         mState = state;
492     } else {
493         ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
494     }
495 }
496 
sendServiceEvent(aaudio_service_event_t event,double dataDouble)497 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
498                                                           double  dataDouble) {
499     AAudioServiceMessage command;
500     command.what = AAudioServiceMessage::code::EVENT;
501     command.event.event = event;
502     command.event.dataDouble = dataDouble;
503     return writeUpMessageQueue(&command);
504 }
505 
sendServiceEvent(aaudio_service_event_t event,int64_t dataLong)506 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
507                                                           int64_t dataLong) {
508     AAudioServiceMessage command;
509     command.what = AAudioServiceMessage::code::EVENT;
510     command.event.event = event;
511     command.event.dataLong = dataLong;
512     return writeUpMessageQueue(&command);
513 }
514 
isUpMessageQueueBusy()515 bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
516     std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
517     if (mUpMessageQueue == nullptr) {
518         ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
519         return true;
520     }
521     int32_t framesAvailable = mUpMessageQueue->getFifoBuffer()
522         ->getFullFramesAvailable();
523     int32_t capacity = mUpMessageQueue->getFifoBuffer()
524         ->getBufferCapacityInFrames();
525     // Is it half full or more
526     return framesAvailable >= (capacity / 2);
527 }
528 
writeUpMessageQueue(AAudioServiceMessage * command)529 aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
530     std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
531     if (mUpMessageQueue == nullptr) {
532         ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
533         return AAUDIO_ERROR_NULL;
534     }
535     int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
536     if (count != 1) {
537         ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
538               __func__, command->what, getTypeText());
539         setSuspended(true);
540         return AAUDIO_ERROR_WOULD_BLOCK;
541     } else {
542         return AAUDIO_OK;
543     }
544 }
545 
sendXRunCount(int32_t xRunCount)546 aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
547     return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
548 }
549 
sendCurrentTimestamp()550 aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
551     AAudioServiceMessage command;
552     // It is not worth filling up the queue with timestamps.
553     // That can cause the stream to get suspended.
554     // So just drop the timestamp if the queue is getting full.
555     if (isUpMessageQueueBusy()) {
556         return AAUDIO_OK;
557     }
558 
559     // Send a timestamp for the clock model.
560     aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
561                                                     &command.timestamp.timestamp);
562     if (result == AAUDIO_OK) {
563         ALOGV("%s() SERVICE  %8lld at %lld", __func__,
564               (long long) command.timestamp.position,
565               (long long) command.timestamp.timestamp);
566         command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
567         result = writeUpMessageQueue(&command);
568 
569         if (result == AAUDIO_OK) {
570             // Send a hardware timestamp for presentation time.
571             result = getHardwareTimestamp(&command.timestamp.position,
572                                           &command.timestamp.timestamp);
573             if (result == AAUDIO_OK) {
574                 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
575                       (long long) command.timestamp.position,
576                       (long long) command.timestamp.timestamp);
577                 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
578                 result = writeUpMessageQueue(&command);
579             }
580         }
581     }
582 
583     if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
584         result = AAUDIO_OK; // just not available yet, try again later
585     }
586     return result;
587 }
588 
589 /**
590  * Get an immutable description of the in-memory queues
591  * used to communicate with the underlying HAL or Service.
592  */
getDescription(AudioEndpointParcelable & parcelable)593 aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
594     std::lock_guard<std::mutex> lock(mLock);
595     {
596         std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
597         if (mUpMessageQueue == nullptr) {
598             ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
599             return AAUDIO_ERROR_NULL;
600         }
601         // Gather information on the message queue.
602         mUpMessageQueue->fillParcelable(parcelable,
603                                         parcelable.mUpMessageQueueParcelable);
604     }
605     return getAudioDataDescription(parcelable);
606 }
607 
onVolumeChanged(float volume)608 void AAudioServiceStreamBase::onVolumeChanged(float volume) {
609     sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
610 }
611 
incrementServiceReferenceCount_l()612 int32_t AAudioServiceStreamBase::incrementServiceReferenceCount_l() {
613     return ++mCallingCount;
614 }
615 
decrementServiceReferenceCount_l()616 int32_t AAudioServiceStreamBase::decrementServiceReferenceCount_l() {
617     int32_t count = --mCallingCount;
618     // Each call to increment should be balanced with one call to decrement.
619     assert(count >= 0);
620     return count;
621 }
622