blob: 4ffc127afa702c421b9ee58506b0937d0eb75367 [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"
37#include "TimestampScheduler.h"
38
39using namespace android; // TODO just import names needed
40using namespace aaudio; // TODO just import names needed
Phil Burk2355edb2016-12-26 13:54:02 -080041
Svet Ganov33761132021-05-13 22:51:08 +000042using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070043
Phil Burk2355edb2016-12-26 13:54:02 -080044/**
Phil Burkc0c70e32017-02-09 13:18:38 -080045 * Base class for streams in the service.
46 * @return
Phil Burk2355edb2016-12-26 13:54:02 -080047 */
48
Phil Burk39f02dd2017-08-04 09:13:31 -070049AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
Phil Burk8f4fe502020-07-15 23:54:50 +000050 : mTimestampThread("AATime")
Phil Burka53ffa62018-10-10 16:21:37 -070051 , mAtomicStreamTimestamp()
Phil Burk39f02dd2017-08-04 09:13:31 -070052 , mAudioService(audioService) {
Svet Ganov33761132021-05-13 22:51:08 +000053 mMmapClient.attributionSource = AttributionSourceState();
Phil Burk2355edb2016-12-26 13:54:02 -080054}
55
Phil Burk5ed503c2017-02-01 09:38:15 -080056AAudioServiceStreamBase::~AAudioServiceStreamBase() {
Phil Burk8f4fe502020-07-15 23:54:50 +000057 ALOGD("%s() called", __func__);
58
Phil Burka9876702020-04-20 18:16:15 -070059 // May not be set if open failed.
60 if (mMetricsId.size() > 0) {
61 mediametrics::LogItem(mMetricsId)
62 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
63 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
64 .record();
65 }
66
Phil Burk5a26e662017-07-07 12:44:48 -070067 // If the stream is deleted when OPEN or in use then audio resources will leak.
68 // This would indicate an internal error. So we want to find this ASAP.
Phil Burkbcc36742017-08-31 17:24:51 -070069 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
Phil Burkdb466142021-04-16 16:50:00 +000070 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED),
Phil Burk8b4e05e2019-12-17 12:12:09 -080071 "service stream %p still open, state = %d",
72 this, getState());
Phil Burk2355edb2016-12-26 13:54:02 -080073}
74
Phil Burka5222e22017-07-28 13:31:14 -070075std::string AAudioServiceStreamBase::dumpHeader() {
jiabina9094092021-06-28 20:36:45 +000076 return std::string(
77 " T Handle UId Port Run State Format Burst Chan Mask Capacity");
Phil Burka5222e22017-07-28 13:31:14 -070078}
79
Phil Burk4501b352017-06-29 18:12:36 -070080std::string AAudioServiceStreamBase::dump() const {
81 std::stringstream result;
82
Phil Burka5222e22017-07-28 13:31:14 -070083 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
84 << std::dec << std::setfill(' ') ;
Svet Ganov33761132021-05-13 22:51:08 +000085 result << std::setw(6) << mMmapClient.attributionSource.uid;
Phil Burkbbd52862018-04-13 11:37:42 -070086 result << std::setw(7) << mClientHandle;
Phil Burka5222e22017-07-28 13:31:14 -070087 result << std::setw(4) << (isRunning() ? "yes" : " no");
Phil Burkbcc36742017-08-31 17:24:51 -070088 result << std::setw(6) << getState();
Phil Burk39f02dd2017-08-04 09:13:31 -070089 result << std::setw(7) << getFormat();
Phil Burka5222e22017-07-28 13:31:14 -070090 result << std::setw(6) << mFramesPerBurst;
Phil Burk39f02dd2017-08-04 09:13:31 -070091 result << std::setw(5) << getSamplesPerFrame();
jiabina9094092021-06-28 20:36:45 +000092 result << std::setw(8) << std::hex << getChannelMask() << std::dec;
Phil Burk39f02dd2017-08-04 09:13:31 -070093 result << std::setw(9) << getBufferCapacity();
Phil Burk4501b352017-06-29 18:12:36 -070094
95 return result.str();
96}
97
Phil Burka9876702020-04-20 18:16:15 -070098void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
99 // This is the first log sent from the AAudio Service for a stream.
100 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
101 + std::to_string(streamHandle);
102
103 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
104
105 // Once this item is logged by the server, the client with the same PID, UID
106 // can also log properties.
107 mediametrics::LogItem(mMetricsId)
108 .setPid(getOwnerProcessId())
109 .setUid(getOwnerUserId())
Andy Hungd203eb62020-04-27 09:12:46 -0700110 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
Phil Burka9876702020-04-20 18:16:15 -0700111 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
112 // the following are immutable
113 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
114 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
115 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
116 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
117 .set(AMEDIAMETRICS_PROP_DIRECTION,
118 AudioGlobal_convertDirectionToText(getDirection()))
119 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
120 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
121 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
122 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
123 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
124 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
125 .record();
126}
127
Phil Burk15f97c92018-09-04 14:06:27 -0700128aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700129 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
130 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700131
Svet Ganov33761132021-05-13 22:51:08 +0000132 mMmapClient.attributionSource = request.getAttributionSource();
133 // TODO b/182392769: use attribution source util
134 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700135 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000136 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700137 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Eric Laurentcb4dae22017-07-01 19:39:32 -0700138
Phil Burk39f02dd2017-08-04 09:13:31 -0700139 // Limit scope of lock to avoid recursive lock in close().
140 {
141 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
142 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700143 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700144 return AAUDIO_ERROR_INVALID_STATE;
145 }
146
Phil Burk8f4fe502020-07-15 23:54:50 +0000147 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700148 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
149 QUEUE_UP_CAPACITY_COMMANDS);
150 if (result != AAUDIO_OK) {
151 goto error;
152 }
153
Phil Burk6e2770e2018-05-01 13:03:52 -0700154 // This is not protected by a lock because the stream cannot be
155 // referenced until the service returns a handle to the client.
156 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700157 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700158 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700159 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700160 result = AAUDIO_ERROR_UNAVAILABLE;
161 goto error;
162 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700163 // Save a weak pointer that we will use to access the endpoint.
164 mServiceEndpointWeak = mServiceEndpoint;
165
Phil Burk39f02dd2017-08-04 09:13:31 -0700166 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
167 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800168 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700169 return result;
170
171error:
172 close();
173 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800174}
Phil Burkdec33ab2017-01-17 14:48:16 -0800175
Phil Burkc0c70e32017-02-09 13:18:38 -0800176aaudio_result_t AAudioServiceStreamBase::close() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700177 std::lock_guard<std::mutex> lock(mLock);
178 return close_l();
179}
180
181aaudio_result_t AAudioServiceStreamBase::close_l() {
Phil Burkbcc36742017-08-31 17:24:51 -0700182 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700183 return AAUDIO_OK;
184 }
185
Phil Burk8f4fe502020-07-15 23:54:50 +0000186 // This will call stopTimestampThread() and also stop the stream,
187 // just in case it was not already stopped.
Phil Burk7ebbc112020-05-13 15:55:17 -0700188 stop_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700189
Phil Burk8b4e05e2019-12-17 12:12:09 -0800190 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700191 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
192 if (endpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700193 result = AAUDIO_ERROR_INVALID_STATE;
194 } else {
Phil Burk6e2770e2018-05-01 13:03:52 -0700195 endpoint->unregisterStream(this);
196 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
197 endpointManager.closeEndpoint(endpoint);
198
199 // AAudioService::closeStream() prevents two threads from closing at the same time.
Phil Burk7ebbc112020-05-13 15:55:17 -0700200 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
Phil Burk39f02dd2017-08-04 09:13:31 -0700201 }
202
Phil Burkbcc36742017-08-31 17:24:51 -0700203 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burka9876702020-04-20 18:16:15 -0700204
205 mediametrics::LogItem(mMetricsId)
206 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
207 .record();
Phil Burk39f02dd2017-08-04 09:13:31 -0700208 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800209}
210
Phil Burkbcc36742017-08-31 17:24:51 -0700211aaudio_result_t AAudioServiceStreamBase::startDevice() {
212 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700213 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
214 if (endpoint == nullptr) {
215 ALOGE("%s() has no endpoint", __func__);
216 return AAUDIO_ERROR_INVALID_STATE;
217 }
218 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700219}
220
Phil Burk39f02dd2017-08-04 09:13:31 -0700221/**
222 * Start the flow of audio data.
223 *
224 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
225 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800226aaudio_result_t AAudioServiceStreamBase::start() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700227 std::lock_guard<std::mutex> lock(mLock);
228
Phil Burka9876702020-04-20 18:16:15 -0700229 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700230 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700231
Phil Burk7ebbc112020-05-13 15:55:17 -0700232 if (auto state = getState();
Phil Burkdb466142021-04-16 16:50:00 +0000233 state == AAUDIO_STREAM_STATE_CLOSED || isDisconnected_l()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700234 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
235 __func__, getHandle());
236 return AAUDIO_ERROR_INVALID_STATE;
237 }
238
Phil Burka9876702020-04-20 18:16:15 -0700239 mediametrics::Defer defer([&] {
240 mediametrics::LogItem(mMetricsId)
241 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700242 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700243 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
244 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
245 .record(); });
246
Eric Laurentcb4dae22017-07-01 19:39:32 -0700247 if (isRunning()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700248 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700249 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700250
Phil Burk23296382017-11-20 15:45:11 -0800251 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800252 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800253
Phil Burkbcc36742017-08-31 17:24:51 -0700254 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700255 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700256
Phil Burk39f02dd2017-08-04 09:13:31 -0700257 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700258 result = startDevice();
259 if (result != AAUDIO_OK) goto error;
260
261 // This should happen at the end of the start.
262 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
263 setState(AAUDIO_STREAM_STATE_STARTED);
264 mThreadEnabled.store(true);
Phil Burk3d201942021-04-08 23:27:04 +0000265 // Make sure this object does not get deleted before the run() method
266 // can protect it by making a strong pointer.
267 incStrong(nullptr); // See run() method.
Phil Burkbcc36742017-08-31 17:24:51 -0700268 result = mTimestampThread.start(this);
Phil Burk3d201942021-04-08 23:27:04 +0000269 if (result != AAUDIO_OK) {
270 decStrong(nullptr); // run() can't do it so we have to do it here.
271 goto error;
272 }
Phil Burkbcc36742017-08-31 17:24:51 -0700273
274 return result;
275
276error:
Phil Burk7ebbc112020-05-13 15:55:17 -0700277 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700278 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800279}
280
281aaudio_result_t AAudioServiceStreamBase::pause() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700282 std::lock_guard<std::mutex> lock(mLock);
283 return pause_l();
284}
285
286aaudio_result_t AAudioServiceStreamBase::pause_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700287 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700288 if (!isRunning()) {
289 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800290 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700291 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk73af62a2017-10-26 12:11:47 -0700292
Phil Burka9876702020-04-20 18:16:15 -0700293 mediametrics::Defer defer([&] {
294 mediametrics::LogItem(mMetricsId)
295 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700296 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700297 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
298 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
299 .record(); });
300
Phil Burk73af62a2017-10-26 12:11:47 -0700301 result = stopTimestampThread();
302 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700303 disconnect_l();
Phil Burk73af62a2017-10-26 12:11:47 -0700304 return result;
305 }
306
Phil Burk6e2770e2018-05-01 13:03:52 -0700307 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
308 if (endpoint == nullptr) {
309 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700310 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
311 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700312 }
313 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700314 if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700315 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700316 disconnect_l(); // TODO should we return or pause Base first?
Phil Burk39f02dd2017-08-04 09:13:31 -0700317 }
318
Eric Laurentcb4dae22017-07-01 19:39:32 -0700319 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
Phil Burkbcc36742017-08-31 17:24:51 -0700320 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burkc0c70e32017-02-09 13:18:38 -0800321 return result;
322}
323
Phil Burk71f35bb2017-04-13 16:05:07 -0700324aaudio_result_t AAudioServiceStreamBase::stop() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700325 std::lock_guard<std::mutex> lock(mLock);
326 return stop_l();
327}
328
329aaudio_result_t AAudioServiceStreamBase::stop_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700330 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700331 if (!isRunning()) {
332 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700333 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700334 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk39f02dd2017-08-04 09:13:31 -0700335
Phil Burka9876702020-04-20 18:16:15 -0700336 mediametrics::Defer defer([&] {
337 mediametrics::LogItem(mMetricsId)
338 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700339 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700340 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
341 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
342 .record(); });
343
Phil Burk83fb8442017-10-05 16:55:17 -0700344 setState(AAUDIO_STREAM_STATE_STOPPING);
345
Phil Burkd50ae622021-04-15 23:40:25 +0000346 // Temporarily unlock because we are joining the timestamp thread and it may try
347 // to acquire mLock.
348 mLock.unlock();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700349 result = stopTimestampThread();
Phil Burkd50ae622021-04-15 23:40:25 +0000350 mLock.lock();
351
Eric Laurentcb4dae22017-07-01 19:39:32 -0700352 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700353 disconnect_l();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700354 return result;
355 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700356
Phil Burk6e2770e2018-05-01 13:03:52 -0700357 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
358 if (endpoint == nullptr) {
359 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700360 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
361 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700362 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700363 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700364 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700365 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700366 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700367 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700368 // TODO what to do with result here?
369 }
370
Eric Laurentcb4dae22017-07-01 19:39:32 -0700371 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700372 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700373 return result;
374}
375
Phil Burk98d6d922017-07-06 11:52:45 -0700376aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
377 aaudio_result_t result = AAUDIO_OK;
378 // clear flag that tells thread to loop
379 if (mThreadEnabled.exchange(false)) {
Phil Burkbcc36742017-08-31 17:24:51 -0700380 result = mTimestampThread.stop();
Phil Burk98d6d922017-07-06 11:52:45 -0700381 }
382 return result;
383}
384
Phil Burk71f35bb2017-04-13 16:05:07 -0700385aaudio_result_t AAudioServiceStreamBase::flush() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700386 std::lock_guard<std::mutex> lock(mLock);
Phil Burk5cc83c32017-11-28 15:43:18 -0800387 aaudio_result_t result = AAudio_isFlushAllowed(getState());
388 if (result != AAUDIO_OK) {
389 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700390 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700391 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800392
Phil Burka9876702020-04-20 18:16:15 -0700393 mediametrics::Defer defer([&] {
394 mediametrics::LogItem(mMetricsId)
395 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700396 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700397 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
398 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
399 .record(); });
400
Phil Burk39f02dd2017-08-04 09:13:31 -0700401 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700402 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700403 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700404 return AAUDIO_OK;
405}
406
Phil Burkcf5f6d22017-05-26 12:35:07 -0700407// implement Runnable, periodically send timestamps to client
Phil Burka53ffa62018-10-10 16:21:37 -0700408__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800409void AAudioServiceStreamBase::run() {
Phil Burk19e990e2018-03-22 13:59:34 -0700410 ALOGD("%s() %s entering >>>>>>>>>>>>>> TIMESTAMPS", __func__, getTypeText());
Phil Burk3d201942021-04-08 23:27:04 +0000411 // Hold onto the ref counted stream until the end.
412 android::sp<AAudioServiceStreamBase> holdStream(this);
Phil Burkc0c70e32017-02-09 13:18:38 -0800413 TimestampScheduler timestampScheduler;
Phil Burk3d201942021-04-08 23:27:04 +0000414 // Balance the incStrong from when the thread was launched.
415 holdStream->decStrong(nullptr);
416
Phil Burk39f02dd2017-08-04 09:13:31 -0700417 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
Phil Burkc0c70e32017-02-09 13:18:38 -0800418 timestampScheduler.start(AudioClock::getNanoseconds());
419 int64_t nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burka53ffa62018-10-10 16:21:37 -0700420 int32_t loopCount = 0;
Phil Burk45da1b72021-04-07 06:30:50 +0000421 aaudio_result_t result = AAUDIO_OK;
Phil Burkc0c70e32017-02-09 13:18:38 -0800422 while(mThreadEnabled.load()) {
Phil Burka53ffa62018-10-10 16:21:37 -0700423 loopCount++;
Phil Burkc0c70e32017-02-09 13:18:38 -0800424 if (AudioClock::getNanoseconds() >= nextTime) {
Phil Burk45da1b72021-04-07 06:30:50 +0000425 result = sendCurrentTimestamp();
Phil Burkc0c70e32017-02-09 13:18:38 -0800426 if (result != AAUDIO_OK) {
Phil Burka53ffa62018-10-10 16:21:37 -0700427 ALOGE("%s() timestamp thread got result = %d", __func__, result);
Phil Burkc0c70e32017-02-09 13:18:38 -0800428 break;
429 }
430 nextTime = timestampScheduler.nextAbsoluteTime();
431 } else {
432 // Sleep until it is time to send the next timestamp.
Phil Burk98d6d922017-07-06 11:52:45 -0700433 // TODO Wait for a signal with a timeout so that we can stop more quickly.
Phil Burkc0c70e32017-02-09 13:18:38 -0800434 AudioClock::sleepUntilNanoTime(nextTime);
435 }
436 }
Phil Burk45da1b72021-04-07 06:30:50 +0000437 // This was moved from the calls in stop_l() and pause_l(), which could cause a deadlock
438 // if it resulted in a call to disconnect.
439 if (result == AAUDIO_OK) {
440 (void) sendCurrentTimestamp();
441 }
Phil Burka53ffa62018-10-10 16:21:37 -0700442 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< TIMESTAMPS",
443 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800444}
445
Phil Burk5ef003b2017-06-30 11:43:37 -0700446void AAudioServiceStreamBase::disconnect() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700447 std::lock_guard<std::mutex> lock(mLock);
448 disconnect_l();
449}
450
451void AAudioServiceStreamBase::disconnect_l() {
Phil Burkdb466142021-04-16 16:50:00 +0000452 if (!isDisconnected_l() && getState() != AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700453
Phil Burka9876702020-04-20 18:16:15 -0700454 mediametrics::LogItem(mMetricsId)
455 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
456 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
457 .record();
Phil Burk7ebbc112020-05-13 15:55:17 -0700458
Phil Burk5ef003b2017-06-30 11:43:37 -0700459 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkdb466142021-04-16 16:50:00 +0000460 setDisconnected_l(true);
Phil Burk5ef003b2017-06-30 11:43:37 -0700461 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800462}
463
Phil Burk7ebbc112020-05-13 15:55:17 -0700464aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId,
465 int priority) {
466 std::lock_guard<std::mutex> lock(mLock);
467 aaudio_result_t result = AAUDIO_OK;
468 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
469 ALOGE("AAudioService::registerAudioThread(), thread already registered");
470 result = AAUDIO_ERROR_INVALID_STATE;
471 } else {
472 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
473 setRegisteredThread(clientThreadId);
474 int err = android::requestPriority(ownerPid, clientThreadId,
475 priority, true /* isForApp */);
476 if (err != 0) {
477 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
478 clientThreadId, errno, priority);
479 result = AAUDIO_ERROR_INTERNAL;
480 }
481 }
482 return result;
483}
484
485aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
486 std::lock_guard<std::mutex> lock(mLock);
487 aaudio_result_t result = AAUDIO_OK;
488 if (getRegisteredThread() != clientThreadId) {
489 ALOGE("%s(), wrong thread", __func__);
490 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
491 } else {
492 setRegisteredThread(0);
493 }
494 return result;
495}
496
497void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
498 // CLOSED is a final state.
499 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
500 mState = state;
501 } else {
502 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
503 }
504}
505
Phil Burkc0c70e32017-02-09 13:18:38 -0800506aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800507 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800508 AAudioServiceMessage command;
509 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800510 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800511 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800512 return writeUpMessageQueue(&command);
513}
514
515aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
516 int64_t dataLong) {
517 AAudioServiceMessage command;
518 command.what = AAudioServiceMessage::code::EVENT;
519 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800520 command.event.dataLong = dataLong;
521 return writeUpMessageQueue(&command);
522}
523
Phil Burkf878a8d2019-03-29 17:23:00 -0700524bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
525 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
526 if (mUpMessageQueue == nullptr) {
527 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
528 return true;
529 }
Phil Burkf878a8d2019-03-29 17:23:00 -0700530 // Is it half full or more
Phil Burk8f4fe502020-07-15 23:54:50 +0000531 return mUpMessageQueue->getFractionalFullness() >= 0.5;
Phil Burkf878a8d2019-03-29 17:23:00 -0700532}
533
Phil Burkc0c70e32017-02-09 13:18:38 -0800534aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700535 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700536 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700537 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700538 return AAUDIO_ERROR_NULL;
539 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800540 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
541 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800542 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
543 __func__, command->what, getTypeText());
544 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800545 return AAUDIO_ERROR_WOULD_BLOCK;
546 } else {
547 return AAUDIO_OK;
548 }
549}
550
Phil Burk23296382017-11-20 15:45:11 -0800551aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
552 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
553}
554
Phil Burkc0c70e32017-02-09 13:18:38 -0800555aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
556 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700557 // It is not worth filling up the queue with timestamps.
558 // That can cause the stream to get suspended.
559 // So just drop the timestamp if the queue is getting full.
560 if (isUpMessageQueueBusy()) {
561 return AAUDIO_OK;
562 }
563
Phil Burk97350f92017-07-21 15:59:44 -0700564 // Send a timestamp for the clock model.
Phil Burkc0c70e32017-02-09 13:18:38 -0800565 aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
566 &command.timestamp.timestamp);
567 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700568 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700569 (long long) command.timestamp.position,
570 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700571 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800572 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700573
574 if (result == AAUDIO_OK) {
575 // Send a hardware timestamp for presentation time.
576 result = getHardwareTimestamp(&command.timestamp.position,
577 &command.timestamp.timestamp);
578 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700579 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700580 (long long) command.timestamp.position,
581 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700582 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
583 result = writeUpMessageQueue(&command);
584 }
585 }
586 }
587
Phil Burkbcc36742017-08-31 17:24:51 -0700588 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700589 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800590 }
591 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800592}
593
Phil Burkc0c70e32017-02-09 13:18:38 -0800594/**
595 * Get an immutable description of the in-memory queues
596 * used to communicate with the underlying HAL or Service.
597 */
598aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700599 std::lock_guard<std::mutex> lock(mLock);
Phil Burk523b3042017-09-13 13:03:08 -0700600 {
601 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
602 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700603 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700604 return AAUDIO_ERROR_NULL;
605 }
606 // Gather information on the message queue.
607 mUpMessageQueue->fillParcelable(parcelable,
608 parcelable.mUpMessageQueueParcelable);
609 }
610 return getAudioDataDescription(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700611}
Phil Burk39f02dd2017-08-04 09:13:31 -0700612
613void AAudioServiceStreamBase::onVolumeChanged(float volume) {
614 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
615}