blob: 34ddd4d3b77c8b8adc60a06f2fbbde6c8ea25eac [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() {
Phil Burkbbd52862018-04-13 11:37:42 -070076 return std::string(" T Handle UId Port Run State Format Burst Chan Capacity");
Phil Burka5222e22017-07-28 13:31:14 -070077}
78
Phil Burk4501b352017-06-29 18:12:36 -070079std::string AAudioServiceStreamBase::dump() const {
80 std::stringstream result;
81
Phil Burka5222e22017-07-28 13:31:14 -070082 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
83 << std::dec << std::setfill(' ') ;
Svet Ganov33761132021-05-13 22:51:08 +000084 result << std::setw(6) << mMmapClient.attributionSource.uid;
Phil Burkbbd52862018-04-13 11:37:42 -070085 result << std::setw(7) << mClientHandle;
Phil Burka5222e22017-07-28 13:31:14 -070086 result << std::setw(4) << (isRunning() ? "yes" : " no");
Phil Burkbcc36742017-08-31 17:24:51 -070087 result << std::setw(6) << getState();
Phil Burk39f02dd2017-08-04 09:13:31 -070088 result << std::setw(7) << getFormat();
Phil Burka5222e22017-07-28 13:31:14 -070089 result << std::setw(6) << mFramesPerBurst;
Phil Burk39f02dd2017-08-04 09:13:31 -070090 result << std::setw(5) << getSamplesPerFrame();
91 result << std::setw(9) << getBufferCapacity();
Phil Burk4501b352017-06-29 18:12:36 -070092
93 return result.str();
94}
95
Phil Burka9876702020-04-20 18:16:15 -070096void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
97 // This is the first log sent from the AAudio Service for a stream.
98 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
99 + std::to_string(streamHandle);
100
101 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
102
103 // Once this item is logged by the server, the client with the same PID, UID
104 // can also log properties.
105 mediametrics::LogItem(mMetricsId)
106 .setPid(getOwnerProcessId())
107 .setUid(getOwnerUserId())
Andy Hungd203eb62020-04-27 09:12:46 -0700108 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
Phil Burka9876702020-04-20 18:16:15 -0700109 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
110 // the following are immutable
111 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
112 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
113 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
114 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
115 .set(AMEDIAMETRICS_PROP_DIRECTION,
116 AudioGlobal_convertDirectionToText(getDirection()))
117 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
118 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
119 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
120 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
121 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
122 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
123 .record();
124}
125
Phil Burk15f97c92018-09-04 14:06:27 -0700126aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700127 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
128 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700129
Svet Ganov33761132021-05-13 22:51:08 +0000130 mMmapClient.attributionSource = request.getAttributionSource();
131 // TODO b/182392769: use attribution source util
132 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700133 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000134 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700135 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Eric Laurentcb4dae22017-07-01 19:39:32 -0700136
Phil Burk39f02dd2017-08-04 09:13:31 -0700137 // Limit scope of lock to avoid recursive lock in close().
138 {
139 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
140 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700141 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700142 return AAUDIO_ERROR_INVALID_STATE;
143 }
144
Phil Burk8f4fe502020-07-15 23:54:50 +0000145 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700146 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
147 QUEUE_UP_CAPACITY_COMMANDS);
148 if (result != AAUDIO_OK) {
149 goto error;
150 }
151
Phil Burk6e2770e2018-05-01 13:03:52 -0700152 // This is not protected by a lock because the stream cannot be
153 // referenced until the service returns a handle to the client.
154 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700155 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700156 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700157 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700158 result = AAUDIO_ERROR_UNAVAILABLE;
159 goto error;
160 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700161 // Save a weak pointer that we will use to access the endpoint.
162 mServiceEndpointWeak = mServiceEndpoint;
163
Phil Burk39f02dd2017-08-04 09:13:31 -0700164 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
165 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800166 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700167 return result;
168
169error:
170 close();
171 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800172}
Phil Burkdec33ab2017-01-17 14:48:16 -0800173
Phil Burkc0c70e32017-02-09 13:18:38 -0800174aaudio_result_t AAudioServiceStreamBase::close() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700175 std::lock_guard<std::mutex> lock(mLock);
176 return close_l();
177}
178
179aaudio_result_t AAudioServiceStreamBase::close_l() {
Phil Burkbcc36742017-08-31 17:24:51 -0700180 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700181 return AAUDIO_OK;
182 }
183
Phil Burk8f4fe502020-07-15 23:54:50 +0000184 // This will call stopTimestampThread() and also stop the stream,
185 // just in case it was not already stopped.
Phil Burk7ebbc112020-05-13 15:55:17 -0700186 stop_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700187
Phil Burk8b4e05e2019-12-17 12:12:09 -0800188 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700189 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
190 if (endpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700191 result = AAUDIO_ERROR_INVALID_STATE;
192 } else {
Phil Burk6e2770e2018-05-01 13:03:52 -0700193 endpoint->unregisterStream(this);
194 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
195 endpointManager.closeEndpoint(endpoint);
196
197 // AAudioService::closeStream() prevents two threads from closing at the same time.
Phil Burk7ebbc112020-05-13 15:55:17 -0700198 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
Phil Burk39f02dd2017-08-04 09:13:31 -0700199 }
200
Phil Burkbcc36742017-08-31 17:24:51 -0700201 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burka9876702020-04-20 18:16:15 -0700202
203 mediametrics::LogItem(mMetricsId)
204 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
205 .record();
Phil Burk39f02dd2017-08-04 09:13:31 -0700206 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800207}
208
Phil Burkbcc36742017-08-31 17:24:51 -0700209aaudio_result_t AAudioServiceStreamBase::startDevice() {
210 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700211 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
212 if (endpoint == nullptr) {
213 ALOGE("%s() has no endpoint", __func__);
214 return AAUDIO_ERROR_INVALID_STATE;
215 }
216 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700217}
218
Phil Burk39f02dd2017-08-04 09:13:31 -0700219/**
220 * Start the flow of audio data.
221 *
222 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
223 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800224aaudio_result_t AAudioServiceStreamBase::start() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700225 std::lock_guard<std::mutex> lock(mLock);
226
Phil Burka9876702020-04-20 18:16:15 -0700227 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700228 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700229
Phil Burk7ebbc112020-05-13 15:55:17 -0700230 if (auto state = getState();
Phil Burkdb466142021-04-16 16:50:00 +0000231 state == AAUDIO_STREAM_STATE_CLOSED || isDisconnected_l()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700232 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
233 __func__, getHandle());
234 return AAUDIO_ERROR_INVALID_STATE;
235 }
236
Phil Burka9876702020-04-20 18:16:15 -0700237 mediametrics::Defer defer([&] {
238 mediametrics::LogItem(mMetricsId)
239 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700240 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700241 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
242 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
243 .record(); });
244
Eric Laurentcb4dae22017-07-01 19:39:32 -0700245 if (isRunning()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700246 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700247 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700248
Phil Burk23296382017-11-20 15:45:11 -0800249 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800250 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800251
Phil Burkbcc36742017-08-31 17:24:51 -0700252 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700253 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700254
Phil Burk39f02dd2017-08-04 09:13:31 -0700255 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700256 result = startDevice();
257 if (result != AAUDIO_OK) goto error;
258
259 // This should happen at the end of the start.
260 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
261 setState(AAUDIO_STREAM_STATE_STARTED);
262 mThreadEnabled.store(true);
Phil Burk3d201942021-04-08 23:27:04 +0000263 // Make sure this object does not get deleted before the run() method
264 // can protect it by making a strong pointer.
265 incStrong(nullptr); // See run() method.
Phil Burkbcc36742017-08-31 17:24:51 -0700266 result = mTimestampThread.start(this);
Phil Burk3d201942021-04-08 23:27:04 +0000267 if (result != AAUDIO_OK) {
268 decStrong(nullptr); // run() can't do it so we have to do it here.
269 goto error;
270 }
Phil Burkbcc36742017-08-31 17:24:51 -0700271
272 return result;
273
274error:
Phil Burk7ebbc112020-05-13 15:55:17 -0700275 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700276 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800277}
278
279aaudio_result_t AAudioServiceStreamBase::pause() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700280 std::lock_guard<std::mutex> lock(mLock);
281 return pause_l();
282}
283
284aaudio_result_t AAudioServiceStreamBase::pause_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700285 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700286 if (!isRunning()) {
287 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800288 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700289 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk73af62a2017-10-26 12:11:47 -0700290
Phil Burka9876702020-04-20 18:16:15 -0700291 mediametrics::Defer defer([&] {
292 mediametrics::LogItem(mMetricsId)
293 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700294 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700295 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
296 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
297 .record(); });
298
Phil Burk73af62a2017-10-26 12:11:47 -0700299 result = stopTimestampThread();
300 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700301 disconnect_l();
Phil Burk73af62a2017-10-26 12:11:47 -0700302 return result;
303 }
304
Phil Burk6e2770e2018-05-01 13:03:52 -0700305 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
306 if (endpoint == nullptr) {
307 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700308 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
309 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700310 }
311 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700312 if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700313 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700314 disconnect_l(); // TODO should we return or pause Base first?
Phil Burk39f02dd2017-08-04 09:13:31 -0700315 }
316
Eric Laurentcb4dae22017-07-01 19:39:32 -0700317 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
Phil Burkbcc36742017-08-31 17:24:51 -0700318 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burkc0c70e32017-02-09 13:18:38 -0800319 return result;
320}
321
Phil Burk71f35bb2017-04-13 16:05:07 -0700322aaudio_result_t AAudioServiceStreamBase::stop() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700323 std::lock_guard<std::mutex> lock(mLock);
324 return stop_l();
325}
326
327aaudio_result_t AAudioServiceStreamBase::stop_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700328 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700329 if (!isRunning()) {
330 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700331 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700332 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk39f02dd2017-08-04 09:13:31 -0700333
Phil Burka9876702020-04-20 18:16:15 -0700334 mediametrics::Defer defer([&] {
335 mediametrics::LogItem(mMetricsId)
336 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700337 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700338 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
339 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
340 .record(); });
341
Phil Burk83fb8442017-10-05 16:55:17 -0700342 setState(AAUDIO_STREAM_STATE_STOPPING);
343
Phil Burkd50ae622021-04-15 23:40:25 +0000344 // Temporarily unlock because we are joining the timestamp thread and it may try
345 // to acquire mLock.
346 mLock.unlock();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700347 result = stopTimestampThread();
Phil Burkd50ae622021-04-15 23:40:25 +0000348 mLock.lock();
349
Eric Laurentcb4dae22017-07-01 19:39:32 -0700350 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700351 disconnect_l();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700352 return result;
353 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700354
Phil Burk6e2770e2018-05-01 13:03:52 -0700355 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
356 if (endpoint == nullptr) {
357 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700358 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
359 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700360 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700361 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700362 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700363 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700364 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700365 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700366 // TODO what to do with result here?
367 }
368
Eric Laurentcb4dae22017-07-01 19:39:32 -0700369 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700370 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700371 return result;
372}
373
Phil Burk98d6d922017-07-06 11:52:45 -0700374aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
375 aaudio_result_t result = AAUDIO_OK;
376 // clear flag that tells thread to loop
377 if (mThreadEnabled.exchange(false)) {
Phil Burkbcc36742017-08-31 17:24:51 -0700378 result = mTimestampThread.stop();
Phil Burk98d6d922017-07-06 11:52:45 -0700379 }
380 return result;
381}
382
Phil Burk71f35bb2017-04-13 16:05:07 -0700383aaudio_result_t AAudioServiceStreamBase::flush() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700384 std::lock_guard<std::mutex> lock(mLock);
Phil Burk5cc83c32017-11-28 15:43:18 -0800385 aaudio_result_t result = AAudio_isFlushAllowed(getState());
386 if (result != AAUDIO_OK) {
387 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700388 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700389 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800390
Phil Burka9876702020-04-20 18:16:15 -0700391 mediametrics::Defer defer([&] {
392 mediametrics::LogItem(mMetricsId)
393 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700394 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700395 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
396 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
397 .record(); });
398
Phil Burk39f02dd2017-08-04 09:13:31 -0700399 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700400 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700401 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700402 return AAUDIO_OK;
403}
404
Phil Burkcf5f6d22017-05-26 12:35:07 -0700405// implement Runnable, periodically send timestamps to client
Phil Burka53ffa62018-10-10 16:21:37 -0700406__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800407void AAudioServiceStreamBase::run() {
Phil Burk19e990e2018-03-22 13:59:34 -0700408 ALOGD("%s() %s entering >>>>>>>>>>>>>> TIMESTAMPS", __func__, getTypeText());
Phil Burk3d201942021-04-08 23:27:04 +0000409 // Hold onto the ref counted stream until the end.
410 android::sp<AAudioServiceStreamBase> holdStream(this);
Phil Burkc0c70e32017-02-09 13:18:38 -0800411 TimestampScheduler timestampScheduler;
Phil Burk3d201942021-04-08 23:27:04 +0000412 // Balance the incStrong from when the thread was launched.
413 holdStream->decStrong(nullptr);
414
Phil Burk39f02dd2017-08-04 09:13:31 -0700415 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
Phil Burkc0c70e32017-02-09 13:18:38 -0800416 timestampScheduler.start(AudioClock::getNanoseconds());
417 int64_t nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burka53ffa62018-10-10 16:21:37 -0700418 int32_t loopCount = 0;
Phil Burk45da1b72021-04-07 06:30:50 +0000419 aaudio_result_t result = AAUDIO_OK;
Phil Burkc0c70e32017-02-09 13:18:38 -0800420 while(mThreadEnabled.load()) {
Phil Burka53ffa62018-10-10 16:21:37 -0700421 loopCount++;
Phil Burkc0c70e32017-02-09 13:18:38 -0800422 if (AudioClock::getNanoseconds() >= nextTime) {
Phil Burk45da1b72021-04-07 06:30:50 +0000423 result = sendCurrentTimestamp();
Phil Burkc0c70e32017-02-09 13:18:38 -0800424 if (result != AAUDIO_OK) {
Phil Burka53ffa62018-10-10 16:21:37 -0700425 ALOGE("%s() timestamp thread got result = %d", __func__, result);
Phil Burkc0c70e32017-02-09 13:18:38 -0800426 break;
427 }
428 nextTime = timestampScheduler.nextAbsoluteTime();
429 } else {
430 // Sleep until it is time to send the next timestamp.
Phil Burk98d6d922017-07-06 11:52:45 -0700431 // TODO Wait for a signal with a timeout so that we can stop more quickly.
Phil Burkc0c70e32017-02-09 13:18:38 -0800432 AudioClock::sleepUntilNanoTime(nextTime);
433 }
434 }
Phil Burk45da1b72021-04-07 06:30:50 +0000435 // This was moved from the calls in stop_l() and pause_l(), which could cause a deadlock
436 // if it resulted in a call to disconnect.
437 if (result == AAUDIO_OK) {
438 (void) sendCurrentTimestamp();
439 }
Phil Burka53ffa62018-10-10 16:21:37 -0700440 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< TIMESTAMPS",
441 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800442}
443
Phil Burk5ef003b2017-06-30 11:43:37 -0700444void AAudioServiceStreamBase::disconnect() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700445 std::lock_guard<std::mutex> lock(mLock);
446 disconnect_l();
447}
448
449void AAudioServiceStreamBase::disconnect_l() {
Phil Burkdb466142021-04-16 16:50:00 +0000450 if (!isDisconnected_l() && getState() != AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700451
Phil Burka9876702020-04-20 18:16:15 -0700452 mediametrics::LogItem(mMetricsId)
453 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
454 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
455 .record();
Phil Burk7ebbc112020-05-13 15:55:17 -0700456
Phil Burk5ef003b2017-06-30 11:43:37 -0700457 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkdb466142021-04-16 16:50:00 +0000458 setDisconnected_l(true);
Phil Burk5ef003b2017-06-30 11:43:37 -0700459 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800460}
461
Phil Burk7ebbc112020-05-13 15:55:17 -0700462aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId,
463 int priority) {
464 std::lock_guard<std::mutex> lock(mLock);
465 aaudio_result_t result = AAUDIO_OK;
466 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
467 ALOGE("AAudioService::registerAudioThread(), thread already registered");
468 result = AAUDIO_ERROR_INVALID_STATE;
469 } else {
470 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
471 setRegisteredThread(clientThreadId);
472 int err = android::requestPriority(ownerPid, clientThreadId,
473 priority, true /* isForApp */);
474 if (err != 0) {
475 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
476 clientThreadId, errno, priority);
477 result = AAUDIO_ERROR_INTERNAL;
478 }
479 }
480 return result;
481}
482
483aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
484 std::lock_guard<std::mutex> lock(mLock);
485 aaudio_result_t result = AAUDIO_OK;
486 if (getRegisteredThread() != clientThreadId) {
487 ALOGE("%s(), wrong thread", __func__);
488 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
489 } else {
490 setRegisteredThread(0);
491 }
492 return result;
493}
494
495void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
496 // CLOSED is a final state.
497 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
498 mState = state;
499 } else {
500 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
501 }
502}
503
Phil Burkc0c70e32017-02-09 13:18:38 -0800504aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800505 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800506 AAudioServiceMessage command;
507 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800508 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800509 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800510 return writeUpMessageQueue(&command);
511}
512
513aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
514 int64_t dataLong) {
515 AAudioServiceMessage command;
516 command.what = AAudioServiceMessage::code::EVENT;
517 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800518 command.event.dataLong = dataLong;
519 return writeUpMessageQueue(&command);
520}
521
Phil Burkf878a8d2019-03-29 17:23:00 -0700522bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
523 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
524 if (mUpMessageQueue == nullptr) {
525 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
526 return true;
527 }
Phil Burkf878a8d2019-03-29 17:23:00 -0700528 // Is it half full or more
Phil Burk8f4fe502020-07-15 23:54:50 +0000529 return mUpMessageQueue->getFractionalFullness() >= 0.5;
Phil Burkf878a8d2019-03-29 17:23:00 -0700530}
531
Phil Burkc0c70e32017-02-09 13:18:38 -0800532aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700533 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700534 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700535 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700536 return AAUDIO_ERROR_NULL;
537 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800538 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
539 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800540 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
541 __func__, command->what, getTypeText());
542 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800543 return AAUDIO_ERROR_WOULD_BLOCK;
544 } else {
545 return AAUDIO_OK;
546 }
547}
548
Phil Burk23296382017-11-20 15:45:11 -0800549aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
550 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
551}
552
Phil Burkc0c70e32017-02-09 13:18:38 -0800553aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
554 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700555 // It is not worth filling up the queue with timestamps.
556 // That can cause the stream to get suspended.
557 // So just drop the timestamp if the queue is getting full.
558 if (isUpMessageQueueBusy()) {
559 return AAUDIO_OK;
560 }
561
Phil Burk97350f92017-07-21 15:59:44 -0700562 // Send a timestamp for the clock model.
Phil Burkc0c70e32017-02-09 13:18:38 -0800563 aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
564 &command.timestamp.timestamp);
565 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700566 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700567 (long long) command.timestamp.position,
568 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700569 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800570 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700571
572 if (result == AAUDIO_OK) {
573 // Send a hardware timestamp for presentation time.
574 result = getHardwareTimestamp(&command.timestamp.position,
575 &command.timestamp.timestamp);
576 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700577 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700578 (long long) command.timestamp.position,
579 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700580 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
581 result = writeUpMessageQueue(&command);
582 }
583 }
584 }
585
Phil Burkbcc36742017-08-31 17:24:51 -0700586 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700587 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800588 }
589 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800590}
591
Phil Burkc0c70e32017-02-09 13:18:38 -0800592/**
593 * Get an immutable description of the in-memory queues
594 * used to communicate with the underlying HAL or Service.
595 */
596aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700597 std::lock_guard<std::mutex> lock(mLock);
Phil Burk523b3042017-09-13 13:03:08 -0700598 {
599 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
600 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700601 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700602 return AAUDIO_ERROR_NULL;
603 }
604 // Gather information on the message queue.
605 mUpMessageQueue->fillParcelable(parcelable,
606 parcelable.mUpMessageQueueParcelable);
607 }
608 return getAudioDataDescription(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700609}
Phil Burk39f02dd2017-08-04 09:13:31 -0700610
611void AAudioServiceStreamBase::onVolumeChanged(float volume) {
612 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
613}