blob: ea691cf99e8b628426ce6baf8f14e808471b7f99 [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/IAAudioService.h"
30#include "binding/AAudioServiceMessage.h"
Phil Burka9876702020-04-20 18:16:15 -070031#include "core/AudioGlobal.h"
Phil Burkc0c70e32017-02-09 13:18:38 -080032#include "utility/AudioClock.h"
33
Phil Burk39f02dd2017-08-04 09:13:31 -070034#include "AAudioEndpointManager.h"
35#include "AAudioService.h"
36#include "AAudioServiceEndpoint.h"
Phil Burkc0c70e32017-02-09 13:18:38 -080037#include "AAudioServiceStreamBase.h"
38#include "TimestampScheduler.h"
39
40using namespace android; // TODO just import names needed
41using namespace aaudio; // TODO just import names needed
Phil Burk2355edb2016-12-26 13:54:02 -080042
43/**
Phil Burkc0c70e32017-02-09 13:18:38 -080044 * Base class for streams in the service.
45 * @return
Phil Burk2355edb2016-12-26 13:54:02 -080046 */
47
Phil Burk39f02dd2017-08-04 09:13:31 -070048AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
Phil Burk8f4fe502020-07-15 23:54:50 +000049 : mTimestampThread("AATime")
Phil Burka53ffa62018-10-10 16:21:37 -070050 , mAtomicStreamTimestamp()
Phil Burk39f02dd2017-08-04 09:13:31 -070051 , mAudioService(audioService) {
Eric Laurentcb4dae22017-07-01 19:39:32 -070052 mMmapClient.clientUid = -1;
53 mMmapClient.clientPid = -1;
54 mMmapClient.packageName = String16("");
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
71 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED
72 || getState() == AAUDIO_STREAM_STATE_DISCONNECTED),
Phil Burk8b4e05e2019-12-17 12:12:09 -080073 "service stream %p still open, state = %d",
74 this, getState());
Phil Burk2355edb2016-12-26 13:54:02 -080075}
76
Phil Burka5222e22017-07-28 13:31:14 -070077std::string AAudioServiceStreamBase::dumpHeader() {
Phil Burkbbd52862018-04-13 11:37:42 -070078 return std::string(" T Handle UId Port Run State Format Burst Chan Capacity");
Phil Burka5222e22017-07-28 13:31:14 -070079}
80
Phil Burk4501b352017-06-29 18:12:36 -070081std::string AAudioServiceStreamBase::dump() const {
82 std::stringstream result;
83
Phil Burka5222e22017-07-28 13:31:14 -070084 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
85 << std::dec << std::setfill(' ') ;
86 result << std::setw(6) << mMmapClient.clientUid;
Phil Burkbbd52862018-04-13 11:37:42 -070087 result << std::setw(7) << mClientHandle;
Phil Burka5222e22017-07-28 13:31:14 -070088 result << std::setw(4) << (isRunning() ? "yes" : " no");
Phil Burkbcc36742017-08-31 17:24:51 -070089 result << std::setw(6) << getState();
Phil Burk39f02dd2017-08-04 09:13:31 -070090 result << std::setw(7) << getFormat();
Phil Burka5222e22017-07-28 13:31:14 -070091 result << std::setw(6) << mFramesPerBurst;
Phil Burk39f02dd2017-08-04 09:13:31 -070092 result << std::setw(5) << getSamplesPerFrame();
93 result << std::setw(9) << getBufferCapacity();
Phil Burk4501b352017-06-29 18:12:36 -070094
95 return result.str();
96}
97
Phil Burka9876702020-04-20 18:16:15 -070098void AAudioServiceStreamBase::logOpen(aaudio_handle_t streamHandle) {
99 // This is the first log sent from the AAudio Service for a stream.
100 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
101 + std::to_string(streamHandle);
102
103 audio_attributes_t attributes = AAudioServiceEndpoint::getAudioAttributesFrom(this);
104
105 // Once this item is logged by the server, the client with the same PID, UID
106 // can also log properties.
107 mediametrics::LogItem(mMetricsId)
108 .setPid(getOwnerProcessId())
109 .setUid(getOwnerUserId())
Andy Hungd203eb62020-04-27 09:12:46 -0700110 .set(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)getOwnerUserId())
Phil Burka9876702020-04-20 18:16:15 -0700111 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
112 // the following are immutable
113 .set(AMEDIAMETRICS_PROP_BUFFERCAPACITYFRAMES, (int32_t)getBufferCapacity())
114 .set(AMEDIAMETRICS_PROP_BURSTFRAMES, (int32_t)getFramesPerBurst())
115 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)getSamplesPerFrame())
116 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(attributes.content_type).c_str())
117 .set(AMEDIAMETRICS_PROP_DIRECTION,
118 AudioGlobal_convertDirectionToText(getDirection()))
119 .set(AMEDIAMETRICS_PROP_ENCODING, toString(getFormat()).c_str())
120 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)getDeviceId())
121 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)getSampleRate())
122 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)getSessionId())
123 .set(AMEDIAMETRICS_PROP_SOURCE, toString(attributes.source).c_str())
124 .set(AMEDIAMETRICS_PROP_USAGE, toString(attributes.usage).c_str())
125 .record();
126}
127
Phil Burk15f97c92018-09-04 14:06:27 -0700128aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700129 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
130 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700131
132 mMmapClient.clientUid = request.getUserId();
133 mMmapClient.clientPid = request.getProcessId();
Phil Burk39f02dd2017-08-04 09:13:31 -0700134 mMmapClient.packageName.setTo(String16("")); // TODO What should we do here?
Eric Laurentcb4dae22017-07-01 19:39:32 -0700135
Phil Burk39f02dd2017-08-04 09:13:31 -0700136 // Limit scope of lock to avoid recursive lock in close().
137 {
138 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
139 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700140 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700141 return AAUDIO_ERROR_INVALID_STATE;
142 }
143
Phil Burk8f4fe502020-07-15 23:54:50 +0000144 mUpMessageQueue = std::make_shared<SharedRingBuffer>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700145 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
146 QUEUE_UP_CAPACITY_COMMANDS);
147 if (result != AAUDIO_OK) {
148 goto error;
149 }
150
Phil Burk6e2770e2018-05-01 13:03:52 -0700151 // This is not protected by a lock because the stream cannot be
152 // referenced until the service returns a handle to the client.
153 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700154 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700155 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700156 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700157 result = AAUDIO_ERROR_UNAVAILABLE;
158 goto error;
159 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700160 // Save a weak pointer that we will use to access the endpoint.
161 mServiceEndpointWeak = mServiceEndpoint;
162
Phil Burk39f02dd2017-08-04 09:13:31 -0700163 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
164 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800165 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700166 return result;
167
168error:
169 close();
170 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800171}
Phil Burkdec33ab2017-01-17 14:48:16 -0800172
Phil Burkc0c70e32017-02-09 13:18:38 -0800173aaudio_result_t AAudioServiceStreamBase::close() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700174 std::lock_guard<std::mutex> lock(mLock);
175 return close_l();
176}
177
178aaudio_result_t AAudioServiceStreamBase::close_l() {
Phil Burkbcc36742017-08-31 17:24:51 -0700179 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700180 return AAUDIO_OK;
181 }
182
Phil Burk8f4fe502020-07-15 23:54:50 +0000183 // This will call stopTimestampThread() and also stop the stream,
184 // just in case it was not already stopped.
Phil Burk7ebbc112020-05-13 15:55:17 -0700185 stop_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700186
Phil Burk8b4e05e2019-12-17 12:12:09 -0800187 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700188 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
189 if (endpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700190 result = AAUDIO_ERROR_INVALID_STATE;
191 } else {
Phil Burk6e2770e2018-05-01 13:03:52 -0700192 endpoint->unregisterStream(this);
193 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
194 endpointManager.closeEndpoint(endpoint);
195
196 // AAudioService::closeStream() prevents two threads from closing at the same time.
Phil Burk7ebbc112020-05-13 15:55:17 -0700197 mServiceEndpoint.clear(); // endpoint will hold the pointer after this method returns.
Phil Burk39f02dd2017-08-04 09:13:31 -0700198 }
199
Phil Burkbcc36742017-08-31 17:24:51 -0700200 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burka9876702020-04-20 18:16:15 -0700201
202 mediametrics::LogItem(mMetricsId)
203 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
204 .record();
Phil Burk39f02dd2017-08-04 09:13:31 -0700205 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800206}
207
Phil Burkbcc36742017-08-31 17:24:51 -0700208aaudio_result_t AAudioServiceStreamBase::startDevice() {
209 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700210 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
211 if (endpoint == nullptr) {
212 ALOGE("%s() has no endpoint", __func__);
213 return AAUDIO_ERROR_INVALID_STATE;
214 }
215 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700216}
217
Phil Burk39f02dd2017-08-04 09:13:31 -0700218/**
219 * Start the flow of audio data.
220 *
221 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
222 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800223aaudio_result_t AAudioServiceStreamBase::start() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700224 std::lock_guard<std::mutex> lock(mLock);
225
Phil Burka9876702020-04-20 18:16:15 -0700226 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700227 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700228
Phil Burk7ebbc112020-05-13 15:55:17 -0700229 if (auto state = getState();
230 state == AAUDIO_STREAM_STATE_CLOSED || state == AAUDIO_STREAM_STATE_DISCONNECTED) {
231 ALOGW("%s() already CLOSED, returns INVALID_STATE, handle = %d",
232 __func__, getHandle());
233 return AAUDIO_ERROR_INVALID_STATE;
234 }
235
Phil Burka9876702020-04-20 18:16:15 -0700236 mediametrics::Defer defer([&] {
237 mediametrics::LogItem(mMetricsId)
238 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700239 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700240 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
241 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
242 .record(); });
243
Eric Laurentcb4dae22017-07-01 19:39:32 -0700244 if (isRunning()) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700245 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700246 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700247
Phil Burk23296382017-11-20 15:45:11 -0800248 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800249 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800250
Phil Burkbcc36742017-08-31 17:24:51 -0700251 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700252 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700253
Phil Burk39f02dd2017-08-04 09:13:31 -0700254 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700255 result = startDevice();
256 if (result != AAUDIO_OK) goto error;
257
258 // This should happen at the end of the start.
259 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
260 setState(AAUDIO_STREAM_STATE_STARTED);
261 mThreadEnabled.store(true);
262 result = mTimestampThread.start(this);
263 if (result != AAUDIO_OK) goto error;
264
265 return result;
266
267error:
Phil Burk7ebbc112020-05-13 15:55:17 -0700268 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700269 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800270}
271
272aaudio_result_t AAudioServiceStreamBase::pause() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700273 std::lock_guard<std::mutex> lock(mLock);
274 return pause_l();
275}
276
277aaudio_result_t AAudioServiceStreamBase::pause_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700278 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700279 if (!isRunning()) {
280 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800281 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700282 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk73af62a2017-10-26 12:11:47 -0700283
Phil Burka9876702020-04-20 18:16:15 -0700284 mediametrics::Defer defer([&] {
285 mediametrics::LogItem(mMetricsId)
286 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700287 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700288 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
289 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
290 .record(); });
291
Phil Burk73af62a2017-10-26 12:11:47 -0700292 // Send it now because the timestamp gets rounded up when stopStream() is called below.
293 // Also we don't need the timestamps while we are shutting down.
294 sendCurrentTimestamp();
295
296 result = stopTimestampThread();
297 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700298 disconnect_l();
Phil Burk73af62a2017-10-26 12:11:47 -0700299 return result;
300 }
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() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700320 std::lock_guard<std::mutex> lock(mLock);
321 return stop_l();
322}
323
324aaudio_result_t AAudioServiceStreamBase::stop_l() {
Phil Burk11e8d332017-05-24 09:59:02 -0700325 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700326 if (!isRunning()) {
327 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700328 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700329 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk39f02dd2017-08-04 09:13:31 -0700330
Phil Burka9876702020-04-20 18:16:15 -0700331 mediametrics::Defer defer([&] {
332 mediametrics::LogItem(mMetricsId)
333 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700334 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700335 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
336 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
337 .record(); });
338
Phil Burk83fb8442017-10-05 16:55:17 -0700339 setState(AAUDIO_STREAM_STATE_STOPPING);
340
Phil Burk73af62a2017-10-26 12:11:47 -0700341 // Send it now because the timestamp gets rounded up when stopStream() is called below.
342 // Also we don't need the timestamps while we are shutting down.
Eric Laurentcb4dae22017-07-01 19:39:32 -0700343 sendCurrentTimestamp(); // warning - this calls a virtual function
344 result = stopTimestampThread();
345 if (result != AAUDIO_OK) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700346 disconnect_l();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700347 return result;
348 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700349
Phil Burk6e2770e2018-05-01 13:03:52 -0700350 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
351 if (endpoint == nullptr) {
352 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700353 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
354 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700355 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700356 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700357 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700358 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700359 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk7ebbc112020-05-13 15:55:17 -0700360 disconnect_l();
Phil Burk39f02dd2017-08-04 09:13:31 -0700361 // TODO what to do with result here?
362 }
363
Eric Laurentcb4dae22017-07-01 19:39:32 -0700364 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700365 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700366 return result;
367}
368
Phil Burk98d6d922017-07-06 11:52:45 -0700369aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
370 aaudio_result_t result = AAUDIO_OK;
371 // clear flag that tells thread to loop
372 if (mThreadEnabled.exchange(false)) {
Phil Burkbcc36742017-08-31 17:24:51 -0700373 result = mTimestampThread.stop();
Phil Burk98d6d922017-07-06 11:52:45 -0700374 }
375 return result;
376}
377
Phil Burk71f35bb2017-04-13 16:05:07 -0700378aaudio_result_t AAudioServiceStreamBase::flush() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700379 std::lock_guard<std::mutex> lock(mLock);
Phil Burk5cc83c32017-11-28 15:43:18 -0800380 aaudio_result_t result = AAudio_isFlushAllowed(getState());
381 if (result != AAUDIO_OK) {
382 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700383 }
Phil Burk7ebbc112020-05-13 15:55:17 -0700384 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800385
Phil Burka9876702020-04-20 18:16:15 -0700386 mediametrics::Defer defer([&] {
387 mediametrics::LogItem(mMetricsId)
388 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700389 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
Phil Burka9876702020-04-20 18:16:15 -0700390 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
391 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
392 .record(); });
393
Phil Burk39f02dd2017-08-04 09:13:31 -0700394 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700395 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700396 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700397 return AAUDIO_OK;
398}
399
Phil Burkcf5f6d22017-05-26 12:35:07 -0700400// implement Runnable, periodically send timestamps to client
Phil Burka53ffa62018-10-10 16:21:37 -0700401__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800402void AAudioServiceStreamBase::run() {
Phil Burk19e990e2018-03-22 13:59:34 -0700403 ALOGD("%s() %s entering >>>>>>>>>>>>>> TIMESTAMPS", __func__, getTypeText());
Phil Burkc0c70e32017-02-09 13:18:38 -0800404 TimestampScheduler timestampScheduler;
Phil Burk39f02dd2017-08-04 09:13:31 -0700405 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
Phil Burkc0c70e32017-02-09 13:18:38 -0800406 timestampScheduler.start(AudioClock::getNanoseconds());
407 int64_t nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burka53ffa62018-10-10 16:21:37 -0700408 int32_t loopCount = 0;
Phil Burkc0c70e32017-02-09 13:18:38 -0800409 while(mThreadEnabled.load()) {
Phil Burka53ffa62018-10-10 16:21:37 -0700410 loopCount++;
Phil Burkc0c70e32017-02-09 13:18:38 -0800411 if (AudioClock::getNanoseconds() >= nextTime) {
412 aaudio_result_t result = sendCurrentTimestamp();
413 if (result != AAUDIO_OK) {
Phil Burka53ffa62018-10-10 16:21:37 -0700414 ALOGE("%s() timestamp thread got result = %d", __func__, result);
Phil Burkc0c70e32017-02-09 13:18:38 -0800415 break;
416 }
417 nextTime = timestampScheduler.nextAbsoluteTime();
418 } else {
419 // Sleep until it is time to send the next timestamp.
Phil Burk98d6d922017-07-06 11:52:45 -0700420 // TODO Wait for a signal with a timeout so that we can stop more quickly.
Phil Burkc0c70e32017-02-09 13:18:38 -0800421 AudioClock::sleepUntilNanoTime(nextTime);
422 }
423 }
Phil Burka53ffa62018-10-10 16:21:37 -0700424 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< TIMESTAMPS",
425 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800426}
427
Phil Burk5ef003b2017-06-30 11:43:37 -0700428void AAudioServiceStreamBase::disconnect() {
Phil Burk7ebbc112020-05-13 15:55:17 -0700429 std::lock_guard<std::mutex> lock(mLock);
430 disconnect_l();
431}
432
433void AAudioServiceStreamBase::disconnect_l() {
434 if (getState() != AAUDIO_STREAM_STATE_DISCONNECTED
435 && getState() != AAUDIO_STREAM_STATE_CLOSED) {
436
Phil Burka9876702020-04-20 18:16:15 -0700437 mediametrics::LogItem(mMetricsId)
438 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
439 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
440 .record();
Phil Burk7ebbc112020-05-13 15:55:17 -0700441
Phil Burk5ef003b2017-06-30 11:43:37 -0700442 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkbcc36742017-08-31 17:24:51 -0700443 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
Phil Burk5ef003b2017-06-30 11:43:37 -0700444 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800445}
446
Phil Burk7ebbc112020-05-13 15:55:17 -0700447aaudio_result_t AAudioServiceStreamBase::registerAudioThread(pid_t clientThreadId,
448 int priority) {
449 std::lock_guard<std::mutex> lock(mLock);
450 aaudio_result_t result = AAUDIO_OK;
451 if (getRegisteredThread() != AAudioServiceStreamBase::ILLEGAL_THREAD_ID) {
452 ALOGE("AAudioService::registerAudioThread(), thread already registered");
453 result = AAUDIO_ERROR_INVALID_STATE;
454 } else {
455 const pid_t ownerPid = IPCThreadState::self()->getCallingPid(); // TODO review
456 setRegisteredThread(clientThreadId);
457 int err = android::requestPriority(ownerPid, clientThreadId,
458 priority, true /* isForApp */);
459 if (err != 0) {
460 ALOGE("AAudioService::registerAudioThread(%d) failed, errno = %d, priority = %d",
461 clientThreadId, errno, priority);
462 result = AAUDIO_ERROR_INTERNAL;
463 }
464 }
465 return result;
466}
467
468aaudio_result_t AAudioServiceStreamBase::unregisterAudioThread(pid_t clientThreadId) {
469 std::lock_guard<std::mutex> lock(mLock);
470 aaudio_result_t result = AAUDIO_OK;
471 if (getRegisteredThread() != clientThreadId) {
472 ALOGE("%s(), wrong thread", __func__);
473 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
474 } else {
475 setRegisteredThread(0);
476 }
477 return result;
478}
479
480void AAudioServiceStreamBase::setState(aaudio_stream_state_t state) {
481 // CLOSED is a final state.
482 if (mState != AAUDIO_STREAM_STATE_CLOSED) {
483 mState = state;
484 } else {
485 ALOGW_IF(mState != state, "%s(%d) when already CLOSED", __func__, state);
486 }
487}
488
Phil Burkc0c70e32017-02-09 13:18:38 -0800489aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800490 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800491 AAudioServiceMessage command;
492 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800493 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800494 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800495 return writeUpMessageQueue(&command);
496}
497
498aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
499 int64_t dataLong) {
500 AAudioServiceMessage command;
501 command.what = AAudioServiceMessage::code::EVENT;
502 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800503 command.event.dataLong = dataLong;
504 return writeUpMessageQueue(&command);
505}
506
Phil Burkf878a8d2019-03-29 17:23:00 -0700507bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
508 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
509 if (mUpMessageQueue == nullptr) {
510 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
511 return true;
512 }
Phil Burkf878a8d2019-03-29 17:23:00 -0700513 // Is it half full or more
Phil Burk8f4fe502020-07-15 23:54:50 +0000514 return mUpMessageQueue->getFractionalFullness() >= 0.5;
Phil Burkf878a8d2019-03-29 17:23:00 -0700515}
516
Phil Burkc0c70e32017-02-09 13:18:38 -0800517aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700518 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700519 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700520 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700521 return AAUDIO_ERROR_NULL;
522 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800523 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
524 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800525 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
526 __func__, command->what, getTypeText());
527 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800528 return AAUDIO_ERROR_WOULD_BLOCK;
529 } else {
530 return AAUDIO_OK;
531 }
532}
533
Phil Burk23296382017-11-20 15:45:11 -0800534aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
535 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
536}
537
Phil Burkc0c70e32017-02-09 13:18:38 -0800538aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
539 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700540 // It is not worth filling up the queue with timestamps.
541 // That can cause the stream to get suspended.
542 // So just drop the timestamp if the queue is getting full.
543 if (isUpMessageQueueBusy()) {
544 return AAUDIO_OK;
545 }
546
Phil Burk97350f92017-07-21 15:59:44 -0700547 // Send a timestamp for the clock model.
Phil Burkc0c70e32017-02-09 13:18:38 -0800548 aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
549 &command.timestamp.timestamp);
550 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700551 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700552 (long long) command.timestamp.position,
553 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700554 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800555 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700556
557 if (result == AAUDIO_OK) {
558 // Send a hardware timestamp for presentation time.
559 result = getHardwareTimestamp(&command.timestamp.position,
560 &command.timestamp.timestamp);
561 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700562 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700563 (long long) command.timestamp.position,
564 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700565 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
566 result = writeUpMessageQueue(&command);
567 }
568 }
569 }
570
Phil Burkbcc36742017-08-31 17:24:51 -0700571 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700572 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800573 }
574 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800575}
576
Phil Burkc0c70e32017-02-09 13:18:38 -0800577/**
578 * Get an immutable description of the in-memory queues
579 * used to communicate with the underlying HAL or Service.
580 */
581aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
Phil Burk7ebbc112020-05-13 15:55:17 -0700582 std::lock_guard<std::mutex> lock(mLock);
Phil Burk523b3042017-09-13 13:03:08 -0700583 {
584 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
585 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700586 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700587 return AAUDIO_ERROR_NULL;
588 }
589 // Gather information on the message queue.
590 mUpMessageQueue->fillParcelable(parcelable,
591 parcelable.mUpMessageQueueParcelable);
592 }
593 return getAudioDataDescription(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700594}
Phil Burk39f02dd2017-08-04 09:13:31 -0700595
596void AAudioServiceStreamBase::onVolumeChanged(float volume) {
597 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
598}
Phil Burk94862522017-09-13 21:31:36 -0700599
Phil Burk2fe718b2018-05-14 12:28:32 -0700600int32_t AAudioServiceStreamBase::incrementServiceReferenceCount_l() {
Phil Burk94862522017-09-13 21:31:36 -0700601 return ++mCallingCount;
602}
603
Phil Burk2fe718b2018-05-14 12:28:32 -0700604int32_t AAudioServiceStreamBase::decrementServiceReferenceCount_l() {
605 int32_t count = --mCallingCount;
606 // Each call to increment should be balanced with one call to decrement.
607 assert(count >= 0);
608 return count;
Phil Burk94862522017-09-13 21:31:36 -0700609}