blob: 75f1f3e9cf9fef214b03d96da5b86c7868630bb4 [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
Philip P. Moltmannbda45752020-07-17 16:41:18 -070042using media::permission::Identity;
43
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) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -070053 mMmapClient.identity = Identity();
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
70 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED
71 || getState() == AAUDIO_STREAM_STATE_DISCONNECTED),
Phil Burk8b4e05e2019-12-17 12:12:09 -080072 "service stream %p still open, state = %d",
73 this, getState());
Phil Burk2355edb2016-12-26 13:54:02 -080074}
75
Phil Burka5222e22017-07-28 13:31:14 -070076std::string AAudioServiceStreamBase::dumpHeader() {
Phil Burkbbd52862018-04-13 11:37:42 -070077 return std::string(" T Handle UId Port Run State Format Burst Chan 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(' ') ;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070085 result << std::setw(6) << mMmapClient.identity.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();
92 result << std::setw(9) << getBufferCapacity();
Phil Burk4501b352017-06-29 18:12:36 -070093
94 return result.str();
95}
96
Phil Burka9876702020-04-20 18:16:15 -070097void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
98 // This is the first log sent from the AAudio Service for a stream.
99 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
100 + std::to_string(streamHandle);
101
102 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
103
104 // Once this item is logged by the server, the client with the same PID, UID
105 // can also log properties.
106 mediametrics::LogItem(mMetricsId)
107 .setPid(getOwnerProcessId())
108 .setUid(getOwnerUserId())
Andy Hungd203eb62020-04-27 09:12:46 -0700109 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
Phil Burka9876702020-04-20 18:16:15 -0700110 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
111 // the following are immutable
112 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
113 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
114 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
115 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
116 .set(AMEDIAMETRICS_PROP_DIRECTION,
117 AudioGlobal_convertDirectionToText(getDirection()))
118 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
119 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
120 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
121 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
122 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
123 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
124 .record();
125}
126
Phil Burk15f97c92018-09-04 14:06:27 -0700127aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700128 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
129 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700130
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700131 mMmapClient.identity = request.getIdentity();
132 // TODO b/182392769: use identity util
133 mMmapClient.identity.uid = VALUE_OR_FATAL(
134 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
135 mMmapClient.identity.pid = VALUE_OR_FATAL(
136 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Eric Laurentcb4dae22017-07-01 19:39:32 -0700137
Phil Burk39f02dd2017-08-04 09:13:31 -0700138 // Limit scope of lock to avoid recursive lock in close().
139 {
140 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
141 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700142 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700143 return AAUDIO_ERROR_INVALID_STATE;
144 }
145
Phil Burk8f4fe502020-07-15 23:54:50 +0000146 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700147 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
148 QUEUE_UP_CAPACITY_COMMANDS);
149 if (result != AAUDIO_OK) {
150 goto error;
151 }
152
Phil Burk6e2770e2018-05-01 13:03:52 -0700153 // This is not protected by a lock because the stream cannot be
154 // referenced until the service returns a handle to the client.
155 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700156 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700157 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700158 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700159 result = AAUDIO_ERROR_UNAVAILABLE;
160 goto error;
161 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700162 // Save a weak pointer that we will use to access the endpoint.
163 mServiceEndpointWeak = mServiceEndpoint;
164
Phil Burk39f02dd2017-08-04 09:13:31 -0700165 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
166 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800167 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700168 return result;
169
170error:
171 close();
172 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800173}
Phil Burkdec33ab2017-01-17 14:48:16 -0800174
Phil Burkc0c70e32017-02-09 13:18:38 -0800175aaudio_result_t AAudioServiceStreamBase::close() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700176 std::lock_guard<std::mutex> lock(mLock);
177 return close_l();
178}
179
180aaudio_result_t AAudioServiceStreamBase::close_l() {
Phil Burkbcc36742017-08-31 17:24:51 -0700181 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700182 return AAUDIO_OK;
183 }
184
Phil Burk8f4fe502020-07-15 23:54:50 +0000185 // This will call stopTimestampThread() and also stop the stream,
186 // just in case it was not already stopped.
Phil Burk7ebbc112020-05-13 15:55:17 -0700187 stop_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700188
Phil Burk8b4e05e2019-12-17 12:12:09 -0800189 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700190 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
191 if (endpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700192 result = AAUDIO_ERROR_INVALID_STATE;
193 } else {
Phil Burk6e2770e2018-05-01 13:03:52 -0700194 endpoint->unregisterStream(this);
195 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
196 endpointManager.closeEndpoint(endpoint);
197
198 // AAudioService::closeStream() prevents two threads from closing at the same time.
Phil Burk7ebbc112020-05-13 15:55:17 -0700199 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
Phil Burk39f02dd2017-08-04 09:13:31 -0700200 }
201
Phil Burkbcc36742017-08-31 17:24:51 -0700202 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burka9876702020-04-20 18:16:15 -0700203
204 mediametrics::LogItem(mMetricsId)
205 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
206 .record();
Phil Burk39f02dd2017-08-04 09:13:31 -0700207 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800208}
209
Phil Burkbcc36742017-08-31 17:24:51 -0700210aaudio_result_t AAudioServiceStreamBase::startDevice() {
211 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700212 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
213 if (endpoint == nullptr) {
214 ALOGE("%s() has no endpoint", __func__);
215 return AAUDIO_ERROR_INVALID_STATE;
216 }
217 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700218}
219
Phil Burk39f02dd2017-08-04 09:13:31 -0700220/**
221 * Start the flow of audio data.
222 *
223 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
224 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800225aaudio_result_t AAudioServiceStreamBase::start() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700226 std::lock_guard<std::mutex> lock(mLock);
227
Phil Burka9876702020-04-20 18:16:15 -0700228 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700229 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700230
Phil Burk7ebbc112020-05-13 15:55:17 -0700231 if (auto state = getState();
232 state == AAUDIO_STREAM_STATE_CLOSED || state == AAUDIO_STREAM_STATE_DISCONNECTED) {
233 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
234 __func__, getHandle());
235 return AAUDIO_ERROR_INVALID_STATE;
236 }
237
Phil Burka9876702020-04-20 18:16:15 -0700238 mediametrics::Defer defer([&] {
239 mediametrics::LogItem(mMetricsId)
240 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700241 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700242 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
243 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
244 .record(); });
245
Eric Laurentcb4dae22017-07-01 19:39:32 -0700246 if (isRunning()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700247 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700248 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700249
Phil Burk23296382017-11-20 15:45:11 -0800250 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800251 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800252
Phil Burkbcc36742017-08-31 17:24:51 -0700253 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700254 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700255
Phil Burk39f02dd2017-08-04 09:13:31 -0700256 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700257 result = startDevice();
258 if (result != AAUDIO_OK) goto error;
259
260 // This should happen at the end of the start.
261 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
262 setState(AAUDIO_STREAM_STATE_STARTED);
263 mThreadEnabled.store(true);
Phil Burk3d201942021-04-08 23:27:04 +0000264 // Make sure this object does not get deleted before the run() method
265 // can protect it by making a strong pointer.
266 incStrong(nullptr); // See run() method.
Phil Burkbcc36742017-08-31 17:24:51 -0700267 result = mTimestampThread.start(this);
Phil Burk3d201942021-04-08 23:27:04 +0000268 if (result != AAUDIO_OK) {
269 decStrong(nullptr); // run() can't do it so we have to do it here.
270 goto error;
271 }
Phil Burkbcc36742017-08-31 17:24:51 -0700272
273 return result;
274
275error:
Phil Burk7ebbc112020-05-13 15:55:17 -0700276 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700277 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800278}
279
280aaudio_result_t AAudioServiceStreamBase::pause() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700281 std::lock_guard<std::mutex> lock(mLock);
282 return pause_l();
283}
284
285aaudio_result_t AAudioServiceStreamBase::pause_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700286 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700287 if (!isRunning()) {
288 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800289 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700290 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk73af62a2017-10-26 12:11:47 -0700291
Phil Burka9876702020-04-20 18:16:15 -0700292 mediametrics::Defer defer([&] {
293 mediametrics::LogItem(mMetricsId)
294 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700295 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700296 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
297 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
298 .record(); });
299
Phil Burk73af62a2017-10-26 12:11:47 -0700300 // Send it now because the timestamp gets rounded up when stopStream() is called below.
301 // Also we don't need the timestamps while we are shutting down.
302 sendCurrentTimestamp();
303
304 result = stopTimestampThread();
305 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700306 disconnect_l();
Phil Burk73af62a2017-10-26 12:11:47 -0700307 return result;
308 }
309
Phil Burk6e2770e2018-05-01 13:03:52 -0700310 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
311 if (endpoint == nullptr) {
312 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700313 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
314 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700315 }
316 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700317 if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700318 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700319 disconnect_l(); // TODO should we return or pause Base first?
Phil Burk39f02dd2017-08-04 09:13:31 -0700320 }
321
Eric Laurentcb4dae22017-07-01 19:39:32 -0700322 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
Phil Burkbcc36742017-08-31 17:24:51 -0700323 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burkc0c70e32017-02-09 13:18:38 -0800324 return result;
325}
326
Phil Burk71f35bb2017-04-13 16:05:07 -0700327aaudio_result_t AAudioServiceStreamBase::stop() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700328 std::lock_guard<std::mutex> lock(mLock);
329 return stop_l();
330}
331
332aaudio_result_t AAudioServiceStreamBase::stop_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700333 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700334 if (!isRunning()) {
335 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700336 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700337 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk39f02dd2017-08-04 09:13:31 -0700338
Phil Burka9876702020-04-20 18:16:15 -0700339 mediametrics::Defer defer([&] {
340 mediametrics::LogItem(mMetricsId)
341 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700342 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700343 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
344 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
345 .record(); });
346
Phil Burk83fb8442017-10-05 16:55:17 -0700347 setState(AAUDIO_STREAM_STATE_STOPPING);
348
Phil Burk73af62a2017-10-26 12:11:47 -0700349 // Send it now because the timestamp gets rounded up when stopStream() is called below.
350 // Also we don't need the timestamps while we are shutting down.
Eric Laurentcb4dae22017-07-01 19:39:32 -0700351 sendCurrentTimestamp(); // warning - this calls a virtual function
352 result = stopTimestampThread();
353 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700354 disconnect_l();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700355 return result;
356 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700357
Phil Burk6e2770e2018-05-01 13:03:52 -0700358 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
359 if (endpoint == nullptr) {
360 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700361 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
362 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700363 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700364 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700365 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700366 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700367 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700368 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700369 // TODO what to do with result here?
370 }
371
Eric Laurentcb4dae22017-07-01 19:39:32 -0700372 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700373 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700374 return result;
375}
376
Phil Burk98d6d922017-07-06 11:52:45 -0700377aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
378 aaudio_result_t result = AAUDIO_OK;
379 // clear flag that tells thread to loop
380 if (mThreadEnabled.exchange(false)) {
Phil Burkbcc36742017-08-31 17:24:51 -0700381 result = mTimestampThread.stop();
Phil Burk98d6d922017-07-06 11:52:45 -0700382 }
383 return result;
384}
385
Phil Burk71f35bb2017-04-13 16:05:07 -0700386aaudio_result_t AAudioServiceStreamBase::flush() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700387 std::lock_guard<std::mutex> lock(mLock);
Phil Burk5cc83c32017-11-28 15:43:18 -0800388 aaudio_result_t result = AAudio_isFlushAllowed(getState());
389 if (result != AAUDIO_OK) {
390 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700391 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700392 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800393
Phil Burka9876702020-04-20 18:16:15 -0700394 mediametrics::Defer defer([&] {
395 mediametrics::LogItem(mMetricsId)
396 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700397 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700398 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
399 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
400 .record(); });
401
Phil Burk39f02dd2017-08-04 09:13:31 -0700402 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700403 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700404 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700405 return AAUDIO_OK;
406}
407
Phil Burkcf5f6d22017-05-26 12:35:07 -0700408// implement Runnable, periodically send timestamps to client
Phil Burka53ffa62018-10-10 16:21:37 -0700409__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800410void AAudioServiceStreamBase::run() {
Phil Burk19e990e2018-03-22 13:59:34 -0700411 ALOGD("%s() %s entering >>>>>>>>>>>>>> TIMESTAMPS", __func__, getTypeText());
Phil Burk3d201942021-04-08 23:27:04 +0000412 // Hold onto the ref counted stream until the end.
413 android::sp<AAudioServiceStreamBase> holdStream(this);
Phil Burkc0c70e32017-02-09 13:18:38 -0800414 TimestampScheduler timestampScheduler;
Phil Burk3d201942021-04-08 23:27:04 +0000415 // Balance the incStrong from when the thread was launched.
416 holdStream->decStrong(nullptr);
417
Phil Burk39f02dd2017-08-04 09:13:31 -0700418 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
Phil Burkc0c70e32017-02-09 13:18:38 -0800419 timestampScheduler.start(AudioClock::getNanoseconds());
420 int64_t nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burka53ffa62018-10-10 16:21:37 -0700421 int32_t loopCount = 0;
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) {
425 aaudio_result_t result = sendCurrentTimestamp();
426 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 Burka53ffa62018-10-10 16:21:37 -0700437 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< TIMESTAMPS",
438 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800439}
440
Phil Burk5ef003b2017-06-30 11:43:37 -0700441void AAudioServiceStreamBase::disconnect() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700442 std::lock_guard<std::mutex> lock(mLock);
443 disconnect_l();
444}
445
446void AAudioServiceStreamBase::disconnect_l() {
447 if (getState() != AAUDIO_STREAM_STATE_DISCONNECTED
448 && getState() != AAUDIO_STREAM_STATE_CLOSED) {
449
Phil Burka9876702020-04-20 18:16:15 -0700450 mediametrics::LogItem(mMetricsId)
451 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
452 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
453 .record();
Phil Burk7ebbc112020-05-13 15:55:17 -0700454
Phil Burk5ef003b2017-06-30 11:43:37 -0700455 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkbcc36742017-08-31 17:24:51 -0700456 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
Phil Burk5ef003b2017-06-30 11:43:37 -0700457 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800458}
459
Phil Burk7ebbc112020-05-13 15:55:17 -0700460aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId,
461 int priority) {
462 std::lock_guard<std::mutex> lock(mLock);
463 aaudio_result_t result = AAUDIO_OK;
464 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
465 ALOGE("AAudioService::registerAudioThread(), thread already registered");
466 result = AAUDIO_ERROR_INVALID_STATE;
467 } else {
468 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
469 setRegisteredThread(clientThreadId);
470 int err = android::requestPriority(ownerPid, clientThreadId,
471 priority, true /* isForApp */);
472 if (err != 0) {
473 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
474 clientThreadId, errno, priority);
475 result = AAUDIO_ERROR_INTERNAL;
476 }
477 }
478 return result;
479}
480
481aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
482 std::lock_guard<std::mutex> lock(mLock);
483 aaudio_result_t result = AAUDIO_OK;
484 if (getRegisteredThread() != clientThreadId) {
485 ALOGE("%s(), wrong thread", __func__);
486 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
487 } else {
488 setRegisteredThread(0);
489 }
490 return result;
491}
492
493void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
494 // CLOSED is a final state.
495 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
496 mState = state;
497 } else {
498 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
499 }
500}
501
Phil Burkc0c70e32017-02-09 13:18:38 -0800502aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800503 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800504 AAudioServiceMessage command;
505 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800506 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800507 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800508 return writeUpMessageQueue(&command);
509}
510
511aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
512 int64_t dataLong) {
513 AAudioServiceMessage command;
514 command.what = AAudioServiceMessage::code::EVENT;
515 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800516 command.event.dataLong = dataLong;
517 return writeUpMessageQueue(&command);
518}
519
Phil Burkf878a8d2019-03-29 17:23:00 -0700520bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
521 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
522 if (mUpMessageQueue == nullptr) {
523 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
524 return true;
525 }
Phil Burkf878a8d2019-03-29 17:23:00 -0700526 // Is it half full or more
Phil Burk8f4fe502020-07-15 23:54:50 +0000527 return mUpMessageQueue->getFractionalFullness() >= 0.5;
Phil Burkf878a8d2019-03-29 17:23:00 -0700528}
529
Phil Burkc0c70e32017-02-09 13:18:38 -0800530aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700531 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700532 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700533 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700534 return AAUDIO_ERROR_NULL;
535 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800536 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
537 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800538 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
539 __func__, command->what, getTypeText());
540 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800541 return AAUDIO_ERROR_WOULD_BLOCK;
542 } else {
543 return AAUDIO_OK;
544 }
545}
546
Phil Burk23296382017-11-20 15:45:11 -0800547aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
548 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
549}
550
Phil Burkc0c70e32017-02-09 13:18:38 -0800551aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
552 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700553 // It is not worth filling up the queue with timestamps.
554 // That can cause the stream to get suspended.
555 // So just drop the timestamp if the queue is getting full.
556 if (isUpMessageQueueBusy()) {
557 return AAUDIO_OK;
558 }
559
Phil Burk97350f92017-07-21 15:59:44 -0700560 // Send a timestamp for the clock model.
Phil Burkc0c70e32017-02-09 13:18:38 -0800561 aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
562 &command.timestamp.timestamp);
563 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700564 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700565 (long long) command.timestamp.position,
566 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700567 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800568 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700569
570 if (result == AAUDIO_OK) {
571 // Send a hardware timestamp for presentation time.
572 result = getHardwareTimestamp(&command.timestamp.position,
573 &command.timestamp.timestamp);
574 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700575 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700576 (long long) command.timestamp.position,
577 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700578 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
579 result = writeUpMessageQueue(&command);
580 }
581 }
582 }
583
Phil Burkbcc36742017-08-31 17:24:51 -0700584 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700585 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800586 }
587 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800588}
589
Phil Burkc0c70e32017-02-09 13:18:38 -0800590/**
591 * Get an immutable description of the in-memory queues
592 * used to communicate with the underlying HAL or Service.
593 */
594aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700595 std::lock_guard<std::mutex> lock(mLock);
Phil Burk523b3042017-09-13 13:03:08 -0700596 {
597 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
598 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700599 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700600 return AAUDIO_ERROR_NULL;
601 }
602 // Gather information on the message queue.
603 mUpMessageQueue->fillParcelable(parcelable,
604 parcelable.mUpMessageQueueParcelable);
605 }
606 return getAudioDataDescription(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700607}
Phil Burk39f02dd2017-08-04 09:13:31 -0700608
609void AAudioServiceStreamBase::onVolumeChanged(float volume) {
610 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
611}