blob: 8b5ccaabe5ca919fde8691c229b8c7fe3bc71cef [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();
Phil Burk2355edb2016-12-26 13:54:02 -080055}
56
Phil Burk5ed503c2017-02-01 09:38:15 -080057AAudioServiceStreamBase::~AAudioServiceStreamBase() {
Phil Burk8f4fe502020-07-15 23:54:50 +000058 ALOGD("%s() called", __func__);
59
Phil Burka9876702020-04-20 18:16:15 -070060 // May not be set if open failed.
61 if (mMetricsId.size() > 0) {
62 mediametrics::LogItem(mMetricsId)
63 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
64 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
65 .record();
66 }
67
Phil Burk5a26e662017-07-07 12:44:48 -070068 // If the stream is deleted when OPEN or in use then audio resources will leak.
69 // This would indicate an internal error. So we want to find this ASAP.
Phil Burkbcc36742017-08-31 17:24:51 -070070 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
Phil Burkdb466142021-04-16 16:50:00 +000071 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED),
Phil Burk8b4e05e2019-12-17 12:12:09 -080072 "service stream %p still open, state = %d",
73 this, getState());
jiabin2a594622021-10-14 00:32:25 +000074
75 // Stop the command thread before destroying.
76 if (mThreadEnabled) {
77 mThreadEnabled = false;
78 mCommandQueue.stopWaiting();
79 mCommandThread.stop();
80 }
Phil Burk2355edb2016-12-26 13:54:02 -080081}
82
Phil Burka5222e22017-07-28 13:31:14 -070083std::string AAudioServiceStreamBase::dumpHeader() {
jiabina9094092021-06-28 20:36:45 +000084 return std::string(
85 " T Handle UId Port Run State Format Burst Chan Mask Capacity");
Phil Burka5222e22017-07-28 13:31:14 -070086}
87
Phil Burk4501b352017-06-29 18:12:36 -070088std::string AAudioServiceStreamBase::dump() const {
89 std::stringstream result;
90
Phil Burka5222e22017-07-28 13:31:14 -070091 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
92 << std::dec << std::setfill(' ') ;
Svet Ganov33761132021-05-13 22:51:08 +000093 result << std::setw(6) << mMmapClient.attributionSource.uid;
Phil Burkbbd52862018-04-13 11:37:42 -070094 result << std::setw(7) << mClientHandle;
Phil Burka5222e22017-07-28 13:31:14 -070095 result << std::setw(4) << (isRunning() ? "yes" : " no");
Phil Burkbcc36742017-08-31 17:24:51 -070096 result << std::setw(6) << getState();
Phil Burk39f02dd2017-08-04 09:13:31 -070097 result << std::setw(7) << getFormat();
Phil Burka5222e22017-07-28 13:31:14 -070098 result << std::setw(6) << mFramesPerBurst;
Phil Burk39f02dd2017-08-04 09:13:31 -070099 result << std::setw(5) << getSamplesPerFrame();
jiabina9094092021-06-28 20:36:45 +0000100 result << std::setw(8) << std::hex << getChannelMask() << std::dec;
Phil Burk39f02dd2017-08-04 09:13:31 -0700101 result << std::setw(9) << getBufferCapacity();
Phil Burk4501b352017-06-29 18:12:36 -0700102
103 return result.str();
104}
105
Phil Burka9876702020-04-20 18:16:15 -0700106void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
107 // This is the first log sent from the AAudio Service for a stream.
108 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
109 + std::to_string(streamHandle);
110
111 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
112
113 // Once this item is logged by the server, the client with the same PID, UID
114 // can also log properties.
115 mediametrics::LogItem(mMetricsId)
116 .setPid(getOwnerProcessId())
117 .setUid(getOwnerUserId())
Andy Hungd203eb62020-04-27 09:12:46 -0700118 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
Phil Burka9876702020-04-20 18:16:15 -0700119 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
120 // the following are immutable
121 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
122 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
123 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
124 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
125 .set(AMEDIAMETRICS_PROP_DIRECTION,
126 AudioGlobal_convertDirectionToText(getDirection()))
127 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
128 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
129 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
130 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
131 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
132 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
133 .record();
134}
135
Phil Burk15f97c92018-09-04 14:06:27 -0700136aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700137 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
138 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700139
Svet Ganov33761132021-05-13 22:51:08 +0000140 mMmapClient.attributionSource = request.getAttributionSource();
141 // TODO b/182392769: use attribution source util
142 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700143 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000144 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700145 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Eric Laurentcb4dae22017-07-01 19:39:32 -0700146
Phil Burk39f02dd2017-08-04 09:13:31 -0700147 // Limit scope of lock to avoid recursive lock in close().
148 {
149 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
150 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700151 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700152 return AAUDIO_ERROR_INVALID_STATE;
153 }
154
Phil Burk8f4fe502020-07-15 23:54:50 +0000155 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700156 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
157 QUEUE_UP_CAPACITY_COMMANDS);
158 if (result != AAUDIO_OK) {
159 goto error;
160 }
161
Phil Burk6e2770e2018-05-01 13:03:52 -0700162 // This is not protected by a lock because the stream cannot be
163 // referenced until the service returns a handle to the client.
164 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700165 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700166 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700167 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700168 result = AAUDIO_ERROR_UNAVAILABLE;
169 goto error;
170 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700171 // Save a weak pointer that we will use to access the endpoint.
172 mServiceEndpointWeak = mServiceEndpoint;
173
Phil Burk39f02dd2017-08-04 09:13:31 -0700174 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
175 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800176 }
jiabin2a594622021-10-14 00:32:25 +0000177
178 // Make sure this object does not get deleted before the run() method
179 // can protect it by making a strong pointer.
jiabinba75f212021-12-07 20:06:30 +0000180 mCommandQueue.startWaiting();
jiabin2a594622021-10-14 00:32:25 +0000181 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:
jiabinba75f212021-12-07 20:06:30 +0000191 closeAndClear();
192 mThreadEnabled = false;
193 mCommandQueue.stopWaiting();
194 mCommandThread.stop();
Phil Burk39f02dd2017-08-04 09:13:31 -0700195 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800196}
Phil Burkdec33ab2017-01-17 14:48:16 -0800197
Phil Burkc0c70e32017-02-09 13:18:38 -0800198aaudio_result_t AAudioServiceStreamBase::close() {
jiabinba75f212021-12-07 20:06:30 +0000199 aaudio_result_t result = sendCommand(CLOSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
jiabin2a594622021-10-14 00:32:25 +0000200
201 // Stop the command thread as the stream is closed.
202 mThreadEnabled = false;
203 mCommandQueue.stopWaiting();
204 mCommandThread.stop();
205
206 return result;
Phil Burk7ebbc112020-05-13 15:55:17 -0700207}
208
209aaudio_result_t AAudioServiceStreamBase::close_l() {
Phil Burkbcc36742017-08-31 17:24:51 -0700210 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700211 return AAUDIO_OK;
212 }
213
jiabin2a594622021-10-14 00:32:25 +0000214 // This will stop the stream, just in case it was not already stopped.
Phil Burk7ebbc112020-05-13 15:55:17 -0700215 stop_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700216
jiabinba75f212021-12-07 20:06:30 +0000217 return closeAndClear();
Phil Burkc0c70e32017-02-09 13:18:38 -0800218}
219
Phil Burkbcc36742017-08-31 17:24:51 -0700220aaudio_result_t AAudioServiceStreamBase::startDevice() {
221 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700222 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
223 if (endpoint == nullptr) {
224 ALOGE("%s() has no endpoint", __func__);
225 return AAUDIO_ERROR_INVALID_STATE;
226 }
227 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700228}
229
Phil Burk39f02dd2017-08-04 09:13:31 -0700230/**
231 * Start the flow of audio data.
232 *
233 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
234 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800235aaudio_result_t AAudioServiceStreamBase::start() {
jiabinba75f212021-12-07 20:06:30 +0000236 return sendCommand(START, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
jiabin2a594622021-10-14 00:32:25 +0000237}
Phil Burk7ebbc112020-05-13 15:55:17 -0700238
jiabin2a594622021-10-14 00:32:25 +0000239aaudio_result_t AAudioServiceStreamBase::start_l() {
Phil Burka9876702020-04-20 18:16:15 -0700240 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700241 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700242
Phil Burk7ebbc112020-05-13 15:55:17 -0700243 if (auto state = getState();
Phil Burkdb466142021-04-16 16:50:00 +0000244 state == AAUDIO_STREAM_STATE_CLOSED || isDisconnected_l()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700245 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
246 __func__, getHandle());
247 return AAUDIO_ERROR_INVALID_STATE;
248 }
249
Phil Burka9876702020-04-20 18:16:15 -0700250 mediametrics::Defer defer([&] {
251 mediametrics::LogItem(mMetricsId)
252 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700253 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700254 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
255 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
256 .record(); });
257
Eric Laurentcb4dae22017-07-01 19:39:32 -0700258 if (isRunning()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700259 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700260 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700261
Phil Burk23296382017-11-20 15:45:11 -0800262 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800263 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800264
Phil Burkbcc36742017-08-31 17:24:51 -0700265 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700266 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700267
Phil Burk39f02dd2017-08-04 09:13:31 -0700268 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700269 result = startDevice();
270 if (result != AAUDIO_OK) goto error;
271
272 // This should happen at the end of the start.
273 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
274 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burkbcc36742017-08-31 17:24:51 -0700275
276 return result;
277
278error:
Phil Burk7ebbc112020-05-13 15:55:17 -0700279 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700280 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800281}
282
283aaudio_result_t AAudioServiceStreamBase::pause() {
jiabinba75f212021-12-07 20:06:30 +0000284 return sendCommand(PAUSE, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
Phil Burk7ebbc112020-05-13 15:55:17 -0700285}
286
287aaudio_result_t AAudioServiceStreamBase::pause_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700288 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700289 if (!isRunning()) {
290 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800291 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700292 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk73af62a2017-10-26 12:11:47 -0700293
Phil Burka9876702020-04-20 18:16:15 -0700294 mediametrics::Defer defer([&] {
295 mediametrics::LogItem(mMetricsId)
296 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700297 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700298 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
299 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
300 .record(); });
301
Phil Burk6e2770e2018-05-01 13:03:52 -0700302 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
303 if (endpoint == nullptr) {
304 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700305 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
306 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700307 }
308 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700309 if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700310 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700311 disconnect_l(); // TODO should we return or pause Base first?
Phil Burk39f02dd2017-08-04 09:13:31 -0700312 }
313
Eric Laurentcb4dae22017-07-01 19:39:32 -0700314 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
Phil Burkbcc36742017-08-31 17:24:51 -0700315 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burkc0c70e32017-02-09 13:18:38 -0800316 return result;
317}
318
Phil Burk71f35bb2017-04-13 16:05:07 -0700319aaudio_result_t AAudioServiceStreamBase::stop() {
jiabinba75f212021-12-07 20:06:30 +0000320 return sendCommand(STOP, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
Phil Burk7ebbc112020-05-13 15:55:17 -0700321}
322
323aaudio_result_t AAudioServiceStreamBase::stop_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700324 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700325 if (!isRunning()) {
326 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700327 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700328 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk39f02dd2017-08-04 09:13:31 -0700329
Phil Burka9876702020-04-20 18:16:15 -0700330 mediametrics::Defer defer([&] {
331 mediametrics::LogItem(mMetricsId)
332 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700333 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700334 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
335 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
336 .record(); });
337
Phil Burk83fb8442017-10-05 16:55:17 -0700338 setState(AAUDIO_STREAM_STATE_STOPPING);
339
Eric Laurentcb4dae22017-07-01 19:39:32 -0700340 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700341 disconnect_l();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700342 return result;
343 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700344
Phil Burk6e2770e2018-05-01 13:03:52 -0700345 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
346 if (endpoint == nullptr) {
347 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700348 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
349 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700350 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700351 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700352 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700353 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700354 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700355 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700356 // TODO what to do with result here?
357 }
358
Eric Laurentcb4dae22017-07-01 19:39:32 -0700359 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700360 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700361 return result;
362}
363
jiabin2a594622021-10-14 00:32:25 +0000364aaudio_result_t AAudioServiceStreamBase::flush() {
jiabinba75f212021-12-07 20:06:30 +0000365 return sendCommand(FLUSH, nullptr, true /*waitForReply*/, TIMEOUT_NANOS);
Phil Burk98d6d922017-07-06 11:52:45 -0700366}
367
jiabin2a594622021-10-14 00:32:25 +0000368aaudio_result_t AAudioServiceStreamBase::flush_l() {
Phil Burk5cc83c32017-11-28 15:43:18 -0800369 aaudio_result_t result = AAudio_isFlushAllowed(getState());
370 if (result != AAUDIO_OK) {
371 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700372 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700373 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800374
Phil Burka9876702020-04-20 18:16:15 -0700375 mediametrics::Defer defer([&] {
376 mediametrics::LogItem(mMetricsId)
377 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700378 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700379 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
380 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
381 .record(); });
382
Phil Burk39f02dd2017-08-04 09:13:31 -0700383 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700384 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700385 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700386 return AAUDIO_OK;
387}
388
jiabin2a594622021-10-14 00:32:25 +0000389// implement Runnable, periodically send timestamps to client and process commands from queue.
Phil Burka53ffa62018-10-10 16:21:37 -0700390__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800391void AAudioServiceStreamBase::run() {
jiabin2a594622021-10-14 00:32:25 +0000392 ALOGD("%s() %s entering >>>>>>>>>>>>>> COMMANDS", __func__, getTypeText());
Phil Burk3d201942021-04-08 23:27:04 +0000393 // Hold onto the ref counted stream until the end.
394 android::sp<AAudioServiceStreamBase> holdStream(this);
Phil Burkc0c70e32017-02-09 13:18:38 -0800395 TimestampScheduler timestampScheduler;
jiabin2a594622021-10-14 00:32:25 +0000396 int64_t nextTime;
Phil Burk3d201942021-04-08 23:27:04 +0000397 // Balance the incStrong from when the thread was launched.
398 holdStream->decStrong(nullptr);
399
jiabin2a594622021-10-14 00:32:25 +0000400 // Taking mLock while starting the thread. All the operation must be able to
401 // run with holding the lock.
402 std::scoped_lock<std::mutex> _l(mLock);
403
Phil Burka53ffa62018-10-10 16:21:37 -0700404 int32_t loopCount = 0;
jiabin2a594622021-10-14 00:32:25 +0000405 while (mThreadEnabled.load()) {
Phil Burka53ffa62018-10-10 16:21:37 -0700406 loopCount++;
jiabin2a594622021-10-14 00:32:25 +0000407 int64_t timeoutNanos = -1;
408 if (isRunning()) {
409 timeoutNanos = nextTime - AudioClock::getNanoseconds();
410 timeoutNanos = std::max<int64_t>(0, timeoutNanos);
411 }
412
413 auto command = mCommandQueue.waitForCommand(timeoutNanos);
414 if (!mThreadEnabled) {
415 // Break the loop if the thread is disabled.
416 break;
417 }
418
419 if (isRunning() && AudioClock::getNanoseconds() >= nextTime) {
420 // It is time to update timestamp.
421 if (sendCurrentTimestamp_l() != AAUDIO_OK) {
422 ALOGE("Failed to send current timestamp, stop updating timestamp");
423 disconnect_l();
424 } else {
425 nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burkc0c70e32017-02-09 13:18:38 -0800426 }
jiabin2a594622021-10-14 00:32:25 +0000427 }
428
429 if (command != nullptr) {
430 std::scoped_lock<std::mutex> _commandLock(command->lock);
431 switch (command->operationCode) {
432 case START:
433 command->result = start_l();
434 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
435 timestampScheduler.start(AudioClock::getNanoseconds());
436 nextTime = timestampScheduler.nextAbsoluteTime();
437 break;
438 case PAUSE:
439 command->result = pause_l();
440 break;
441 case STOP:
442 command->result = stop_l();
443 break;
444 case FLUSH:
445 command->result = flush_l();
446 break;
447 case CLOSE:
448 command->result = close_l();
449 break;
450 case DISCONNECT:
451 disconnect_l();
452 break;
453 case REGISTER_AUDIO_THREAD: {
454 RegisterAudioThreadParam *param =
455 (RegisterAudioThreadParam *) command->parameter.get();
456 command->result =
457 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
458 : registerAudioThread_l(param->mOwnerPid,
459 param->mClientThreadId,
460 param->mPriority);
461 }
462 break;
463 case UNREGISTER_AUDIO_THREAD: {
464 UnregisterAudioThreadParam *param =
465 (UnregisterAudioThreadParam *) command->parameter.get();
466 command->result =
467 param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
468 : unregisterAudioThread_l(param->mClientThreadId);
469 }
470 break;
471 case GET_DESCRIPTION: {
472 GetDescriptionParam *param = (GetDescriptionParam *) command->parameter.get();
473 command->result = param == nullptr ? AAUDIO_ERROR_ILLEGAL_ARGUMENT
474 : getDescription_l(param->mParcelable);
475 }
476 break;
477 default:
478 ALOGE("Invalid command op code: %d", command->operationCode);
479 break;
480 }
481 if (command->isWaitingForReply) {
482 command->isWaitingForReply = false;
483 command->conditionVariable.notify_one();
484 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800485 }
486 }
jiabin2a594622021-10-14 00:32:25 +0000487 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< COMMANDS",
Phil Burka53ffa62018-10-10 16:21:37 -0700488 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800489}
490
Phil Burk5ef003b2017-06-30 11:43:37 -0700491void AAudioServiceStreamBase::disconnect() {
jiabinba75f212021-12-07 20:06:30 +0000492 sendCommand(DISCONNECT);
Phil Burk7ebbc112020-05-13 15:55:17 -0700493}
494
495void AAudioServiceStreamBase::disconnect_l() {
Phil Burkdb466142021-04-16 16:50:00 +0000496 if (!isDisconnected_l() && getState() != AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700497
Phil Burka9876702020-04-20 18:16:15 -0700498 mediametrics::LogItem(mMetricsId)
499 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
500 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
501 .record();
Phil Burk7ebbc112020-05-13 15:55:17 -0700502
Phil Burk5ef003b2017-06-30 11:43:37 -0700503 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkdb466142021-04-16 16:50:00 +0000504 setDisconnected_l(true);
Phil Burk5ef003b2017-06-30 11:43:37 -0700505 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800506}
507
jiabin2a594622021-10-14 00:32:25 +0000508aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId, int priority) {
509 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
jiabinba75f212021-12-07 20:06:30 +0000510 return sendCommand(REGISTER_AUDIO_THREAD,
jiabin2a594622021-10-14 00:32:25 +0000511 std::make_shared<RegisterAudioThreadParam>(ownerPid, clientThreadId, priority),
512 true /*waitForReply*/,
513 TIMEOUT_NANOS);
jiabin2a594622021-10-14 00:32:25 +0000514}
515
516aaudio_result_t AAudioServiceStreamBase::registerAudioThread_l(
517 pid_t ownerPid, pid_t clientThreadId, int priority) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700518 aaudio_result_t result = AAUDIO_OK;
519 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
520 ALOGE("AAudioService::registerAudioThread(), thread already registered");
521 result = AAUDIO_ERROR_INVALID_STATE;
522 } else {
Phil Burk7ebbc112020-05-13 15:55:17 -0700523 setRegisteredThread(clientThreadId);
524 int err = android::requestPriority(ownerPid, clientThreadId,
525 priority, true /* isForApp */);
526 if (err != 0) {
527 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
528 clientThreadId, errno, priority);
529 result = AAUDIO_ERROR_INTERNAL;
530 }
531 }
532 return result;
533}
534
535aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
jiabinba75f212021-12-07 20:06:30 +0000536 return sendCommand(UNREGISTER_AUDIO_THREAD,
jiabin2a594622021-10-14 00:32:25 +0000537 std::make_shared<UnregisterAudioThreadParam>(clientThreadId),
538 true /*waitForReply*/,
539 TIMEOUT_NANOS);
jiabin2a594622021-10-14 00:32:25 +0000540}
541
542aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread_l(pid_t clientThreadId) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700543 aaudio_result_t result = AAUDIO_OK;
544 if (getRegisteredThread() != clientThreadId) {
545 ALOGE("%s(), wrong thread", __func__);
546 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
547 } else {
548 setRegisteredThread(0);
549 }
550 return result;
551}
552
553void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
554 // CLOSED is a final state.
555 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
556 mState = state;
557 } else {
558 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
559 }
560}
561
Phil Burkc0c70e32017-02-09 13:18:38 -0800562aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800563 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800564 AAudioServiceMessage command;
565 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800566 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800567 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800568 return writeUpMessageQueue(&command);
569}
570
571aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
572 int64_t dataLong) {
573 AAudioServiceMessage command;
574 command.what = AAudioServiceMessage::code::EVENT;
575 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800576 command.event.dataLong = dataLong;
577 return writeUpMessageQueue(&command);
578}
579
Phil Burkf878a8d2019-03-29 17:23:00 -0700580bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
581 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
582 if (mUpMessageQueue == nullptr) {
583 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
584 return true;
585 }
Phil Burkf878a8d2019-03-29 17:23:00 -0700586 // Is it half full or more
Phil Burk8f4fe502020-07-15 23:54:50 +0000587 return mUpMessageQueue->getFractionalFullness() >= 0.5;
Phil Burkf878a8d2019-03-29 17:23:00 -0700588}
589
Phil Burkc0c70e32017-02-09 13:18:38 -0800590aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700591 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700592 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700593 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700594 return AAUDIO_ERROR_NULL;
595 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800596 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
597 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800598 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
599 __func__, command->what, getTypeText());
600 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800601 return AAUDIO_ERROR_WOULD_BLOCK;
602 } else {
603 return AAUDIO_OK;
604 }
605}
606
Phil Burk23296382017-11-20 15:45:11 -0800607aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
608 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
609}
610
jiabin2a594622021-10-14 00:32:25 +0000611aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp_l() {
Phil Burkc0c70e32017-02-09 13:18:38 -0800612 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700613 // It is not worth filling up the queue with timestamps.
614 // That can cause the stream to get suspended.
615 // So just drop the timestamp if the queue is getting full.
616 if (isUpMessageQueueBusy()) {
617 return AAUDIO_OK;
618 }
619
Phil Burk97350f92017-07-21 15:59:44 -0700620 // Send a timestamp for the clock model.
jiabin2a594622021-10-14 00:32:25 +0000621 aaudio_result_t result = getFreeRunningPosition_l(&command.timestamp.position,
622 &command.timestamp.timestamp);
Phil Burkc0c70e32017-02-09 13:18:38 -0800623 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700624 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700625 (long long) command.timestamp.position,
626 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700627 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800628 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700629
630 if (result == AAUDIO_OK) {
631 // Send a hardware timestamp for presentation time.
jiabin2a594622021-10-14 00:32:25 +0000632 result = getHardwareTimestamp_l(&command.timestamp.position,
633 &command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700634 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700635 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700636 (long long) command.timestamp.position,
637 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700638 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
639 result = writeUpMessageQueue(&command);
640 }
641 }
642 }
643
Phil Burkbcc36742017-08-31 17:24:51 -0700644 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700645 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800646 }
647 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800648}
649
Phil Burkc0c70e32017-02-09 13:18:38 -0800650/**
651 * Get an immutable description of the in-memory queues
652 * used to communicate with the underlying HAL or Service.
653 */
654aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
jiabinba75f212021-12-07 20:06:30 +0000655 return sendCommand(
jiabin2a594622021-10-14 00:32:25 +0000656 GET_DESCRIPTION,
657 std::make_shared<GetDescriptionParam>(&parcelable),
658 true /*waitForReply*/,
659 TIMEOUT_NANOS);
jiabin2a594622021-10-14 00:32:25 +0000660}
661
662aaudio_result_t AAudioServiceStreamBase::getDescription_l(AudioEndpointParcelable* parcelable) {
Phil Burk523b3042017-09-13 13:03:08 -0700663 {
664 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
665 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700666 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700667 return AAUDIO_ERROR_NULL;
668 }
669 // Gather information on the message queue.
670 mUpMessageQueue->fillParcelable(parcelable,
jiabin2a594622021-10-14 00:32:25 +0000671 parcelable->mUpMessageQueueParcelable);
Phil Burk523b3042017-09-13 13:03:08 -0700672 }
jiabin2a594622021-10-14 00:32:25 +0000673 return getAudioDataDescription_l(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700674}
Phil Burk39f02dd2017-08-04 09:13:31 -0700675
676void AAudioServiceStreamBase::onVolumeChanged(float volume) {
677 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
678}
jiabinba75f212021-12-07 20:06:30 +0000679
680aaudio_result_t AAudioServiceStreamBase::sendCommand(aaudio_command_opcode opCode,
681 std::shared_ptr<AAudioCommandParam> param,
682 bool waitForReply,
683 int64_t timeoutNanos) {
684 return mCommandQueue.sendCommand(std::make_shared<AAudioCommand>(
685 opCode, param, waitForReply, timeoutNanos));
686}
687
688aaudio_result_t AAudioServiceStreamBase::closeAndClear() {
689 aaudio_result_t result = AAUDIO_OK;
690 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
691 if (endpoint == nullptr) {
692 result = AAUDIO_ERROR_INVALID_STATE;
693 } else {
694 endpoint->unregisterStream(this);
695 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
696 endpointManager.closeEndpoint(endpoint);
697
698 // AAudioService::closeStream() prevents two threads from closing at the same time.
699 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
700 }
701
702 setState(AAUDIO_STREAM_STATE_CLOSED);
703
704 mediametrics::LogItem(mMetricsId)
705 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
706 .record();
707 return result;
708}