blob: a25a79111ca8279b5026e5276993bb75932f049f [file] [log] [blame]
Phil Burk2355edb2016-12-26 13:54:02 -08001/*
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
Eric Laurentcb4dae22017-07-01 19:39:32 -070017#define LOG_TAG "AAudioServiceStreamBase"
Phil Burk2355edb2016-12-26 13:54:02 -080018//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
Phil Burka5222e22017-07-28 13:31:14 -070021#include <iomanip>
22#include <iostream>
Phil Burkc0c70e32017-02-09 13:18:38 -080023#include <mutex>
Phil Burk2355edb2016-12-26 13:54:02 -080024
Phil Burka9876702020-04-20 18:16:15 -070025#include <media/MediaMetricsItem.h>
26#include <media/TypeConverter.h>
Phil Burk7ebbc112020-05-13 15:55:17 -070027#include <mediautils/SchedulingPolicyService.h>
Phil Burka9876702020-04-20 18:16:15 -070028
Phil Burkc0c70e32017-02-09 13:18:38 -080029#include "binding/AAudioServiceMessage.h"
Phil Burka9876702020-04-20 18:16:15 -070030#include "core/AudioGlobal.h"
Phil Burkc0c70e32017-02-09 13:18:38 -080031#include "utility/AudioClock.h"
32
Phil Burk39f02dd2017-08-04 09:13:31 -070033#include "AAudioEndpointManager.h"
34#include "AAudioService.h"
35#include "AAudioServiceEndpoint.h"
Phil Burkc0c70e32017-02-09 13:18:38 -080036#include "AAudioServiceStreamBase.h"
Phil Burkc0c70e32017-02-09 13:18:38 -080037
38using namespace android; // TODO just import names needed
39using namespace aaudio; // TODO just import names needed
Phil Burk2355edb2016-12-26 13:54:02 -080040
Svet Ganov33761132021-05-13 22:51:08 +000041using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070042
jiabin2a594622021-10-14 00:32:25 +000043static const int64_t TIMEOUT_NANOS = 3LL * 1000 * 1000 * 1000;
44
Phil Burk2355edb2016-12-26 13:54:02 -080045/**
Phil Burkc0c70e32017-02-09 13:18:38 -080046 * Base class for streams in the service.
47 * @return
Phil Burk2355edb2016-12-26 13:54:02 -080048 */
49
Phil Burk39f02dd2017-08-04 09:13:31 -070050AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
jiabin2a594622021-10-14 00:32:25 +000051 : mCommandThread("AACommand")
Phil Burka53ffa62018-10-10 16:21:37 -070052 , mAtomicStreamTimestamp()
Phil Burk39f02dd2017-08-04 09:13:31 -070053 , mAudioService(audioService) {
Svet Ganov33761132021-05-13 22:51:08 +000054 mMmapClient.attributionSource = AttributionSourceState();
jiabin2a594622021-10-14 00:32:25 +000055 mThreadEnabled = true;
Phil Burk2355edb2016-12-26 13:54:02 -080056}
57
Phil Burk5ed503c2017-02-01 09:38:15 -080058AAudioServiceStreamBase::~AAudioServiceStreamBase() {
Phil Burk8f4fe502020-07-15 23:54:50 +000059 ALOGD("%s() called", __func__);
60
Phil Burka9876702020-04-20 18:16:15 -070061 // May not be set if open failed.
62 if (mMetricsId.size() > 0) {
63 mediametrics::LogItem(mMetricsId)
64 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
65 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
66 .record();
67 }
68
Phil Burk5a26e662017-07-07 12:44:48 -070069 // If the stream is deleted when OPEN or in use then audio resources will leak.
70 // This would indicate an internal error. So we want to find this ASAP.
Phil Burkbcc36742017-08-31 17:24:51 -070071 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
Phil Burkdb466142021-04-16 16:50:00 +000072 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED),
Phil Burk8b4e05e2019-12-17 12:12:09 -080073 "service stream %p still open, state = %d",
74 this, getState());
jiabin2a594622021-10-14 00:32:25 +000075
76 // Stop the command thread before destroying.
77 if (mThreadEnabled) {
78 mThreadEnabled = false;
79 mCommandQueue.stopWaiting();
80 mCommandThread.stop();
81 }
Phil Burk2355edb2016-12-26 13:54:02 -080082}
83
Phil Burka5222e22017-07-28 13:31:14 -070084std::string AAudioServiceStreamBase::dumpHeader() {
jiabina9094092021-06-28 20:36:45 +000085 return std::string(
86 " T Handle UId Port Run State Format Burst Chan Mask Capacity");
Phil Burka5222e22017-07-28 13:31:14 -070087}
88
Phil Burk4501b352017-06-29 18:12:36 -070089std::string AAudioServiceStreamBase::dump() const {
90 std::stringstream result;
91
Phil Burka5222e22017-07-28 13:31:14 -070092 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
93 << std::dec << std::setfill(' ') ;
Svet Ganov33761132021-05-13 22:51:08 +000094 result << std::setw(6) << mMmapClient.attributionSource.uid;
Phil Burkbbd52862018-04-13 11:37:42 -070095 result << std::setw(7) << mClientHandle;
Phil Burka5222e22017-07-28 13:31:14 -070096 result << std::setw(4) << (isRunning() ? "yes" : " no");
Phil Burkbcc36742017-08-31 17:24:51 -070097 result << std::setw(6) << getState();
Phil Burk39f02dd2017-08-04 09:13:31 -070098 result << std::setw(7) << getFormat();
Phil Burka5222e22017-07-28 13:31:14 -070099 result << std::setw(6) << mFramesPerBurst;
Phil Burk39f02dd2017-08-04 09:13:31 -0700100 result << std::setw(5) << getSamplesPerFrame();
jiabina9094092021-06-28 20:36:45 +0000101 result << std::setw(8) << std::hex << getChannelMask() << std::dec;
Phil Burk39f02dd2017-08-04 09:13:31 -0700102 result << std::setw(9) << getBufferCapacity();
Phil Burk4501b352017-06-29 18:12:36 -0700103
104 return result.str();
105}
106
Phil Burka9876702020-04-20 18:16:15 -0700107void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
108 // This is the first log sent from the AAudio Service for a stream.
109 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
110 + std::to_string(streamHandle);
111
112 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
113
114 // Once this item is logged by the server, the client with the same PID, UID
115 // can also log properties.
116 mediametrics::LogItem(mMetricsId)
117 .setPid(getOwnerProcessId())
118 .setUid(getOwnerUserId())
Andy Hungd203eb62020-04-27 09:12:46 -0700119 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
Phil Burka9876702020-04-20 18:16:15 -0700120 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
121 // the following are immutable
122 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
123 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
124 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
125 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
126 .set(AMEDIAMETRICS_PROP_DIRECTION,
127 AudioGlobal_convertDirectionToText(getDirection()))
128 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
129 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
130 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
131 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
132 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
133 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
134 .record();
135}
136
Phil Burk15f97c92018-09-04 14:06:27 -0700137aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700138 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
139 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700140
Svet Ganov33761132021-05-13 22:51:08 +0000141 mMmapClient.attributionSource = request.getAttributionSource();
142 // TODO b/182392769: use attribution source util
143 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700144 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000145 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700146 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Eric Laurentcb4dae22017-07-01 19:39:32 -0700147
Phil Burk39f02dd2017-08-04 09:13:31 -0700148 // Limit scope of lock to avoid recursive lock in close().
149 {
150 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
151 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700152 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700153 return AAUDIO_ERROR_INVALID_STATE;
154 }
155
Phil Burk8f4fe502020-07-15 23:54:50 +0000156 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700157 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
158 QUEUE_UP_CAPACITY_COMMANDS);
159 if (result != AAUDIO_OK) {
160 goto error;
161 }
162
Phil Burk6e2770e2018-05-01 13:03:52 -0700163 // This is not protected by a lock because the stream cannot be
164 // referenced until the service returns a handle to the client.
165 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700166 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700167 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700168 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700169 result = AAUDIO_ERROR_UNAVAILABLE;
170 goto error;
171 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700172 // Save a weak pointer that we will use to access the endpoint.
173 mServiceEndpointWeak = mServiceEndpoint;
174
Phil Burk39f02dd2017-08-04 09:13:31 -0700175 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
176 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800177 }
jiabin2a594622021-10-14 00:32:25 +0000178
179 // Make sure this object does not get deleted before the run() method
180 // can protect it by making a strong pointer.
181 mThreadEnabled = true;
182 incStrong(nullptr); // See run() method.
183 result = mCommandThread.start(this);
184 if (result != AAUDIO_OK) {
185 decStrong(nullptr); // run() can't do it so we have to do it here.
186 goto error;
187 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700188 return result;
189
190error:
191 close();
192 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800193}
Phil Burkdec33ab2017-01-17 14:48:16 -0800194
Phil Burkc0c70e32017-02-09 13:18:38 -0800195aaudio_result_t AAudioServiceStreamBase::close() {
jiabin2a594622021-10-14 00:32:25 +0000196 auto command = std::make_shared<AAudioCommand>(
197 CLOSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
198 aaudio_result_t result = mCommandQueue.sendCommand(command);
199
200 // Stop the command thread as the stream is closed.
201 mThreadEnabled = false;
202 mCommandQueue.stopWaiting();
203 mCommandThread.stop();
204
205 return result;
Phil Burk7ebbc112020-05-13 15:55:17 -0700206}
207
208aaudio_result_t AAudioServiceStreamBase::close_l() {
Phil Burkbcc36742017-08-31 17:24:51 -0700209 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700210 return AAUDIO_OK;
211 }
212
jiabin2a594622021-10-14 00:32:25 +0000213 // This will stop the stream, just in case it was not already stopped.
Phil Burk7ebbc112020-05-13 15:55:17 -0700214 stop_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700215
Phil Burk8b4e05e2019-12-17 12:12:09 -0800216 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700217 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
218 if (endpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700219 result = AAUDIO_ERROR_INVALID_STATE;
220 } else {
Phil Burk6e2770e2018-05-01 13:03:52 -0700221 endpoint->unregisterStream(this);
222 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
223 endpointManager.closeEndpoint(endpoint);
224
225 // AAudioService::closeStream() prevents two threads from closing at the same time.
Phil Burk7ebbc112020-05-13 15:55:17 -0700226 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
Phil Burk39f02dd2017-08-04 09:13:31 -0700227 }
228
Phil Burkbcc36742017-08-31 17:24:51 -0700229 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burka9876702020-04-20 18:16:15 -0700230
231 mediametrics::LogItem(mMetricsId)
232 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
233 .record();
Phil Burk39f02dd2017-08-04 09:13:31 -0700234 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800235}
236
Phil Burkbcc36742017-08-31 17:24:51 -0700237aaudio_result_t AAudioServiceStreamBase::startDevice() {
238 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700239 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
240 if (endpoint == nullptr) {
241 ALOGE("%s() has no endpoint", __func__);
242 return AAUDIO_ERROR_INVALID_STATE;
243 }
244 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700245}
246
Phil Burk39f02dd2017-08-04 09:13:31 -0700247/**
248 * Start the flow of audio data.
249 *
250 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
251 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800252aaudio_result_t AAudioServiceStreamBase::start() {
jiabin2a594622021-10-14 00:32:25 +0000253 auto command = std::make_shared<AAudioCommand>(
254 START, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
255 return mCommandQueue.sendCommand(command);
256}
Phil Burk7ebbc112020-05-13 15:55:17 -0700257
jiabin2a594622021-10-14 00:32:25 +0000258aaudio_result_t AAudioServiceStreamBase::start_l() {
Phil Burka9876702020-04-20 18:16:15 -0700259 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700260 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700261
Phil Burk7ebbc112020-05-13 15:55:17 -0700262 if (auto state = getState();
Phil Burkdb466142021-04-16 16:50:00 +0000263 state == AAUDIO_STREAM_STATE_CLOSED || isDisconnected_l()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700264 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
265 __func__, getHandle());
266 return AAUDIO_ERROR_INVALID_STATE;
267 }
268
Phil Burka9876702020-04-20 18:16:15 -0700269 mediametrics::Defer defer([&] {
270 mediametrics::LogItem(mMetricsId)
271 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700272 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700273 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
274 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
275 .record(); });
276
Eric Laurentcb4dae22017-07-01 19:39:32 -0700277 if (isRunning()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700278 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700279 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700280
Phil Burk23296382017-11-20 15:45:11 -0800281 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800282 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800283
Phil Burkbcc36742017-08-31 17:24:51 -0700284 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700285 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700286
Phil Burk39f02dd2017-08-04 09:13:31 -0700287 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700288 result = startDevice();
289 if (result != AAUDIO_OK) goto error;
290
291 // This should happen at the end of the start.
292 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
293 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burkbcc36742017-08-31 17:24:51 -0700294
295 return result;
296
297error:
Phil Burk7ebbc112020-05-13 15:55:17 -0700298 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700299 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800300}
301
302aaudio_result_t AAudioServiceStreamBase::pause() {
jiabin2a594622021-10-14 00:32:25 +0000303 auto command = std::make_shared<AAudioCommand>(
304 PAUSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
305 return mCommandQueue.sendCommand(command);
Phil Burk7ebbc112020-05-13 15:55:17 -0700306}
307
308aaudio_result_t AAudioServiceStreamBase::pause_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700309 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700310 if (!isRunning()) {
311 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800312 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700313 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk73af62a2017-10-26 12:11:47 -0700314
Phil Burka9876702020-04-20 18:16:15 -0700315 mediametrics::Defer defer([&] {
316 mediametrics::LogItem(mMetricsId)
317 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700318 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700319 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
320 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
321 .record(); });
322
Phil Burk6e2770e2018-05-01 13:03:52 -0700323 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
324 if (endpoint == nullptr) {
325 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700326 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
327 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700328 }
329 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700330 if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700331 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700332 disconnect_l(); // TODO should we return or pause Base first?
Phil Burk39f02dd2017-08-04 09:13:31 -0700333 }
334
Eric Laurentcb4dae22017-07-01 19:39:32 -0700335 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
Phil Burkbcc36742017-08-31 17:24:51 -0700336 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burkc0c70e32017-02-09 13:18:38 -0800337 return result;
338}
339
Phil Burk71f35bb2017-04-13 16:05:07 -0700340aaudio_result_t AAudioServiceStreamBase::stop() {
jiabin2a594622021-10-14 00:32:25 +0000341 auto command = std::make_shared<AAudioCommand>(
342 STOP, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
343 return mCommandQueue.sendCommand(command);
Phil Burk7ebbc112020-05-13 15:55:17 -0700344}
345
346aaudio_result_t AAudioServiceStreamBase::stop_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700347 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700348 if (!isRunning()) {
349 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700350 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700351 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk39f02dd2017-08-04 09:13:31 -0700352
Phil Burka9876702020-04-20 18:16:15 -0700353 mediametrics::Defer defer([&] {
354 mediametrics::LogItem(mMetricsId)
355 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700356 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700357 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
358 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
359 .record(); });
360
Phil Burk83fb8442017-10-05 16:55:17 -0700361 setState(AAUDIO_STREAM_STATE_STOPPING);
362
Eric Laurentcb4dae22017-07-01 19:39:32 -0700363 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700364 disconnect_l();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700365 return result;
366 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700367
Phil Burk6e2770e2018-05-01 13:03:52 -0700368 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
369 if (endpoint == nullptr) {
370 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700371 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
372 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700373 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700374 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700375 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700376 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700377 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700378 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700379 // TODO what to do with result here?
380 }
381
Eric Laurentcb4dae22017-07-01 19:39:32 -0700382 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700383 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700384 return result;
385}
386
jiabin2a594622021-10-14 00:32:25 +0000387aaudio_result_t AAudioServiceStreamBase::flush() {
388 auto command = std::make_shared<AAudioCommand>(
389 FLUSH, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
390 return mCommandQueue.sendCommand(command);
Phil Burk98d6d922017-07-06 11:52:45 -0700391}
392
jiabin2a594622021-10-14 00:32:25 +0000393aaudio_result_t AAudioServiceStreamBase::flush_l() {
Phil Burk5cc83c32017-11-28 15:43:18 -0800394 aaudio_result_t result = AAudio_isFlushAllowed(getState());
395 if (result != AAUDIO_OK) {
396 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700397 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700398 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800399
Phil Burka9876702020-04-20 18:16:15 -0700400 mediametrics::Defer defer([&] {
401 mediametrics::LogItem(mMetricsId)
402 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700403 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700404 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
405 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
406 .record(); });
407
Phil Burk39f02dd2017-08-04 09:13:31 -0700408 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700409 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700410 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700411 return AAUDIO_OK;
412}
413
jiabin2a594622021-10-14 00:32:25 +0000414// implement Runnable, periodically send timestamps to client and process commands from queue.
Phil Burka53ffa62018-10-10 16:21:37 -0700415__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800416void AAudioServiceStreamBase::run() {
jiabin2a594622021-10-14 00:32:25 +0000417 ALOGD("%s() %s entering >>>>>>>>>>>>>> COMMANDS", __func__, getTypeText());
Phil Burk3d201942021-04-08 23:27:04 +0000418 // Hold onto the ref counted stream until the end.
419 android::sp<AAudioServiceStreamBase> holdStream(this);
Phil Burkc0c70e32017-02-09 13:18:38 -0800420 TimestampScheduler timestampScheduler;
jiabin2a594622021-10-14 00:32:25 +0000421 int64_t nextTime;
Phil Burk3d201942021-04-08 23:27:04 +0000422 // Balance the incStrong from when the thread was launched.
423 holdStream->decStrong(nullptr);
424
jiabin2a594622021-10-14 00:32:25 +0000425 // Taking mLock while starting the thread. All the operation must be able to
426 // run with holding the lock.
427 std::scoped_lock<std::mutex> _l(mLock);
428
Phil Burka53ffa62018-10-10 16:21:37 -0700429 int32_t loopCount = 0;
jiabin2a594622021-10-14 00:32:25 +0000430 while (mThreadEnabled.load()) {
Phil Burka53ffa62018-10-10 16:21:37 -0700431 loopCount++;
jiabin2a594622021-10-14 00:32:25 +0000432 int64_t timeoutNanos = -1;
433 if (isRunning()) {
434 timeoutNanos = nextTime - AudioClock::getNanoseconds();
435 timeoutNanos = std::max<int64_t>(0, timeoutNanos);
436 }
437
438 auto command = mCommandQueue.waitForCommand(timeoutNanos);
439 if (!mThreadEnabled) {
440 // Break the loop if the thread is disabled.
441 break;
442 }
443
444 if (isRunning() && AudioClock::getNanoseconds() >= nextTime) {
445 // It is time to update timestamp.
446 if (sendCurrentTimestamp_l() != AAUDIO_OK) {
447 ALOGE("Failed to send current timestamp, stop updating timestamp");
448 disconnect_l();
449 } else {
450 nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burkc0c70e32017-02-09 13:18:38 -0800451 }
jiabin2a594622021-10-14 00:32:25 +0000452 }
453
454 if (command != nullptr) {
455 std::scoped_lock<std::mutex> _commandLock(command->lock);
456 switch (command->operationCode) {
457 case START:
458 command->result = start_l();
459 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
460 timestampScheduler.start(AudioClock::getNanoseconds());
461 nextTime = timestampScheduler.nextAbsoluteTime();
462 break;
463 case PAUSE:
464 command->result = pause_l();
465 break;
466 case STOP:
467 command->result = stop_l();
468 break;
469 case FLUSH:
470 command->result = flush_l();
471 break;
472 case CLOSE:
473 command->result = close_l();
474 break;
475 case DISCONNECT:
476 disconnect_l();
477 break;
478 case REGISTER_AUDIO_THREAD: {
479 RegisterAudioThreadParam *param =
480 (RegisterAudioThreadParam *) command->parameter.get();
481 command->result =
482 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
483 : registerAudioThread_l(param->mOwnerPid,
484 param->mClientThreadId,
485 param->mPriority);
486 }
487 break;
488 case UNREGISTER_AUDIO_THREAD: {
489 UnregisterAudioThreadParam *param =
490 (UnregisterAudioThreadParam *) command->parameter.get();
491 command->result =
492 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
493 : unregisterAudioThread_l(param->mClientThreadId);
494 }
495 break;
496 case GET_DESCRIPTION: {
497 GetDescriptionParam *param = (GetDescriptionParam *) command->parameter.get();
498 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
499 : getDescription_l(param->mParcelable);
500 }
501 break;
502 default:
503 ALOGE("Invalid command op code: %d", command->operationCode);
504 break;
505 }
506 if (command->isWaitingForReply) {
507 command->isWaitingForReply = false;
508 command->conditionVariable.notify_one();
509 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800510 }
511 }
jiabin2a594622021-10-14 00:32:25 +0000512 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< COMMANDS",
Phil Burka53ffa62018-10-10 16:21:37 -0700513 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800514}
515
Phil Burk5ef003b2017-06-30 11:43:37 -0700516void AAudioServiceStreamBase::disconnect() {
jiabin2a594622021-10-14 00:32:25 +0000517 auto command = std::make_shared<AAudioCommand>(DISCONNECT);
518 mCommandQueue.sendCommand(command);
Phil Burk7ebbc112020-05-13 15:55:17 -0700519}
520
521void AAudioServiceStreamBase::disconnect_l() {
Phil Burkdb466142021-04-16 16:50:00 +0000522 if (!isDisconnected_l() && getState() != AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700523
Phil Burka9876702020-04-20 18:16:15 -0700524 mediametrics::LogItem(mMetricsId)
525 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
526 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
527 .record();
Phil Burk7ebbc112020-05-13 15:55:17 -0700528
Phil Burk5ef003b2017-06-30 11:43:37 -0700529 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkdb466142021-04-16 16:50:00 +0000530 setDisconnected_l(true);
Phil Burk5ef003b2017-06-30 11:43:37 -0700531 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800532}
533
jiabin2a594622021-10-14 00:32:25 +0000534aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId, int priority) {
535 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
536 auto command = std::make_shared<AAudioCommand>(
537 REGISTER_AUDIO_THREAD,
538 std::make_shared<RegisterAudioThreadParam>(ownerPid, clientThreadId, priority),
539 true /*waitForReply*/,
540 TIMEOUT_NANOS);
541 return mCommandQueue.sendCommand(command);
542}
543
544aaudio_result_t AAudioServiceStreamBase::registerAudioThread_l(
545 pid_t ownerPid, pid_t clientThreadId, int priority) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700546 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 {
Phil Burk7ebbc112020-05-13 15:55:17 -0700551 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
563aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
jiabin2a594622021-10-14 00:32:25 +0000564 auto command = std::make_shared<AAudioCommand>(
565 UNREGISTER_AUDIO_THREAD,
566 std::make_shared<UnregisterAudioThreadParam>(clientThreadId),
567 true /*waitForReply*/,
568 TIMEOUT_NANOS);
569 return mCommandQueue.sendCommand(command);
570}
571
572aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread_l(pid_t clientThreadId) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700573 aaudio_result_t result = AAUDIO_OK;
574 if (getRegisteredThread() != clientThreadId) {
575 ALOGE("%s(), wrong thread", __func__);
576 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
577 } else {
578 setRegisteredThread(0);
579 }
580 return result;
581}
582
583void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
584 // CLOSED is a final state.
585 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
586 mState = state;
587 } else {
588 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
589 }
590}
591
Phil Burkc0c70e32017-02-09 13:18:38 -0800592aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800593 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800594 AAudioServiceMessage command;
595 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800596 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800597 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800598 return writeUpMessageQueue(&command);
599}
600
601aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
602 int64_t dataLong) {
603 AAudioServiceMessage command;
604 command.what = AAudioServiceMessage::code::EVENT;
605 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800606 command.event.dataLong = dataLong;
607 return writeUpMessageQueue(&command);
608}
609
Phil Burkf878a8d2019-03-29 17:23:00 -0700610bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
611 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
612 if (mUpMessageQueue == nullptr) {
613 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
614 return true;
615 }
Phil Burkf878a8d2019-03-29 17:23:00 -0700616 // Is it half full or more
Phil Burk8f4fe502020-07-15 23:54:50 +0000617 return mUpMessageQueue->getFractionalFullness() >= 0.5;
Phil Burkf878a8d2019-03-29 17:23:00 -0700618}
619
Phil Burkc0c70e32017-02-09 13:18:38 -0800620aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700621 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700622 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700623 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700624 return AAUDIO_ERROR_NULL;
625 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800626 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
627 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800628 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
629 __func__, command->what, getTypeText());
630 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800631 return AAUDIO_ERROR_WOULD_BLOCK;
632 } else {
633 return AAUDIO_OK;
634 }
635}
636
Phil Burk23296382017-11-20 15:45:11 -0800637aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
638 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
639}
640
jiabin2a594622021-10-14 00:32:25 +0000641aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp_l() {
Phil Burkc0c70e32017-02-09 13:18:38 -0800642 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700643 // It is not worth filling up the queue with timestamps.
644 // That can cause the stream to get suspended.
645 // So just drop the timestamp if the queue is getting full.
646 if (isUpMessageQueueBusy()) {
647 return AAUDIO_OK;
648 }
649
Phil Burk97350f92017-07-21 15:59:44 -0700650 // Send a timestamp for the clock model.
jiabin2a594622021-10-14 00:32:25 +0000651 aaudio_result_t result = getFreeRunningPosition_l(&command.timestamp.position,
652 &command.timestamp.timestamp);
Phil Burkc0c70e32017-02-09 13:18:38 -0800653 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700654 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700655 (long long) command.timestamp.position,
656 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700657 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800658 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700659
660 if (result == AAUDIO_OK) {
661 // Send a hardware timestamp for presentation time.
jiabin2a594622021-10-14 00:32:25 +0000662 result = getHardwareTimestamp_l(&command.timestamp.position,
663 &command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700664 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700665 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700666 (long long) command.timestamp.position,
667 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700668 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
669 result = writeUpMessageQueue(&command);
670 }
671 }
672 }
673
Phil Burkbcc36742017-08-31 17:24:51 -0700674 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700675 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800676 }
677 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800678}
679
Phil Burkc0c70e32017-02-09 13:18:38 -0800680/**
681 * Get an immutable description of the in-memory queues
682 * used to communicate with the underlying HAL or Service.
683 */
684aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
jiabin2a594622021-10-14 00:32:25 +0000685 auto command = std::make_shared<AAudioCommand>(
686 GET_DESCRIPTION,
687 std::make_shared<GetDescriptionParam>(&parcelable),
688 true /*waitForReply*/,
689 TIMEOUT_NANOS);
690 return mCommandQueue.sendCommand(command);
691}
692
693aaudio_result_t AAudioServiceStreamBase::getDescription_l(AudioEndpointParcelable* parcelable) {
Phil Burk523b3042017-09-13 13:03:08 -0700694 {
695 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
696 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700697 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700698 return AAUDIO_ERROR_NULL;
699 }
700 // Gather information on the message queue.
701 mUpMessageQueue->fillParcelable(parcelable,
jiabin2a594622021-10-14 00:32:25 +0000702 parcelable->mUpMessageQueueParcelable);
Phil Burk523b3042017-09-13 13:03:08 -0700703 }
jiabin2a594622021-10-14 00:32:25 +0000704 return getAudioDataDescription_l(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700705}
Phil Burk39f02dd2017-08-04 09:13:31 -0700706
707void AAudioServiceStreamBase::onVolumeChanged(float volume) {
708 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
709}