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/AAudioServiceMessage.h"
30 #include "core/AudioGlobal.h"
31 #include "utility/AudioClock.h"
32
33 #include "AAudioEndpointManager.h"
34 #include "AAudioService.h"
35 #include "AAudioServiceEndpoint.h"
36 #include "AAudioServiceStreamBase.h"
37
38 using namespace android; // TODO just import names needed
39 using namespace aaudio; // TODO just import names needed
40
41 using content::AttributionSourceState;
42
43 static const int64_t TIMEOUT_NANOS = 3LL * 1000 * 1000 * 1000;
44 // If the stream is idle for more than `IDLE_TIMEOUT_NANOS`, the stream will be put into standby.
45 static const int64_t IDLE_TIMEOUT_NANOS = 3e9;
46
47 /**
48 * Base class for streams in the service.
49 * @return
50 */
51
AAudioServiceStreamBase(AAudioService & audioService)52 AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
53 : mCommandThread("AACommand")
54 , mAtomicStreamTimestamp()
55 , mAudioService(audioService) {
56 mMmapClient.attributionSource = AttributionSourceState();
57 }
58
~AAudioServiceStreamBase()59 AAudioServiceStreamBase::~AAudioServiceStreamBase() {
60 ALOGD("%s() called", __func__);
61
62 // May not be set if open failed.
63 if (mMetricsId.size() > 0) {
64 mediametrics::LogItem(mMetricsId)
65 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
66 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
67 .record();
68 }
69
70 // If the stream is deleted when OPEN or in use then audio resources will leak.
71 // This would indicate an internal error. So we want to find this ASAP.
72 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
73 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED),
74 "service stream %p still open, state = %d",
75 this, getState());
76
77 // Stop the command thread before destroying.
78 if (mThreadEnabled) {
79 mThreadEnabled = false;
80 mCommandQueue.stopWaiting();
81 mCommandThread.stop();
82 }
83 }
84
dumpHeader()85 std::string AAudioServiceStreamBase::dumpHeader() {
86 return std::string(
87 " T Handle UId Port Run State Format Burst Chan Mask Capacity");
88 }
89
dump() const90 std::string AAudioServiceStreamBase::dump() const {
91 std::stringstream result;
92
93 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
94 << std::dec << std::setfill(' ') ;
95 result << std::setw(6) << mMmapClient.attributionSource.uid;
96 result << std::setw(7) << mClientHandle;
97 result << std::setw(4) << (isRunning() ? "yes" : " no");
98 result << std::setw(6) << getState();
99 result << std::setw(7) << getFormat();
100 result << std::setw(6) << mFramesPerBurst;
101 result << std::setw(5) << getSamplesPerFrame();
102 result << std::setw(8) << std::hex << getChannelMask() << std::dec;
103 result << std::setw(9) << getBufferCapacity();
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 mThreadEnabled = false;
195 mCommandQueue.stopWaiting();
196 mCommandThread.stop();
197 return result;
198 }
199
close()200 aaudio_result_t AAudioServiceStreamBase::close() {
201 aaudio_result_t result = sendCommand(CLOSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
202
203 // Stop the command thread as the stream is closed.
204 mThreadEnabled = false;
205 mCommandQueue.stopWaiting();
206 mCommandThread.stop();
207
208 return result;
209 }
210
close_l()211 aaudio_result_t AAudioServiceStreamBase::close_l() {
212 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
213 return AAUDIO_OK;
214 }
215
216 // This will stop the stream, just in case it was not already stopped.
217 stop_l();
218
219 return closeAndClear();
220 }
221
startDevice()222 aaudio_result_t AAudioServiceStreamBase::startDevice() {
223 mClientHandle = AUDIO_PORT_HANDLE_NONE;
224 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
225 if (endpoint == nullptr) {
226 ALOGE("%s() has no endpoint", __func__);
227 return AAUDIO_ERROR_INVALID_STATE;
228 }
229 return endpoint->startStream(this, &mClientHandle);
230 }
231
232 /**
233 * Start the flow of audio data.
234 *
235 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
236 */
start()237 aaudio_result_t AAudioServiceStreamBase::start() {
238 return sendCommand(START, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
239 }
240
start_l()241 aaudio_result_t AAudioServiceStreamBase::start_l() {
242 const int64_t beginNs = AudioClock::getNanoseconds();
243 aaudio_result_t result = AAUDIO_OK;
244
245 if (auto state = getState();
246 state == AAUDIO_STREAM_STATE_CLOSED || isDisconnected_l()) {
247 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
248 __func__, getHandle());
249 return AAUDIO_ERROR_INVALID_STATE;
250 }
251
252 if (mStandby) {
253 ALOGW("%s() the stream is standby, return ERROR_STANDBY, "
254 "expecting the client call exitStandby before start", __func__);
255 return AAUDIO_ERROR_STANDBY;
256 }
257
258 mediametrics::Defer defer([&] {
259 mediametrics::LogItem(mMetricsId)
260 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
261 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
262 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
263 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
264 .record(); });
265
266 if (isRunning()) {
267 return result;
268 }
269
270 setFlowing(false);
271 setSuspended(false);
272
273 // Start with fresh presentation timestamps.
274 mAtomicStreamTimestamp.clear();
275
276 mClientHandle = AUDIO_PORT_HANDLE_NONE;
277 result = startDevice();
278 if (result != AAUDIO_OK) goto error;
279
280 // This should happen at the end of the start.
281 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
282 setState(AAUDIO_STREAM_STATE_STARTED);
283
284 return result;
285
286 error:
287 disconnect_l();
288 return result;
289 }
290
pause()291 aaudio_result_t AAudioServiceStreamBase::pause() {
292 return sendCommand(PAUSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
293 }
294
pause_l()295 aaudio_result_t AAudioServiceStreamBase::pause_l() {
296 aaudio_result_t result = AAUDIO_OK;
297 if (!isRunning()) {
298 return result;
299 }
300 const int64_t beginNs = AudioClock::getNanoseconds();
301
302 mediametrics::Defer defer([&] {
303 mediametrics::LogItem(mMetricsId)
304 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
305 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
306 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
307 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
308 .record(); });
309
310 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
311 if (endpoint == nullptr) {
312 ALOGE("%s() has no endpoint", __func__);
313 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
314 return result;
315 }
316 result = endpoint->stopStream(this, mClientHandle);
317 if (result != AAUDIO_OK) {
318 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
319 disconnect_l(); // TODO should we return or pause Base first?
320 }
321
322 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
323 setState(AAUDIO_STREAM_STATE_PAUSED);
324 return result;
325 }
326
stop()327 aaudio_result_t AAudioServiceStreamBase::stop() {
328 return sendCommand(STOP, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
329 }
330
stop_l()331 aaudio_result_t AAudioServiceStreamBase::stop_l() {
332 aaudio_result_t result = AAUDIO_OK;
333 if (!isRunning()) {
334 return result;
335 }
336 const int64_t beginNs = AudioClock::getNanoseconds();
337
338 mediametrics::Defer defer([&] {
339 mediametrics::LogItem(mMetricsId)
340 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
341 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
342 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
343 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
344 .record(); });
345
346 setState(AAUDIO_STREAM_STATE_STOPPING);
347
348 if (result != AAUDIO_OK) {
349 disconnect_l();
350 return result;
351 }
352
353 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
354 if (endpoint == nullptr) {
355 ALOGE("%s() has no endpoint", __func__);
356 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
357 return result;
358 }
359 // TODO wait for data to be played out
360 result = endpoint->stopStream(this, mClientHandle);
361 if (result != AAUDIO_OK) {
362 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
363 disconnect_l();
364 // TODO what to do with result here?
365 }
366
367 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
368 setState(AAUDIO_STREAM_STATE_STOPPED);
369 return result;
370 }
371
flush()372 aaudio_result_t AAudioServiceStreamBase::flush() {
373 return sendCommand(FLUSH, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
374 }
375
flush_l()376 aaudio_result_t AAudioServiceStreamBase::flush_l() {
377 aaudio_result_t result = AAudio_isFlushAllowed(getState());
378 if (result != AAUDIO_OK) {
379 return result;
380 }
381 const int64_t beginNs = AudioClock::getNanoseconds();
382
383 mediametrics::Defer defer([&] {
384 mediametrics::LogItem(mMetricsId)
385 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
386 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
387 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
388 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
389 .record(); });
390
391 // Data will get flushed when the client receives the FLUSHED event.
392 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
393 setState(AAUDIO_STREAM_STATE_FLUSHED);
394 return AAUDIO_OK;
395 }
396
397 // implement Runnable, periodically send timestamps to client and process commands from queue.
398 __attribute__((no_sanitize("integer")))
run()399 void AAudioServiceStreamBase::run() {
400 ALOGD("%s() %s entering >>>>>>>>>>>>>> COMMANDS", __func__, getTypeText());
401 // Hold onto the ref counted stream until the end.
402 android::sp<AAudioServiceStreamBase> holdStream(this);
403 TimestampScheduler timestampScheduler;
404 int64_t nextTime;
405 int64_t standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
406 // Balance the incStrong from when the thread was launched.
407 holdStream->decStrong(nullptr);
408
409 // Taking mLock while starting the thread. All the operation must be able to
410 // run with holding the lock.
411 std::scoped_lock<std::mutex> _l(mLock);
412
413 int32_t loopCount = 0;
414 while (mThreadEnabled.load()) {
415 loopCount++;
416 int64_t timeoutNanos = -1;
417 if (isRunning() || (isIdle_l() && !isStandby_l())) {
418 timeoutNanos = (isRunning() ? nextTime : standbyTime) - AudioClock::getNanoseconds();
419 timeoutNanos = std::max<int64_t>(0, timeoutNanos);
420 }
421
422 auto command = mCommandQueue.waitForCommand(timeoutNanos);
423 if (!mThreadEnabled) {
424 // Break the loop if the thread is disabled.
425 break;
426 }
427
428 if (isRunning() && AudioClock::getNanoseconds() >= nextTime) {
429 // It is time to update timestamp.
430 if (sendCurrentTimestamp_l() != AAUDIO_OK) {
431 ALOGE("Failed to send current timestamp, stop updating timestamp");
432 disconnect_l();
433 } else {
434 nextTime = timestampScheduler.nextAbsoluteTime();
435 }
436 }
437 if (isIdle_l() && AudioClock::getNanoseconds() >= standbyTime) {
438 aaudio_result_t result = standby_l();
439 if (result != AAUDIO_OK) {
440 // If standby failed because of the function is not implemented, there is no
441 // need to retry. Otherwise, retry standby later.
442 ALOGW("Failed to enter standby, error=%d", result);
443 standbyTime = result == AAUDIO_ERROR_UNIMPLEMENTED
444 ? std::numeric_limits<int64_t>::max()
445 : AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
446 }
447 }
448
449 if (command != nullptr) {
450 std::scoped_lock<std::mutex> _commandLock(command->lock);
451 switch (command->operationCode) {
452 case START:
453 command->result = start_l();
454 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
455 timestampScheduler.start(AudioClock::getNanoseconds());
456 nextTime = timestampScheduler.nextAbsoluteTime();
457 break;
458 case PAUSE:
459 command->result = pause_l();
460 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
461 break;
462 case STOP:
463 command->result = stop_l();
464 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
465 break;
466 case FLUSH:
467 command->result = flush_l();
468 break;
469 case CLOSE:
470 command->result = close_l();
471 break;
472 case DISCONNECT:
473 disconnect_l();
474 break;
475 case REGISTER_AUDIO_THREAD: {
476 RegisterAudioThreadParam *param =
477 (RegisterAudioThreadParam *) command->parameter.get();
478 command->result =
479 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
480 : registerAudioThread_l(param->mOwnerPid,
481 param->mClientThreadId,
482 param->mPriority);
483 }
484 break;
485 case UNREGISTER_AUDIO_THREAD: {
486 UnregisterAudioThreadParam *param =
487 (UnregisterAudioThreadParam *) command->parameter.get();
488 command->result =
489 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
490 : unregisterAudioThread_l(param->mClientThreadId);
491 }
492 break;
493 case GET_DESCRIPTION: {
494 GetDescriptionParam *param = (GetDescriptionParam *) command->parameter.get();
495 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
496 : getDescription_l(param->mParcelable);
497 }
498 break;
499 case EXIT_STANDBY: {
500 ExitStandbyParam *param = (ExitStandbyParam *) command->parameter.get();
501 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
502 : exitStandby_l(param->mParcelable);
503 standbyTime = AudioClock::getNanoseconds() + IDLE_TIMEOUT_NANOS;
504 } break;
505 default:
506 ALOGE("Invalid command op code: %d", command->operationCode);
507 break;
508 }
509 if (command->isWaitingForReply) {
510 command->isWaitingForReply = false;
511 command->conditionVariable.notify_one();
512 }
513 }
514 }
515 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< COMMANDS",
516 __func__, getTypeText(), loopCount);
517 }
518
disconnect()519 void AAudioServiceStreamBase::disconnect() {
520 sendCommand(DISCONNECT);
521 }
522
disconnect_l()523 void AAudioServiceStreamBase::disconnect_l() {
524 if (!isDisconnected_l() && getState() != AAUDIO_STREAM_STATE_CLOSED) {
525
526 mediametrics::LogItem(mMetricsId)
527 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
528 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
529 .record();
530
531 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
532 setDisconnected_l(true);
533 }
534 }
535
registerAudioThread(pid_t clientThreadId,int priority)536 aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId, int priority) {
537 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
538 return sendCommand(REGISTER_AUDIO_THREAD,
539 std::make_shared<RegisterAudioThreadParam>(ownerPid, clientThreadId, priority),
540 true /*waitForReply*/,
541 TIMEOUT_NANOS);
542 }
543
registerAudioThread_l(pid_t ownerPid,pid_t clientThreadId,int priority)544 aaudio_result_t AAudioServiceStreamBase::registerAudioThread_l(
545 pid_t ownerPid, pid_t clientThreadId, int priority) {
546 aaudio_result_t result = AAUDIO_OK;
547 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
548 ALOGE("AAudioService::registerAudioThread(), thread already registered");
549 result = AAUDIO_ERROR_INVALID_STATE;
550 } else {
551 setRegisteredThread(clientThreadId);
552 int err = android::requestPriority(ownerPid, clientThreadId,
553 priority, true /* isForApp */);
554 if (err != 0) {
555 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
556 clientThreadId, errno, priority);
557 result = AAUDIO_ERROR_INTERNAL;
558 }
559 }
560 return result;
561 }
562
unregisterAudioThread(pid_t clientThreadId)563 aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
564 return sendCommand(UNREGISTER_AUDIO_THREAD,
565 std::make_shared<UnregisterAudioThreadParam>(clientThreadId),
566 true /*waitForReply*/,
567 TIMEOUT_NANOS);
568 }
569
unregisterAudioThread_l(pid_t clientThreadId)570 aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread_l(pid_t clientThreadId) {
571 aaudio_result_t result = AAUDIO_OK;
572 if (getRegisteredThread() != clientThreadId) {
573 ALOGE("%s(), wrong thread", __func__);
574 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
575 } else {
576 setRegisteredThread(0);
577 }
578 return result;
579 }
580
setState(aaudio_stream_state_t state)581 void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
582 // CLOSED is a final state.
583 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
584 mState = state;
585 } else {
586 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
587 }
588 }
589
sendServiceEvent(aaudio_service_event_t event,double dataDouble)590 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
591 double dataDouble) {
592 AAudioServiceMessage command;
593 command.what = AAudioServiceMessage::code::EVENT;
594 command.event.event = event;
595 command.event.dataDouble = dataDouble;
596 return writeUpMessageQueue(&command);
597 }
598
sendServiceEvent(aaudio_service_event_t event,int64_t dataLong)599 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
600 int64_t dataLong) {
601 AAudioServiceMessage command;
602 command.what = AAudioServiceMessage::code::EVENT;
603 command.event.event = event;
604 command.event.dataLong = dataLong;
605 return writeUpMessageQueue(&command);
606 }
607
isUpMessageQueueBusy()608 bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
609 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
610 if (mUpMessageQueue == nullptr) {
611 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
612 return true;
613 }
614 // Is it half full or more
615 return mUpMessageQueue->getFractionalFullness() >= 0.5;
616 }
617
writeUpMessageQueue(AAudioServiceMessage * command)618 aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
619 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
620 if (mUpMessageQueue == nullptr) {
621 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
622 return AAUDIO_ERROR_NULL;
623 }
624 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
625 if (count != 1) {
626 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
627 __func__, command->what, getTypeText());
628 setSuspended(true);
629 return AAUDIO_ERROR_WOULD_BLOCK;
630 } else {
631 return AAUDIO_OK;
632 }
633 }
634
sendXRunCount(int32_t xRunCount)635 aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
636 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
637 }
638
sendCurrentTimestamp_l()639 aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp_l() {
640 AAudioServiceMessage command;
641 // It is not worth filling up the queue with timestamps.
642 // That can cause the stream to get suspended.
643 // So just drop the timestamp if the queue is getting full.
644 if (isUpMessageQueueBusy()) {
645 return AAUDIO_OK;
646 }
647
648 // Send a timestamp for the clock model.
649 aaudio_result_t result = getFreeRunningPosition_l(&command.timestamp.position,
650 &command.timestamp.timestamp);
651 if (result == AAUDIO_OK) {
652 ALOGV("%s() SERVICE %8lld at %lld", __func__,
653 (long long) command.timestamp.position,
654 (long long) command.timestamp.timestamp);
655 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
656 result = writeUpMessageQueue(&command);
657
658 if (result == AAUDIO_OK) {
659 // Send a hardware timestamp for presentation time.
660 result = getHardwareTimestamp_l(&command.timestamp.position,
661 &command.timestamp.timestamp);
662 if (result == AAUDIO_OK) {
663 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
664 (long long) command.timestamp.position,
665 (long long) command.timestamp.timestamp);
666 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
667 result = writeUpMessageQueue(&command);
668 }
669 }
670 }
671
672 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
673 result = AAUDIO_OK; // just not available yet, try again later
674 }
675 return result;
676 }
677
678 /**
679 * Get an immutable description of the in-memory queues
680 * used to communicate with the underlying HAL or Service.
681 */
getDescription(AudioEndpointParcelable & parcelable)682 aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
683 return sendCommand(
684 GET_DESCRIPTION,
685 std::make_shared<GetDescriptionParam>(&parcelable),
686 true /*waitForReply*/,
687 TIMEOUT_NANOS);
688 }
689
getDescription_l(AudioEndpointParcelable * parcelable)690 aaudio_result_t AAudioServiceStreamBase::getDescription_l(AudioEndpointParcelable* parcelable) {
691 {
692 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
693 if (mUpMessageQueue == nullptr) {
694 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
695 return AAUDIO_ERROR_NULL;
696 }
697 // Gather information on the message queue.
698 mUpMessageQueue->fillParcelable(parcelable,
699 parcelable->mUpMessageQueueParcelable);
700 }
701 return getAudioDataDescription_l(parcelable);
702 }
703
exitStandby(AudioEndpointParcelable * parcelable)704 aaudio_result_t AAudioServiceStreamBase::exitStandby(AudioEndpointParcelable *parcelable) {
705 auto command = std::make_shared<AAudioCommand>(
706 EXIT_STANDBY,
707 std::make_shared<ExitStandbyParam>(parcelable),
708 true /*waitForReply*/,
709 TIMEOUT_NANOS);
710 return mCommandQueue.sendCommand(command);
711 }
712
onVolumeChanged(float volume)713 void AAudioServiceStreamBase::onVolumeChanged(float volume) {
714 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
715 }
716
sendCommand(aaudio_command_opcode opCode,std::shared_ptr<AAudioCommandParam> param,bool waitForReply,int64_t timeoutNanos)717 aaudio_result_t AAudioServiceStreamBase::sendCommand(aaudio_command_opcode opCode,
718 std::shared_ptr<AAudioCommandParam> param,
719 bool waitForReply,
720 int64_t timeoutNanos) {
721 return mCommandQueue.sendCommand(std::make_shared<AAudioCommand>(
722 opCode, param, waitForReply, timeoutNanos));
723 }
724
closeAndClear()725 aaudio_result_t AAudioServiceStreamBase::closeAndClear() {
726 aaudio_result_t result = AAUDIO_OK;
727 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
728 if (endpoint == nullptr) {
729 result = AAUDIO_ERROR_INVALID_STATE;
730 } else {
731 endpoint->unregisterStream(this);
732 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
733 endpointManager.closeEndpoint(endpoint);
734
735 // AAudioService::closeStream() prevents two threads from closing at the same time.
736 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
737 }
738
739 setState(AAUDIO_STREAM_STATE_CLOSED);
740
741 mediametrics::LogItem(mMetricsId)
742 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
743 .record();
744 return result;
745 }
746