blob: dba9fb9fee6f910d7504f4486afd72bc97d62567 [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>
27
Phil Burkc0c70e32017-02-09 13:18:38 -080028#include "binding/IAAudioService.h"
29#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
42/**
Phil Burkc0c70e32017-02-09 13:18:38 -080043 * Base class for streams in the service.
44 * @return
Phil Burk2355edb2016-12-26 13:54:02 -080045 */
46
Phil Burk39f02dd2017-08-04 09:13:31 -070047AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
Phil Burk2355edb2016-12-26 13:54:02 -080048 : mUpMessageQueue(nullptr)
Phil Burk55978892018-01-11 14:56:09 -080049 , 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 Burka9876702020-04-20 18:16:15 -070058 // May not be set if open failed.
59 if (mMetricsId.size() > 0) {
60 mediametrics::LogItem(mMetricsId)
61 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
62 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
63 .record();
64 }
65
Phil Burk5a26e662017-07-07 12:44:48 -070066 // If the stream is deleted when OPEN or in use then audio resources will leak.
67 // This would indicate an internal error. So we want to find this ASAP.
Phil Burkbcc36742017-08-31 17:24:51 -070068 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
69 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED
70 || getState() == AAUDIO_STREAM_STATE_DISCONNECTED),
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(' ') ;
84 result << std::setw(6) << mMmapClient.clientUid;
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
130 mMmapClient.clientUid = request.getUserId();
131 mMmapClient.clientPid = request.getProcessId();
Phil Burk39f02dd2017-08-04 09:13:31 -0700132 mMmapClient.packageName.setTo(String16("")); // TODO What should we do here?
Eric Laurentcb4dae22017-07-01 19:39:32 -0700133
Phil Burk39f02dd2017-08-04 09:13:31 -0700134 // Limit scope of lock to avoid recursive lock in close().
135 {
136 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
137 if (mUpMessageQueue != nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700138 ALOGE("%s() called twice", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700139 return AAUDIO_ERROR_INVALID_STATE;
140 }
141
Phil Burkc0c70e32017-02-09 13:18:38 -0800142 mUpMessageQueue = new SharedRingBuffer();
Phil Burk39f02dd2017-08-04 09:13:31 -0700143 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
144 QUEUE_UP_CAPACITY_COMMANDS);
145 if (result != AAUDIO_OK) {
146 goto error;
147 }
148
Phil Burk6e2770e2018-05-01 13:03:52 -0700149 // This is not protected by a lock because the stream cannot be
150 // referenced until the service returns a handle to the client.
151 // So only one thread can open a stream.
Phil Burk39f02dd2017-08-04 09:13:31 -0700152 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
Phil Burk15f97c92018-09-04 14:06:27 -0700153 request);
Phil Burk39f02dd2017-08-04 09:13:31 -0700154 if (mServiceEndpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700155 result = AAUDIO_ERROR_UNAVAILABLE;
156 goto error;
157 }
Phil Burk6e2770e2018-05-01 13:03:52 -0700158 // Save a weak pointer that we will use to access the endpoint.
159 mServiceEndpointWeak = mServiceEndpoint;
160
Phil Burk39f02dd2017-08-04 09:13:31 -0700161 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
162 copyFrom(*mServiceEndpoint);
Phil Burkc0c70e32017-02-09 13:18:38 -0800163 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700164 return result;
165
166error:
167 close();
168 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800169}
Phil Burkdec33ab2017-01-17 14:48:16 -0800170
Phil Burkc0c70e32017-02-09 13:18:38 -0800171aaudio_result_t AAudioServiceStreamBase::close() {
Phil Burkbcc36742017-08-31 17:24:51 -0700172 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700173 return AAUDIO_OK;
174 }
175
176 stop();
177
Phil Burk8b4e05e2019-12-17 12:12:09 -0800178 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700179 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
180 if (endpoint == nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700181 result = AAUDIO_ERROR_INVALID_STATE;
182 } else {
Phil Burk6e2770e2018-05-01 13:03:52 -0700183 endpoint->unregisterStream(this);
184 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
185 endpointManager.closeEndpoint(endpoint);
186
187 // AAudioService::closeStream() prevents two threads from closing at the same time.
188 mServiceEndpoint.clear(); // endpoint will hold the pointer until this method returns.
Phil Burk39f02dd2017-08-04 09:13:31 -0700189 }
190
191 {
192 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk98d6d922017-07-06 11:52:45 -0700193 stopTimestampThread();
Phil Burk98d6d922017-07-06 11:52:45 -0700194 delete mUpMessageQueue;
195 mUpMessageQueue = nullptr;
Phil Burk98d6d922017-07-06 11:52:45 -0700196 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700197
Phil Burkbcc36742017-08-31 17:24:51 -0700198 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burka9876702020-04-20 18:16:15 -0700199
200 mediametrics::LogItem(mMetricsId)
201 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CLOSE)
202 .record();
Phil Burk39f02dd2017-08-04 09:13:31 -0700203 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800204}
205
Phil Burkbcc36742017-08-31 17:24:51 -0700206aaudio_result_t AAudioServiceStreamBase::startDevice() {
207 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burk6e2770e2018-05-01 13:03:52 -0700208 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
209 if (endpoint == nullptr) {
210 ALOGE("%s() has no endpoint", __func__);
211 return AAUDIO_ERROR_INVALID_STATE;
212 }
213 return endpoint->startStream(this, &mClientHandle);
Phil Burkbcc36742017-08-31 17:24:51 -0700214}
215
Phil Burk39f02dd2017-08-04 09:13:31 -0700216/**
217 * Start the flow of audio data.
218 *
219 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
220 */
Phil Burkc0c70e32017-02-09 13:18:38 -0800221aaudio_result_t AAudioServiceStreamBase::start() {
Phil Burka9876702020-04-20 18:16:15 -0700222 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burkbcc36742017-08-31 17:24:51 -0700223 aaudio_result_t result = AAUDIO_OK;
Phil Burk6e2770e2018-05-01 13:03:52 -0700224
Phil Burka9876702020-04-20 18:16:15 -0700225 mediametrics::Defer defer([&] {
226 mediametrics::LogItem(mMetricsId)
227 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
228 .set(AMEDIAMETRICS_PROP_DURATIONNS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
229 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
230 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
231 .record(); });
232
Eric Laurentcb4dae22017-07-01 19:39:32 -0700233 if (isRunning()) {
234 return AAUDIO_OK;
235 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700236
Phil Burk23296382017-11-20 15:45:11 -0800237 setFlowing(false);
Phil Burk762365c2018-12-10 16:02:16 -0800238 setSuspended(false);
Phil Burk23296382017-11-20 15:45:11 -0800239
Phil Burkbcc36742017-08-31 17:24:51 -0700240 // Start with fresh presentation timestamps.
Phil Burka53ffa62018-10-10 16:21:37 -0700241 mAtomicStreamTimestamp.clear();
Phil Burkbcc36742017-08-31 17:24:51 -0700242
Phil Burk39f02dd2017-08-04 09:13:31 -0700243 mClientHandle = AUDIO_PORT_HANDLE_NONE;
Phil Burkbcc36742017-08-31 17:24:51 -0700244 result = startDevice();
245 if (result != AAUDIO_OK) goto error;
246
247 // This should happen at the end of the start.
248 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
249 setState(AAUDIO_STREAM_STATE_STARTED);
250 mThreadEnabled.store(true);
251 result = mTimestampThread.start(this);
252 if (result != AAUDIO_OK) goto error;
253
254 return result;
255
256error:
257 disconnect();
Phil Burk39f02dd2017-08-04 09:13:31 -0700258 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800259}
260
261aaudio_result_t AAudioServiceStreamBase::pause() {
Phil Burka9876702020-04-20 18:16:15 -0700262 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk11e8d332017-05-24 09:59:02 -0700263 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700264 if (!isRunning()) {
265 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800266 }
Phil Burk73af62a2017-10-26 12:11:47 -0700267
Phil Burka9876702020-04-20 18:16:15 -0700268 mediametrics::Defer defer([&] {
269 mediametrics::LogItem(mMetricsId)
270 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
271 .set(AMEDIAMETRICS_PROP_DURATIONNS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
272 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
273 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
274 .record(); });
275
Phil Burk73af62a2017-10-26 12:11:47 -0700276 // Send it now because the timestamp gets rounded up when stopStream() is called below.
277 // Also we don't need the timestamps while we are shutting down.
278 sendCurrentTimestamp();
279
280 result = stopTimestampThread();
281 if (result != AAUDIO_OK) {
282 disconnect();
283 return result;
284 }
285
Phil Burk6e2770e2018-05-01 13:03:52 -0700286 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
287 if (endpoint == nullptr) {
288 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700289 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
290 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700291 }
292 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700293 if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700294 ALOGE("%s() mServiceEndpoint returned %d, %s", __func__, result, getTypeText());
Phil Burk39f02dd2017-08-04 09:13:31 -0700295 disconnect(); // TODO should we return or pause Base first?
296 }
297
Eric Laurentcb4dae22017-07-01 19:39:32 -0700298 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
Phil Burkbcc36742017-08-31 17:24:51 -0700299 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burkc0c70e32017-02-09 13:18:38 -0800300 return result;
301}
302
Phil Burk71f35bb2017-04-13 16:05:07 -0700303aaudio_result_t AAudioServiceStreamBase::stop() {
Phil Burka9876702020-04-20 18:16:15 -0700304 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk11e8d332017-05-24 09:59:02 -0700305 aaudio_result_t result = AAUDIO_OK;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700306 if (!isRunning()) {
307 return result;
Phil Burk71f35bb2017-04-13 16:05:07 -0700308 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700309
Phil Burka9876702020-04-20 18:16:15 -0700310 mediametrics::Defer defer([&] {
311 mediametrics::LogItem(mMetricsId)
312 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
313 .set(AMEDIAMETRICS_PROP_DURATIONNS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
314 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
315 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
316 .record(); });
317
Phil Burk83fb8442017-10-05 16:55:17 -0700318 setState(AAUDIO_STREAM_STATE_STOPPING);
319
Phil Burk73af62a2017-10-26 12:11:47 -0700320 // Send it now because the timestamp gets rounded up when stopStream() is called below.
321 // Also we don't need the timestamps while we are shutting down.
Eric Laurentcb4dae22017-07-01 19:39:32 -0700322 sendCurrentTimestamp(); // warning - this calls a virtual function
323 result = stopTimestampThread();
324 if (result != AAUDIO_OK) {
325 disconnect();
326 return result;
327 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700328
Phil Burk6e2770e2018-05-01 13:03:52 -0700329 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
330 if (endpoint == nullptr) {
331 ALOGE("%s() has no endpoint", __func__);
Phil Burka9876702020-04-20 18:16:15 -0700332 result = AAUDIO_ERROR_INVALID_STATE; // for MediaMetric tracking
333 return result;
Phil Burk6e2770e2018-05-01 13:03:52 -0700334 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700335 // TODO wait for data to be played out
Phil Burk6e2770e2018-05-01 13:03:52 -0700336 result = endpoint->stopStream(this, mClientHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700337 if (result != AAUDIO_OK) {
Phil Burk6e2770e2018-05-01 13:03:52 -0700338 ALOGE("%s() stopStream returned %d, %s", __func__, result, getTypeText());
Phil Burk39f02dd2017-08-04 09:13:31 -0700339 disconnect();
340 // TODO what to do with result here?
341 }
342
Eric Laurentcb4dae22017-07-01 19:39:32 -0700343 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
Phil Burkbcc36742017-08-31 17:24:51 -0700344 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700345 return result;
346}
347
Phil Burk98d6d922017-07-06 11:52:45 -0700348aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
349 aaudio_result_t result = AAUDIO_OK;
350 // clear flag that tells thread to loop
351 if (mThreadEnabled.exchange(false)) {
Phil Burkbcc36742017-08-31 17:24:51 -0700352 result = mTimestampThread.stop();
Phil Burk98d6d922017-07-06 11:52:45 -0700353 }
354 return result;
355}
356
Phil Burk71f35bb2017-04-13 16:05:07 -0700357aaudio_result_t AAudioServiceStreamBase::flush() {
Phil Burka9876702020-04-20 18:16:15 -0700358 const int64_t beginNs = AudioClock::getNanoseconds();
Phil Burk5cc83c32017-11-28 15:43:18 -0800359 aaudio_result_t result = AAudio_isFlushAllowed(getState());
360 if (result != AAUDIO_OK) {
361 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700362 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800363
Phil Burka9876702020-04-20 18:16:15 -0700364 mediametrics::Defer defer([&] {
365 mediametrics::LogItem(mMetricsId)
366 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
367 .set(AMEDIAMETRICS_PROP_DURATIONNS, (int64_t)(AudioClock::getNanoseconds() - beginNs))
368 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
369 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
370 .record(); });
371
Phil Burk39f02dd2017-08-04 09:13:31 -0700372 // Data will get flushed when the client receives the FLUSHED event.
Phil Burk71f35bb2017-04-13 16:05:07 -0700373 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
Phil Burkbcc36742017-08-31 17:24:51 -0700374 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burk71f35bb2017-04-13 16:05:07 -0700375 return AAUDIO_OK;
376}
377
Phil Burkcf5f6d22017-05-26 12:35:07 -0700378// implement Runnable, periodically send timestamps to client
Phil Burka53ffa62018-10-10 16:21:37 -0700379__attribute__((no_sanitize("integer")))
Phil Burkc0c70e32017-02-09 13:18:38 -0800380void AAudioServiceStreamBase::run() {
Phil Burk19e990e2018-03-22 13:59:34 -0700381 ALOGD("%s() %s entering >>>>>>>>>>>>>> TIMESTAMPS", __func__, getTypeText());
Phil Burkc0c70e32017-02-09 13:18:38 -0800382 TimestampScheduler timestampScheduler;
Phil Burk39f02dd2017-08-04 09:13:31 -0700383 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
Phil Burkc0c70e32017-02-09 13:18:38 -0800384 timestampScheduler.start(AudioClock::getNanoseconds());
385 int64_t nextTime = timestampScheduler.nextAbsoluteTime();
Phil Burka53ffa62018-10-10 16:21:37 -0700386 int32_t loopCount = 0;
Phil Burkc0c70e32017-02-09 13:18:38 -0800387 while(mThreadEnabled.load()) {
Phil Burka53ffa62018-10-10 16:21:37 -0700388 loopCount++;
Phil Burkc0c70e32017-02-09 13:18:38 -0800389 if (AudioClock::getNanoseconds() >= nextTime) {
390 aaudio_result_t result = sendCurrentTimestamp();
391 if (result != AAUDIO_OK) {
Phil Burka53ffa62018-10-10 16:21:37 -0700392 ALOGE("%s() timestamp thread got result = %d", __func__, result);
Phil Burkc0c70e32017-02-09 13:18:38 -0800393 break;
394 }
395 nextTime = timestampScheduler.nextAbsoluteTime();
396 } else {
397 // Sleep until it is time to send the next timestamp.
Phil Burk98d6d922017-07-06 11:52:45 -0700398 // TODO Wait for a signal with a timeout so that we can stop more quickly.
Phil Burkc0c70e32017-02-09 13:18:38 -0800399 AudioClock::sleepUntilNanoTime(nextTime);
400 }
401 }
Phil Burka53ffa62018-10-10 16:21:37 -0700402 ALOGD("%s() %s exiting after %d loops <<<<<<<<<<<<<< TIMESTAMPS",
403 __func__, getTypeText(), loopCount);
Phil Burkc0c70e32017-02-09 13:18:38 -0800404}
405
Phil Burk5ef003b2017-06-30 11:43:37 -0700406void AAudioServiceStreamBase::disconnect() {
Phil Burkbcc36742017-08-31 17:24:51 -0700407 if (getState() != AAUDIO_STREAM_STATE_DISCONNECTED) {
Phil Burka9876702020-04-20 18:16:15 -0700408 mediametrics::LogItem(mMetricsId)
409 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DISCONNECT)
410 .set(AMEDIAMETRICS_PROP_STATE, AudioGlobal_convertStreamStateToText(getState()))
411 .record();
Phil Burk5ef003b2017-06-30 11:43:37 -0700412 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
Phil Burkbcc36742017-08-31 17:24:51 -0700413 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
Phil Burk5ef003b2017-06-30 11:43:37 -0700414 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800415}
416
417aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
Phil Burk23296382017-11-20 15:45:11 -0800418 double dataDouble) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800419 AAudioServiceMessage command;
420 command.what = AAudioServiceMessage::code::EVENT;
Phil Burk2355edb2016-12-26 13:54:02 -0800421 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800422 command.event.dataDouble = dataDouble;
Phil Burk23296382017-11-20 15:45:11 -0800423 return writeUpMessageQueue(&command);
424}
425
426aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
427 int64_t dataLong) {
428 AAudioServiceMessage command;
429 command.what = AAudioServiceMessage::code::EVENT;
430 command.event.event = event;
Phil Burkc0c70e32017-02-09 13:18:38 -0800431 command.event.dataLong = dataLong;
432 return writeUpMessageQueue(&command);
433}
434
Phil Burkf878a8d2019-03-29 17:23:00 -0700435bool AAudioServiceStreamBase::isUpMessageQueueBusy() {
436 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
437 if (mUpMessageQueue == nullptr) {
438 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
439 return true;
440 }
441 int32_t framesAvailable = mUpMessageQueue->getFifoBuffer()
442 ->getFullFramesAvailable();
443 int32_t capacity = mUpMessageQueue->getFifoBuffer()
444 ->getBufferCapacityInFrames();
445 // Is it half full or more
446 return framesAvailable >= (capacity / 2);
447}
448
Phil Burkc0c70e32017-02-09 13:18:38 -0800449aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700450 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
Phil Burk71f35bb2017-04-13 16:05:07 -0700451 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700452 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk71f35bb2017-04-13 16:05:07 -0700453 return AAUDIO_ERROR_NULL;
454 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800455 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
456 if (count != 1) {
Phil Burk762365c2018-12-10 16:02:16 -0800457 ALOGW("%s(): Queue full. Did client stop? Suspending stream. what = %u, %s",
458 __func__, command->what, getTypeText());
459 setSuspended(true);
Phil Burkc0c70e32017-02-09 13:18:38 -0800460 return AAUDIO_ERROR_WOULD_BLOCK;
461 } else {
462 return AAUDIO_OK;
463 }
464}
465
Phil Burk23296382017-11-20 15:45:11 -0800466aaudio_result_t AAudioServiceStreamBase::sendXRunCount(int32_t xRunCount) {
467 return sendServiceEvent(AAUDIO_SERVICE_EVENT_XRUN, (int64_t) xRunCount);
468}
469
Phil Burkc0c70e32017-02-09 13:18:38 -0800470aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
471 AAudioServiceMessage command;
Phil Burkf878a8d2019-03-29 17:23:00 -0700472 // It is not worth filling up the queue with timestamps.
473 // That can cause the stream to get suspended.
474 // So just drop the timestamp if the queue is getting full.
475 if (isUpMessageQueueBusy()) {
476 return AAUDIO_OK;
477 }
478
Phil Burk97350f92017-07-21 15:59:44 -0700479 // Send a timestamp for the clock model.
Phil Burkc0c70e32017-02-09 13:18:38 -0800480 aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
481 &command.timestamp.timestamp);
482 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700483 ALOGV("%s() SERVICE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700484 (long long) command.timestamp.position,
485 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700486 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
Phil Burkc0c70e32017-02-09 13:18:38 -0800487 result = writeUpMessageQueue(&command);
Phil Burk97350f92017-07-21 15:59:44 -0700488
489 if (result == AAUDIO_OK) {
490 // Send a hardware timestamp for presentation time.
491 result = getHardwareTimestamp(&command.timestamp.position,
492 &command.timestamp.timestamp);
493 if (result == AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700494 ALOGV("%s() HARDWARE %8lld at %lld", __func__,
Phil Burkbcc36742017-08-31 17:24:51 -0700495 (long long) command.timestamp.position,
496 (long long) command.timestamp.timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700497 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
498 result = writeUpMessageQueue(&command);
499 }
500 }
501 }
502
Phil Burkbcc36742017-08-31 17:24:51 -0700503 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
Phil Burk940083c2017-07-17 17:00:02 -0700504 result = AAUDIO_OK; // just not available yet, try again later
Phil Burkc0c70e32017-02-09 13:18:38 -0800505 }
506 return result;
Phil Burk2355edb2016-12-26 13:54:02 -0800507}
508
Phil Burkc0c70e32017-02-09 13:18:38 -0800509/**
510 * Get an immutable description of the in-memory queues
511 * used to communicate with the underlying HAL or Service.
512 */
513aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
Phil Burk523b3042017-09-13 13:03:08 -0700514 {
515 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
516 if (mUpMessageQueue == nullptr) {
Phil Burk19e990e2018-03-22 13:59:34 -0700517 ALOGE("%s(): mUpMessageQueue null! - stream not open", __func__);
Phil Burk523b3042017-09-13 13:03:08 -0700518 return AAUDIO_ERROR_NULL;
519 }
520 // Gather information on the message queue.
521 mUpMessageQueue->fillParcelable(parcelable,
522 parcelable.mUpMessageQueueParcelable);
523 }
524 return getAudioDataDescription(parcelable);
Phil Burk11e8d332017-05-24 09:59:02 -0700525}
Phil Burk39f02dd2017-08-04 09:13:31 -0700526
527void AAudioServiceStreamBase::onVolumeChanged(float volume) {
528 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
529}
Phil Burk94862522017-09-13 21:31:36 -0700530
Phil Burk2fe718b2018-05-14 12:28:32 -0700531int32_t AAudioServiceStreamBase::incrementServiceReferenceCount_l() {
Phil Burk94862522017-09-13 21:31:36 -0700532 return ++mCallingCount;
533}
534
Phil Burk2fe718b2018-05-14 12:28:32 -0700535int32_t AAudioServiceStreamBase::decrementServiceReferenceCount_l() {
536 int32_t count = --mCallingCount;
537 // Each call to increment should be balanced with one call to decrement.
538 assert(count >= 0);
539 return count;
Phil Burk94862522017-09-13 21:31:36 -0700540}