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 <com_android_media_aaudio.h>
26 #include <media/MediaMetricsItem.h>
27 #include <media/TypeConverter.h>
28 #include <mediautils/SchedulingPolicyService.h>
29
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
39 using namespace android; // TODO just import names needed
40 using namespace aaudio; // TODO just import names needed
41
42 using content::AttributionSourceState;
43
44 static const int64_t TIMEOUT_NANOS = 3LL * 1000 * 1000 * 1000;
45 // If the stream is idle for more than `IDLE_TIMEOUT_NANOS`, the stream will be put into standby.
46 static const int64_t IDLE_TIMEOUT_NANOS = 3e9;
47
48 /**
49 * Base class for streams in the service.
50 * @return
51 */
52
AAudioServiceStreamBase(AAudioService & audioService)53 AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
54 : mCommandThread("AACommand")
55 , mAtomicStreamTimestamp()
56 , mAudioService(audioService) {
57 mMmapClient.attributionSource = AttributionSourceState();
58 }
59
~AAudioServiceStreamBase()60 AAudioServiceStreamBase::~AAudioServiceStreamBase() {
61 ALOGD("%s() called", __func__);
62
63 // May not be set if open failed.
64 if (mMetricsId.size() > 0) {
65 mediametrics::LogItem(mMetricsId)
66 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
67 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
68 .record();
69 }
70
71 // If the stream is deleted when OPEN or in use then audio resources will leak.
72 // This would indicate an internal error. So we want to find this ASAP.
73 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
74 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED),
75 "service stream %p still open, state = %d",
76 this, getState());
77
78 // Stop the command thread before destroying.
79 stopCommandThread();
80 }
81
dumpHeader()82 std::string AAudioServiceStreamBase::dumpHeader() {
83 return {" T Handle UId Port Run State Format Burst Chan Mask Capacity"
84 " HwFormat HwChan HwRate"};
85 }
86
dump() const87 std::string AAudioServiceStreamBase::dump() const {
88 std::stringstream result;
89
90 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
91 << std::dec << std::setfill(' ') ;
92 result << std::setw(6) << mMmapClient.attributionSource.uid;
93 result << std::setw(7) << mClientHandle;
94 result << std::setw(4) << (isRunning() ? "yes" : " no");
95 result << std::setw(6) << getState();
96 result << std::setw(7) << getFormat();
97 result << std::setw(6) << mFramesPerBurst;
98 result << std::setw(5) << getSamplesPerFrame();
99 result << std::setw(8) << std::hex << getChannelMask() << std::dec;
100 result << std::setw(9) << getBufferCapacity();
101 result << std::setw(9) << getHardwareFormat();
102 result << std::setw(7) << getHardwareSamplesPerFrame();
103 result << std::setw(7) << getHardwareSampleRate();
104
105 return result.str();
106 }
107
logOpen(aaudio_handle_t streamHandle)108 void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
109 // This is the first log sent from the AAudio Service for a stream.
110 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
111 + std::to_string(streamHandle);
112
113 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
114
115 // Once this item is logged by the server, the client with the same PID, UID
116 // can also log properties.
117 mediametrics::LogItem(mMetricsId)
118 .setPid(getOwnerProcessId())
119 .setUid(getOwnerUserId())
120 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
121 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
122 // the following are immutable
123 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
124 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
125 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
126 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
127 .set(AMEDIAMETRICS_PROP_DIRECTION,
128 AudioGlobal_convertDirectionToText(getDirection()))
129 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
130 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
131 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
132 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
133 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
134 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
135 .record();
136 }
137
open(const aaudio::AAudioStreamRequest & request)138 aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
139 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
140 aaudio_result_t result = AAUDIO_OK;
141
142 mMmapClient.attributionSource = request.getAttributionSource();
143 // TODO b/182392769: use attribution source util
144 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
145 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
146 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
147 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
148
149 // Limit scope of lock to avoid recursive lock in close().
150 {
151 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
152 if (mUpMessageQueue != nullptr) {
153 ALOGE("%s() called twice", __func__);
154 return AAUDIO_ERROR_INVALID_STATE;
155 }
156
157 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
158 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
159 QUEUE_UP_CAPACITY_COMMANDS);
160 if (result != AAUDIO_OK) {
161 goto error;
162 }
163
164 // This is not protected by a lock because the stream cannot be
165 // referenced until the service returns a handle to the client.
166 // So only one thread can open a stream.
167 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
168 request);
169 if (mServiceEndpoint == nullptr) {
170 result = AAUDIO_ERROR_UNAVAILABLE;
171 goto error;
172 }
173 // Save a weak pointer that we will use to access the endpoint.
174 mServiceEndpointWeak = mServiceEndpoint;
175
176 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
177 copyFrom(*mServiceEndpoint);
178 }
179
180 // Make sure this object does not get deleted before the run() method
181 // can protect it by making a strong pointer.
182 mCommandQueue.startWaiting();
183 mThreadEnabled = true;
184 incStrong(nullptr); // See run() method.
185 result = mCommandThread.start(this);
186 if (result != AAUDIO_OK) {
187 decStrong(nullptr); // run() can't do it so we have to do it here.
188 goto error;
189 }
190 return result;
191
192 error:
193 closeAndClear();
194 stopCommandThread();
195 return result;
196 }
197
close()198 aaudio_result_t AAudioServiceStreamBase::close() {
199 aaudio_result_t result = sendCommand(CLOSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
200 if (result == AAUDIO_ERROR_ALREADY_CLOSED) {
201 // AAUDIO_ERROR_ALREADY_CLOSED is not a really error but just indicate the stream has
202 // already been closed. In that case, there is no need to close the stream once more.
203 ALOGD("The stream(%d) is already closed", mHandle);
204 return AAUDIO_OK;
205 }
206
207 stopCommandThread();
208
209 return result;
210 }
211
close_l()212 aaudio_result_t AAudioServiceStreamBase::close_l() {
213 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
214 return AAUDIO_ERROR_ALREADY_CLOSED;
215 }
216
217 // This will stop the stream, just in case it was not already stopped.
218 stop_l();
219
220 return closeAndClear();
221 }
222
startDevice_l()223 aaudio_result_t AAudioServiceStreamBase::startDevice_l() {
224 mClientHandle = AUDIO_PORT_HANDLE_NONE;
225 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
226 if (endpoint == nullptr) {
227 ALOGE("%s() has no endpoint", __func__);
228 return AAUDIO_ERROR_INVALID_STATE;
229 }
230 if (!endpoint->isConnected()) {
231 ALOGE("%s() endpoint was already disconnected", __func__);
232 return AAUDIO_ERROR_DISCONNECTED;
233 }
234 return endpoint->startStream(this, &mClientHandle);
235 }
236
237 /**
238 * Start the flow of audio data.
239 *
240 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
241 */
start()242 aaudio_result_t AAudioServiceStreamBase::start() {
243 return sendCommand(START, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
244 }
245
start_l()246 aaudio_result_t AAudioServiceStreamBase::start_l() {
247 const int64_t beginNs = AudioClock::getNanoseconds();
248 aaudio_result_t result = AAUDIO_OK;
249
250 if (auto state = getState();
251 state == AAUDIO_STREAM_STATE_CLOSED || isDisconnected_l()) {
252 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
253 __func__, getHandle());
254 return AAUDIO_ERROR_INVALID_STATE;
255 }
256
257 if (mStandby) {
258 ALOGW("%s() the stream is standby, return ERROR_STANDBY, "
259 "expecting the client call exitStandby before start", __func__);
260 return AAUDIO_ERROR_STANDBY;
261 }
262
263 mediametrics::Defer defer([&] {
264 mediametrics::LogItem(mMetricsId)
265 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
266 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
267 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
268 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
269 .record(); });
270
271 if (isRunning()) {
272 return result;
273 }
274
275 setFlowing(false);
276 setSuspended(false);
277
278 // Start with fresh presentation timestamps.
279 mAtomicStreamTimestamp.clear();
280
281 mClientHandle = AUDIO_PORT_HANDLE_NONE;
282 result = startDevice_l();
283 if (result != AAUDIO_OK) goto error;
284
285 // This should happen at the end of the start.
286 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED, static_cast<int64_t>(mClientHandle));
287 setState(AAUDIO_STREAM_STATE_STARTED);
288
289 return result;
290
291 error:
292 disconnect_l();
293 return result;
294 }
295
pause()296 aaudio_result_t AAudioServiceStreamBase::pause() {
297 return sendCommand(PAUSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
298 }
299
pause_l()300 aaudio_result_t AAudioServiceStreamBase::pause_l() {
301 aaudio_result_t result = AAUDIO_OK;
302 if (!isRunning()) {
303 return result;
304 }
305 const int64_t beginNs = AudioClock::getNanoseconds();
306
307 mediametrics::Defer defer([&] {
308 mediametrics::LogItem(mMetricsId)
309 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
310 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
311 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
312 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
313 .record(); });
314
315 setState(AAUDIO_STREAM_STATE_PAUSING);
316
317 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
318 if (endpoint == nullptr) {
319 ALOGE("%s() has no endpoint", __func__);
320 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
321 return result;
322 }
323 result = endpoint->stopStream(this, mClientHandle);
324 if (result != AAUDIO_OK) {
325 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
326 disconnect_l(); // TODO should we return or pause Base first?
327 }
328
329 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
330 setState(AAUDIO_STREAM_STATE_PAUSED);
331 return result;
332 }
333
stop()334 aaudio_result_t AAudioServiceStreamBase::stop() {
335 return sendCommand(STOP, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
336 }
337
stop_l()338 aaudio_result_t AAudioServiceStreamBase::stop_l() {
339 aaudio_result_t result = AAUDIO_OK;
340 if (!isRunning()) {
341 ALOGW("%s() stream not running, returning early", __func__);
342 return result;
343 }
344 const int64_t beginNs = AudioClock::getNanoseconds();
345
346 mediametrics::Defer defer([&] {
347 mediametrics::LogItem(mMetricsId)
348 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
349 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
350 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
351 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
352 .record(); });
353
354 setState(AAUDIO_STREAM_STATE_STOPPING);
355
356 if (result != AAUDIO_OK) {
357 disconnect_l();
358 return result;
359 }
360
361 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
362 if (endpoint == nullptr) {
363 ALOGE("%s() has no endpoint", __func__);
364 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
365 return result;
366 }
367 // TODO wait for data to be played out
368 result = endpoint->stopStream(this, mClientHandle);
369 if (result != AAUDIO_OK) {
370 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
371 disconnect_l();
372 // TODO what to do with result here?
373 }
374
375 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
376 setState(AAUDIO_STREAM_STATE_STOPPED);
377 return result;
378 }
379
flush()380 aaudio_result_t AAudioServiceStreamBase::flush() {
381 return sendCommand(FLUSH, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
382 }
383
flush_l()384 aaudio_result_t AAudioServiceStreamBase::flush_l() {
385 aaudio_result_t result = AAudio_isFlushAllowed(getState());
386 if (result != AAUDIO_OK) {
387 return result;
388 }
389 const int64_t beginNs = AudioClock::getNanoseconds();
390
391 mediametrics::Defer defer([&] {
392 mediametrics::LogItem(mMetricsId)
393 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
394 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
395 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
396 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
397 .record(); });
398
399 // Data will get flushed when the client receives the FLUSHED event.
400 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
401 setState(AAUDIO_STREAM_STATE_FLUSHED);
402 return AAUDIO_OK;
403 }
404
405 // implement Runnable, periodically send timestamps to client and process commands from queue.
406 // Enter standby mode if idle for a while.
407 __attribute__((no_sanitize("integer")))
run()408 void AAudioServiceStreamBase::run() {
409 ALOGD("%s() %s entering >>>>>>>>>>>>>> COMMANDS", __func__, getTypeText());
410 // Hold onto the ref counted stream until the end.
411 android::sp<AAudioServiceStreamBase> holdStream(this);
412 TimestampScheduler timestampScheduler;
413 int64_t nextTimestampReportTime;
414 int64_t nextDataReportTime;
415 // When to try to enter standby.
416 int64_t standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
417 // Balance the incStrong from when the thread was launched.
418 holdStream->decStrong(nullptr);
419
420 // Taking mLock while starting the thread. All the operation must be able to
421 // run with holding the lock.
422 std::scoped_lock<std::mutex> _l(mLock);
423
424 int32_t loopCount = 0;
425 while (mThreadEnabled.load()) {
426 loopCount++;
427 int64_t timeoutNanos = -1; // wait forever
428 if (isDisconnected_l() || isIdle_l()) {
429 if (isStandbyImplemented() && !isStandby_l()) {
430 // If not in standby mode, wait until standby time.
431 timeoutNanos = standbyTime - AudioClock::getNanoseconds();
432 timeoutNanos = std::max<int64_t>(0, timeoutNanos);
433 }
434 // Otherwise, keep `timeoutNanos` as -1 to wait forever until next command.
435 } else if (isRunning()) {
436 timeoutNanos = std::min(nextTimestampReportTime, nextDataReportTime)
437 - AudioClock::getNanoseconds();
438 timeoutNanos = std::max<int64_t>(0, timeoutNanos);
439 }
440 auto command = mCommandQueue.waitForCommand(timeoutNanos);
441 if (!mThreadEnabled) {
442 // Break the loop if the thread is disabled.
443 break;
444 }
445
446 // Is it time to send timestamps?
447 if (isRunning() && !isDisconnected_l()) {
448 auto currentTimestamp = AudioClock::getNanoseconds();
449 if (currentTimestamp >= nextDataReportTime) {
450 reportData_l();
451 nextDataReportTime = nextDataReportTime_l();
452 }
453 if (currentTimestamp >= nextTimestampReportTime) {
454 // It is time to update timestamp.
455 if (sendCurrentTimestamp_l() != AAUDIO_OK) {
456 ALOGE("Failed to send current timestamp, stop updating timestamp");
457 disconnect_l();
458 }
459 nextTimestampReportTime = timestampScheduler.nextAbsoluteTime();
460 }
461 }
462
463 // Is it time to enter standby?
464 if ((isIdle_l() || isDisconnected_l())
465 && isStandbyImplemented()
466 && !isStandby_l()
467 && (AudioClock::getNanoseconds() >= standbyTime)) {
468 ALOGD("%s() call standby_l(), %d loops", __func__, loopCount);
469 aaudio_result_t result = standby_l();
470 if (result != AAUDIO_OK) {
471 ALOGW("Failed to enter standby, error = %d", result);
472 // Try again later.
473 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
474 }
475 }
476
477 if (command != nullptr) {
478 ALOGD("%s() got COMMAND opcode %d after %d loops",
479 __func__, command->operationCode, loopCount);
480 std::scoped_lock<std::mutex> _commandLock(command->lock);
481 switch (command->operationCode) {
482 case START:
483 command->result = start_l();
484 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
485 timestampScheduler.start(AudioClock::getNanoseconds());
486 nextTimestampReportTime = timestampScheduler.nextAbsoluteTime();
487 nextDataReportTime = nextDataReportTime_l();
488 break;
489 case PAUSE:
490 command->result = pause_l();
491 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
492 break;
493 case STOP:
494 command->result = stop_l();
495 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
496 break;
497 case FLUSH:
498 command->result = flush_l();
499 break;
500 case CLOSE:
501 command->result = close_l();
502 break;
503 case DISCONNECT:
504 disconnect_l();
505 break;
506 case REGISTER_AUDIO_THREAD: {
507 auto param = (RegisterAudioThreadParam *) command->parameter.get();
508 command->result =
509 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
510 : registerAudioThread_l(param->mOwnerPid,
511 param->mClientThreadId,
512 param->mPriority);
513 }
514 break;
515 case UNREGISTER_AUDIO_THREAD: {
516 auto param = (UnregisterAudioThreadParam *) command->parameter.get();
517 command->result =
518 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
519 : unregisterAudioThread_l(param->mClientThreadId);
520 }
521 break;
522 case GET_DESCRIPTION: {
523 auto param = (GetDescriptionParam *) command->parameter.get();
524 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
525 : getDescription_l(param->mParcelable);
526 }
527 break;
528 case EXIT_STANDBY: {
529 auto param = (ExitStandbyParam *) command->parameter.get();
530 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
531 : exitStandby_l(param->mParcelable);
532 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
533 } break;
534 case START_CLIENT: {
535 auto param = (StartClientParam *) command->parameter.get();
536 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
537 : startClient_l(param->mClient,
538 param->mAttr,
539 param->mClientHandle);
540 } break;
541 case STOP_CLIENT: {
542 auto param = (StopClientParam *) command->parameter.get();
543 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
544 : stopClient_l(param->mClientHandle);
545 } break;
546 default:
547 ALOGE("Invalid command op code: %d", command->operationCode);
548 break;
549 }
550 if (command->isWaitingForReply) {
551 command->isWaitingForReply = false;
552 command->conditionVariable.notify_one();
553 }
554 }
555 }
556 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< COMMANDS",
557 __func__, getTypeText(), loopCount);
558 }
559
disconnect()560 void AAudioServiceStreamBase::disconnect() {
561 sendCommand(DISCONNECT);
562 }
563
disconnect_l()564 void AAudioServiceStreamBase::disconnect_l() {
565 if (!isDisconnected_l() && getState() != AAUDIO_STREAM_STATE_CLOSED) {
566
567 mediametrics::LogItem(mMetricsId)
568 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
569 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
570 .record();
571
572 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
573 setDisconnected_l(true);
574 }
575 }
576
registerAudioThread(pid_t clientThreadId,int priority)577 aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId, int priority) {
578 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
579 return sendCommand(REGISTER_AUDIO_THREAD,
580 std::make_shared<RegisterAudioThreadParam>(ownerPid, clientThreadId, priority),
581 true /*waitForReply*/,
582 TIMEOUT_NANOS);
583 }
584
registerAudioThread_l(pid_t ownerPid,pid_t clientThreadId,int priority)585 aaudio_result_t AAudioServiceStreamBase::registerAudioThread_l(
586 pid_t ownerPid, pid_t clientThreadId, int priority) {
587 aaudio_result_t result = AAUDIO_OK;
588 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
589 ALOGE("AAudioService::registerAudioThread(), thread already registered");
590 result = AAUDIO_ERROR_INVALID_STATE;
591 } else {
592 setRegisteredThread(clientThreadId);
593 int err = android::requestPriority(ownerPid, clientThreadId,
594 priority, true /* isForApp */);
595 if (err != 0) {
596 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
597 clientThreadId, errno, priority);
598 result = AAUDIO_ERROR_INTERNAL;
599 }
600 }
601 return result;
602 }
603
unregisterAudioThread(pid_t clientThreadId)604 aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
605 return sendCommand(UNREGISTER_AUDIO_THREAD,
606 std::make_shared<UnregisterAudioThreadParam>(clientThreadId),
607 true /*waitForReply*/,
608 TIMEOUT_NANOS);
609 }
610
unregisterAudioThread_l(pid_t clientThreadId)611 aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread_l(pid_t clientThreadId) {
612 aaudio_result_t result = AAUDIO_OK;
613 if (getRegisteredThread() != clientThreadId) {
614 ALOGE("%s(), wrong thread", __func__);
615 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
616 } else {
617 setRegisteredThread(0);
618 }
619 return result;
620 }
621
setState(aaudio_stream_state_t state)622 void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
623 // CLOSED is a final state.
624 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
625 mState = state;
626 } else {
627 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
628 }
629 }
630
sendServiceEvent(aaudio_service_event_t event,double dataDouble)631 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
632 double dataDouble) {
633 AAudioServiceMessage command;
634 command.what = AAudioServiceMessage::code::EVENT;
635 command.event.event = event;
636 command.event.dataDouble = dataDouble;
637 return writeUpMessageQueue(&command);
638 }
639
sendServiceEvent(aaudio_service_event_t event,int64_t dataLong)640 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
641 int64_t dataLong) {
642 AAudioServiceMessage command;
643 command.what = AAudioServiceMessage::code::EVENT;
644 command.event.event = event;
645 command.event.dataLong = dataLong;
646 return writeUpMessageQueue(&command);
647 }
648
isUpMessageQueueBusy()649 bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
650 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
651 if (mUpMessageQueue == nullptr) {
652 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
653 return true;
654 }
655 // Is it half full or more
656 return mUpMessageQueue->getFractionalFullness() >= 0.5;
657 }
658
writeUpMessageQueue(AAudioServiceMessage * command)659 aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
660 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
661 if (mUpMessageQueue == nullptr) {
662 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
663 return AAUDIO_ERROR_NULL;
664 }
665 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
666 if (count != 1) {
667 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
668 __func__, static_cast<unsigned>(command->what), getTypeText());
669 setSuspended(true);
670 return AAUDIO_ERROR_WOULD_BLOCK;
671 } else {
672 if (isSuspended()) {
673 ALOGW("%s(): Queue no longer full. Un-suspending the stream.", __func__);
674 setSuspended(false);
675 }
676 return AAUDIO_OK;
677 }
678 }
679
sendXRunCount(int32_t xRunCount)680 aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
681 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
682 }
683
sendCurrentTimestamp_l()684 aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp_l() {
685 AAudioServiceMessage command;
686 // It is not worth filling up the queue with timestamps.
687 // That can cause the stream to get suspended.
688 // So just drop the timestamp if the queue is getting full.
689 if (isUpMessageQueueBusy()) {
690 return AAUDIO_OK;
691 }
692
693 // Send a timestamp for the clock model.
694 aaudio_result_t result = getFreeRunningPosition_l(&command.timestamp.position,
695 &command.timestamp.timestamp);
696 if (result == AAUDIO_OK) {
697 ALOGV("%s() SERVICE %8lld at %lld", __func__,
698 (long long) command.timestamp.position,
699 (long long) command.timestamp.timestamp);
700 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
701 result = writeUpMessageQueue(&command);
702
703 if (result == AAUDIO_OK) {
704 // Send a hardware timestamp for presentation time.
705 result = getHardwareTimestamp_l(&command.timestamp.position,
706 &command.timestamp.timestamp);
707 if (result == AAUDIO_OK) {
708 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
709 (long long) command.timestamp.position,
710 (long long) command.timestamp.timestamp);
711 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
712 result = writeUpMessageQueue(&command);
713 }
714 }
715 }
716
717 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
718 result = AAUDIO_OK; // just not available yet, try again later
719 }
720 return result;
721 }
722
723 /**
724 * Get an immutable description of the in-memory queues
725 * used to communicate with the underlying HAL or Service.
726 */
getDescription(AudioEndpointParcelable & parcelable)727 aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
728 return sendCommand(
729 GET_DESCRIPTION,
730 std::make_shared<GetDescriptionParam>(&parcelable),
731 true /*waitForReply*/,
732 TIMEOUT_NANOS);
733 }
734
getDescription_l(AudioEndpointParcelable * parcelable)735 aaudio_result_t AAudioServiceStreamBase::getDescription_l(AudioEndpointParcelable* parcelable) {
736 {
737 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
738 if (mUpMessageQueue == nullptr) {
739 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
740 return AAUDIO_ERROR_NULL;
741 }
742 // Gather information on the message queue.
743 mUpMessageQueue->fillParcelable(parcelable,
744 parcelable->mUpMessageQueueParcelable);
745 }
746 return getAudioDataDescription_l(parcelable);
747 }
748
exitStandby(AudioEndpointParcelable * parcelable)749 aaudio_result_t AAudioServiceStreamBase::exitStandby(AudioEndpointParcelable *parcelable) {
750 auto command = std::make_shared<AAudioCommand>(
751 EXIT_STANDBY,
752 std::make_shared<ExitStandbyParam>(parcelable),
753 true /*waitForReply*/,
754 TIMEOUT_NANOS);
755 return mCommandQueue.sendCommand(command);
756 }
757
sendStartClientCommand(const android::AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * clientHandle)758 aaudio_result_t AAudioServiceStreamBase::sendStartClientCommand(const android::AudioClient &client,
759 const audio_attributes_t *attr,
760 audio_port_handle_t *clientHandle) {
761 auto command = std::make_shared<AAudioCommand>(
762 START_CLIENT,
763 std::make_shared<StartClientParam>(client, attr, clientHandle),
764 true /*waitForReply*/,
765 TIMEOUT_NANOS);
766 return mCommandQueue.sendCommand(command);
767 }
768
sendStopClientCommand(audio_port_handle_t clientHandle)769 aaudio_result_t AAudioServiceStreamBase::sendStopClientCommand(audio_port_handle_t clientHandle) {
770 auto command = std::make_shared<AAudioCommand>(
771 STOP_CLIENT,
772 std::make_shared<StopClientParam>(clientHandle),
773 true /*waitForReply*/,
774 TIMEOUT_NANOS);
775 return mCommandQueue.sendCommand(command);
776 }
777
onVolumeChanged(float volume)778 void AAudioServiceStreamBase::onVolumeChanged(float volume) {
779 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
780 }
781
sendCommand(aaudio_command_opcode opCode,std::shared_ptr<AAudioCommandParam> param,bool waitForReply,int64_t timeoutNanos)782 aaudio_result_t AAudioServiceStreamBase::sendCommand(aaudio_command_opcode opCode,
783 std::shared_ptr<AAudioCommandParam> param,
784 bool waitForReply,
785 int64_t timeoutNanos) {
786 return mCommandQueue.sendCommand(std::make_shared<AAudioCommand>(
787 opCode, param, waitForReply, timeoutNanos));
788 }
789
closeAndClear()790 aaudio_result_t AAudioServiceStreamBase::closeAndClear() {
791 aaudio_result_t result = AAUDIO_OK;
792 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
793 if (endpoint == nullptr) {
794 result = AAUDIO_ERROR_INVALID_STATE;
795 } else {
796 endpoint->unregisterStream(this);
797 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
798 endpointManager.closeEndpoint(endpoint);
799
800 // AAudioService::closeStream() prevents two threads from closing at the same time.
801 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
802 }
803
804 setState(AAUDIO_STREAM_STATE_CLOSED);
805
806 mediametrics::LogItem(mMetricsId)
807 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
808 .record();
809 return result;
810 }
811
stopCommandThread()812 void AAudioServiceStreamBase::stopCommandThread() {
813 bool threadEnabled = true;
814 if (mThreadEnabled.compare_exchange_strong(threadEnabled, false)) {
815 mCommandQueue.stopWaiting();
816 mCommandThread.stop();
817 }
818 }
819