blob: b6111601b2aaf10912d975501f36f06a9a74ab0b [file] [log] [blame]
Phil Burk204a1632017-01-03 17:23:43 -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
Phil Burkcf5f6d22017-05-26 12:35:07 -070017// This file is used in both client and server processes.
18// This is needed to make sense of the logs more easily.
Eric Laurentcb4dae22017-07-01 19:39:32 -070019#define LOG_TAG (mInService ? "AudioStreamInternal_Service" : "AudioStreamInternal_Client")
Phil Burk204a1632017-01-03 17:23:43 -080020//#define LOG_NDEBUG 0
21#include <utils/Log.h>
22
Phil Burk4485d412017-05-09 15:55:02 -070023#define ATRACE_TAG ATRACE_TAG_AUDIO
24
Phil Burkc0c70e32017-02-09 13:18:38 -080025#include <stdint.h>
Phil Burk204a1632017-01-03 17:23:43 -080026
27#include <binder/IServiceManager.h>
28
Phil Burk5ed503c2017-02-01 09:38:15 -080029#include <aaudio/AAudio.h>
Phil Burkfd34a932017-07-19 07:03:52 -070030#include <cutils/properties.h>
Phil Burke4d7bb42017-03-28 11:32:39 -070031#include <utils/String16.h>
Phil Burk4485d412017-05-09 15:55:02 -070032#include <utils/Trace.h>
Phil Burk204a1632017-01-03 17:23:43 -080033
Phil Burkc0c70e32017-02-09 13:18:38 -080034#include "AudioEndpointParcelable.h"
35#include "binding/AAudioStreamRequest.h"
36#include "binding/AAudioStreamConfiguration.h"
37#include "binding/IAAudioService.h"
Phil Burk5ed503c2017-02-01 09:38:15 -080038#include "binding/AAudioServiceMessage.h"
Phil Burk3df348f2017-02-08 11:41:55 -080039#include "core/AudioStreamBuilder.h"
Phil Burke572f462017-04-20 13:03:19 -070040#include "fifo/FifoBuffer.h"
Phil Burkfd34a932017-07-19 07:03:52 -070041#include "utility/AudioClock.h"
Phil Burke572f462017-04-20 13:03:19 -070042#include "utility/LinearRamp.h"
43
Phil Burkc0c70e32017-02-09 13:18:38 -080044#include "AudioStreamInternal.h"
Phil Burk204a1632017-01-03 17:23:43 -080045
Phil Burk204a1632017-01-03 17:23:43 -080046using android::String16;
Phil Burkdec33ab2017-01-17 14:48:16 -080047using android::Mutex;
Phil Burkc0c70e32017-02-09 13:18:38 -080048using android::WrappingBuffer;
Phil Burk204a1632017-01-03 17:23:43 -080049
Phil Burk5ed503c2017-02-01 09:38:15 -080050using namespace aaudio;
Phil Burk204a1632017-01-03 17:23:43 -080051
Phil Burke4d7bb42017-03-28 11:32:39 -070052#define MIN_TIMEOUT_NANOS (1000 * AAUDIO_NANOS_PER_MILLISECOND)
53
54// Wait at least this many times longer than the operation should take.
55#define MIN_TIMEOUT_OPERATIONS 4
56
Phil Burkbcc36742017-08-31 17:24:51 -070057#define LOG_TIMESTAMPS 0
Phil Burk87c9f642017-05-17 07:22:39 -070058
Phil Burkc0c70e32017-02-09 13:18:38 -080059AudioStreamInternal::AudioStreamInternal(AAudioServiceInterface &serviceInterface, bool inService)
Phil Burk204a1632017-01-03 17:23:43 -080060 : AudioStream()
61 , mClockModel()
62 , mAudioEndpoint()
Phil Burk5ed503c2017-02-01 09:38:15 -080063 , mServiceStreamHandle(AAUDIO_HANDLE_INVALID)
Phil Burkec89b2e2017-06-20 15:05:06 -070064 , mInService(inService)
Phil Burkfd34a932017-07-19 07:03:52 -070065 , mServiceInterface(serviceInterface)
Phil Burkbcc36742017-08-31 17:24:51 -070066 , mAtomicTimestamp()
Phil Burkfd34a932017-07-19 07:03:52 -070067 , mWakeupDelayNanos(AAudioProperty_getWakeupDelayMicros() * AAUDIO_NANOS_PER_MICROSECOND)
68 , mMinimumSleepNanos(AAudioProperty_getMinimumSleepMicros() * AAUDIO_NANOS_PER_MICROSECOND)
69 {
Phil Burkfbf031e2017-10-12 15:58:31 -070070 ALOGD("%s - mWakeupDelayNanos = %d, mMinimumSleepNanos = %d",
71 __func__, mWakeupDelayNanos, mMinimumSleepNanos);
Phil Burk204a1632017-01-03 17:23:43 -080072}
73
74AudioStreamInternal::~AudioStreamInternal() {
75}
76
Phil Burk5ed503c2017-02-01 09:38:15 -080077aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) {
Phil Burk204a1632017-01-03 17:23:43 -080078
Phil Burk5ed503c2017-02-01 09:38:15 -080079 aaudio_result_t result = AAUDIO_OK;
Phil Burk99306c82017-08-14 12:38:58 -070080 int32_t capacity;
Phil Burk6479d502017-11-20 09:32:52 -080081 int32_t framesPerBurst;
Phil Burk5ed503c2017-02-01 09:38:15 -080082 AAudioStreamRequest request;
Phil Burk99306c82017-08-14 12:38:58 -070083 AAudioStreamConfiguration configurationOutput;
Phil Burk204a1632017-01-03 17:23:43 -080084
Phil Burk99306c82017-08-14 12:38:58 -070085 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
Phil Burkfbf031e2017-10-12 15:58:31 -070086 ALOGE("%s - already open! state = %d", __func__, getState());
Phil Burk99306c82017-08-14 12:38:58 -070087 return AAUDIO_ERROR_INVALID_STATE;
88 }
89
90 // Copy requested parameters to the stream.
Phil Burk204a1632017-01-03 17:23:43 -080091 result = AudioStream::open(builder);
92 if (result < 0) {
93 return result;
94 }
95
Phil Burkc0c70e32017-02-09 13:18:38 -080096 // We have to do volume scaling. So we prefer FLOAT format.
Glenn Kasten37a466a2017-05-30 15:53:14 -070097 if (getFormat() == AAUDIO_FORMAT_UNSPECIFIED) {
Phil Burkc0c70e32017-02-09 13:18:38 -080098 setFormat(AAUDIO_FORMAT_PCM_FLOAT);
99 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700100 // Request FLOAT for the shared mixer.
jiabin901f65d2017-07-12 17:56:35 -0700101 request.getConfiguration().setFormat(AAUDIO_FORMAT_PCM_FLOAT);
Phil Burkc0c70e32017-02-09 13:18:38 -0800102
Phil Burkdec33ab2017-01-17 14:48:16 -0800103 // Build the request to send to the server.
Phil Burk204a1632017-01-03 17:23:43 -0800104 request.setUserId(getuid());
105 request.setProcessId(getpid());
Phil Burk71f35bb2017-04-13 16:05:07 -0700106 request.setSharingModeMatchRequired(isSharingModeMatchRequired());
Eric Laurentcb4dae22017-07-01 19:39:32 -0700107 request.setInService(mInService);
Phil Burkc0c70e32017-02-09 13:18:38 -0800108
Phil Burk204a1632017-01-03 17:23:43 -0800109 request.getConfiguration().setDeviceId(getDeviceId());
110 request.getConfiguration().setSampleRate(getSampleRate());
111 request.getConfiguration().setSamplesPerFrame(getSamplesPerFrame());
Phil Burk39f02dd2017-08-04 09:13:31 -0700112 request.getConfiguration().setDirection(getDirection());
Phil Burk71f35bb2017-04-13 16:05:07 -0700113 request.getConfiguration().setSharingMode(getSharingMode());
114
Phil Burka62fb952018-01-16 12:44:06 -0800115 request.getConfiguration().setUsage(getUsage());
116 request.getConfiguration().setContentType(getContentType());
117 request.getConfiguration().setInputPreset(getInputPreset());
118
Phil Burk3df348f2017-02-08 11:41:55 -0800119 request.getConfiguration().setBufferCapacity(builder.getBufferCapacity());
Phil Burk204a1632017-01-03 17:23:43 -0800120
Phil Burk99306c82017-08-14 12:38:58 -0700121 mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
Phil Burk204a1632017-01-03 17:23:43 -0800122 if (mServiceStreamHandle < 0) {
123 result = mServiceStreamHandle;
Phil Burkfbf031e2017-10-12 15:58:31 -0700124 ALOGE("%s - openStream() returned %d", __func__, result);
Phil Burk99306c82017-08-14 12:38:58 -0700125 return result;
Phil Burk204a1632017-01-03 17:23:43 -0800126 }
Phil Burk99306c82017-08-14 12:38:58 -0700127
128 result = configurationOutput.validate();
129 if (result != AAUDIO_OK) {
130 goto error;
131 }
132 // Save results of the open.
133 setSampleRate(configurationOutput.getSampleRate());
134 setSamplesPerFrame(configurationOutput.getSamplesPerFrame());
135 setDeviceId(configurationOutput.getDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800136 setSessionId(configurationOutput.getSessionId());
Phil Burk99306c82017-08-14 12:38:58 -0700137 setSharingMode(configurationOutput.getSharingMode());
138
Phil Burka62fb952018-01-16 12:44:06 -0800139 setUsage(configurationOutput.getUsage());
140 setContentType(configurationOutput.getContentType());
141 setInputPreset(configurationOutput.getInputPreset());
142
Phil Burk99306c82017-08-14 12:38:58 -0700143 // Save device format so we can do format conversion and volume scaling together.
144 mDeviceFormat = configurationOutput.getFormat();
145
146 result = mServiceInterface.getStreamDescription(mServiceStreamHandle, mEndPointParcelable);
147 if (result != AAUDIO_OK) {
148 goto error;
149 }
150
151 // Resolve parcelable into a descriptor.
152 result = mEndPointParcelable.resolve(&mEndpointDescriptor);
153 if (result != AAUDIO_OK) {
154 goto error;
155 }
156
157 // Configure endpoint based on descriptor.
158 result = mAudioEndpoint.configure(&mEndpointDescriptor, getDirection());
159 if (result != AAUDIO_OK) {
160 goto error;
161 }
162
Phil Burk99306c82017-08-14 12:38:58 -0700163
164 // Validate result from server.
Phil Burk6479d502017-11-20 09:32:52 -0800165 framesPerBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst;
166 if (framesPerBurst < MIN_FRAMES_PER_BURST || framesPerBurst > MAX_FRAMES_PER_BURST) {
167 ALOGE("%s - framesPerBurst out of range = %d", __func__, framesPerBurst);
Phil Burk99306c82017-08-14 12:38:58 -0700168 result = AAUDIO_ERROR_OUT_OF_RANGE;
169 goto error;
170 }
Phil Burk6479d502017-11-20 09:32:52 -0800171 mFramesPerBurst = framesPerBurst; // only save good value
172
173 capacity = mEndpointDescriptor.dataQueueDescriptor.capacityInFrames;
174 if (capacity < mFramesPerBurst || capacity > MAX_BUFFER_CAPACITY_IN_FRAMES) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700175 ALOGE("%s - bufferCapacity out of range = %d", __func__, capacity);
Phil Burk99306c82017-08-14 12:38:58 -0700176 result = AAUDIO_ERROR_OUT_OF_RANGE;
177 goto error;
178 }
179
180 mClockModel.setSampleRate(getSampleRate());
181 mClockModel.setFramesPerBurst(mFramesPerBurst);
182
Phil Burk134f1972017-12-08 13:06:11 -0800183 if (isDataCallbackSet()) {
Phil Burk99306c82017-08-14 12:38:58 -0700184 mCallbackFrames = builder.getFramesPerDataCallback();
185 if (mCallbackFrames > getBufferCapacity() / 2) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700186 ALOGE("%s - framesPerCallback too big = %d, capacity = %d",
187 __func__, mCallbackFrames, getBufferCapacity());
Phil Burk99306c82017-08-14 12:38:58 -0700188 result = AAUDIO_ERROR_OUT_OF_RANGE;
189 goto error;
190
191 } else if (mCallbackFrames < 0) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700192 ALOGE("%s - framesPerCallback negative", __func__);
Phil Burk99306c82017-08-14 12:38:58 -0700193 result = AAUDIO_ERROR_OUT_OF_RANGE;
194 goto error;
195
196 }
197 if (mCallbackFrames == AAUDIO_UNSPECIFIED) {
198 mCallbackFrames = mFramesPerBurst;
199 }
200
201 int32_t bytesPerFrame = getSamplesPerFrame()
202 * AAudioConvert_formatToSizeInBytes(getFormat());
203 int32_t callbackBufferSize = mCallbackFrames * bytesPerFrame;
204 mCallbackBuffer = new uint8_t[callbackBufferSize];
205 }
206
207 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burk99306c82017-08-14 12:38:58 -0700208
209 return result;
210
211error:
212 close();
Phil Burk204a1632017-01-03 17:23:43 -0800213 return result;
214}
215
Phil Burk5ed503c2017-02-01 09:38:15 -0800216aaudio_result_t AudioStreamInternal::close() {
Phil Burk965650e2017-09-07 21:00:09 -0700217 aaudio_result_t result = AAUDIO_OK;
218 ALOGD("close(): mServiceStreamHandle = 0x%08X",
Phil Burk71f35bb2017-04-13 16:05:07 -0700219 mServiceStreamHandle);
Phil Burk5ed503c2017-02-01 09:38:15 -0800220 if (mServiceStreamHandle != AAUDIO_HANDLE_INVALID) {
Phil Burk4485d412017-05-09 15:55:02 -0700221 // Don't close a stream while it is running.
222 aaudio_stream_state_t currentState = getState();
Phil Burk87c9f642017-05-17 07:22:39 -0700223 if (isActive()) {
Phil Burk4485d412017-05-09 15:55:02 -0700224 requestStop();
225 aaudio_stream_state_t nextState;
226 int64_t timeoutNanoseconds = MIN_TIMEOUT_NANOS;
Phil Burk965650e2017-09-07 21:00:09 -0700227 result = waitForStateChange(currentState, &nextState,
Phil Burk4485d412017-05-09 15:55:02 -0700228 timeoutNanoseconds);
229 if (result != AAUDIO_OK) {
Phil Burk965650e2017-09-07 21:00:09 -0700230 ALOGE("close() waitForStateChange() returned %d %s",
Phil Burk4485d412017-05-09 15:55:02 -0700231 result, AAudio_convertResultToText(result));
232 }
233 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700234 setState(AAUDIO_STREAM_STATE_CLOSING);
Phil Burk5ed503c2017-02-01 09:38:15 -0800235 aaudio_handle_t serviceStreamHandle = mServiceStreamHandle;
236 mServiceStreamHandle = AAUDIO_HANDLE_INVALID;
Phil Burkc0c70e32017-02-09 13:18:38 -0800237
238 mServiceInterface.closeStream(serviceStreamHandle);
Phil Burke4d7bb42017-03-28 11:32:39 -0700239 delete[] mCallbackBuffer;
Phil Burk4485d412017-05-09 15:55:02 -0700240 mCallbackBuffer = nullptr;
Phil Burk965650e2017-09-07 21:00:09 -0700241
Phil Burkec89b2e2017-06-20 15:05:06 -0700242 setState(AAUDIO_STREAM_STATE_CLOSED);
Phil Burk965650e2017-09-07 21:00:09 -0700243 result = mEndPointParcelable.close();
244 aaudio_result_t result2 = AudioStream::close();
245 return (result != AAUDIO_OK) ? result : result2;
Phil Burk204a1632017-01-03 17:23:43 -0800246 } else {
Phil Burk5ed503c2017-02-01 09:38:15 -0800247 return AAUDIO_ERROR_INVALID_HANDLE;
Phil Burk204a1632017-01-03 17:23:43 -0800248 }
249}
250
Phil Burke4d7bb42017-03-28 11:32:39 -0700251static void *aaudio_callback_thread_proc(void *context)
252{
253 AudioStreamInternal *stream = (AudioStreamInternal *)context;
Phil Burkfbf031e2017-10-12 15:58:31 -0700254 //LOGD("oboe_callback_thread, stream = %p", stream);
Phil Burke4d7bb42017-03-28 11:32:39 -0700255 if (stream != NULL) {
256 return stream->callbackLoop();
257 } else {
258 return NULL;
259 }
260}
261
Phil Burkbcc36742017-08-31 17:24:51 -0700262/*
263 * It normally takes about 20-30 msec to start a stream on the server.
264 * But the first time can take as much as 200-300 msec. The HW
265 * starts right away so by the time the client gets a chance to write into
266 * the buffer, it is already in a deep underflow state. That can cause the
267 * XRunCount to be non-zero, which could lead an app to tune its latency higher.
268 * To avoid this problem, we set a request for the processing code to start the
269 * client stream at the same position as the server stream.
270 * The processing code will then save the current offset
271 * between client and server and apply that to any position given to the app.
272 */
Phil Burk5ed503c2017-02-01 09:38:15 -0800273aaudio_result_t AudioStreamInternal::requestStart()
Phil Burk204a1632017-01-03 17:23:43 -0800274{
Phil Burk3316d5e2017-02-15 11:23:01 -0800275 int64_t startTime;
Phil Burk5ed503c2017-02-01 09:38:15 -0800276 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burkbcc36742017-08-31 17:24:51 -0700277 ALOGE("requestStart() mServiceStreamHandle invalid");
Phil Burk5ed503c2017-02-01 09:38:15 -0800278 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800279 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700280 if (isActive()) {
Phil Burkbcc36742017-08-31 17:24:51 -0700281 ALOGE("requestStart() already active");
Phil Burkec89b2e2017-06-20 15:05:06 -0700282 return AAUDIO_ERROR_INVALID_STATE;
283 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700284
Phil Burkbcc36742017-08-31 17:24:51 -0700285 aaudio_stream_state_t originalState = getState();
286 if (originalState == AAUDIO_STREAM_STATE_DISCONNECTED) {
287 ALOGE("requestStart() but DISCONNECTED");
288 return AAUDIO_ERROR_DISCONNECTED;
289 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700290 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burkbcc36742017-08-31 17:24:51 -0700291
292 // Clear any stale timestamps from the previous run.
293 drainTimestampsFromService();
294
Phil Burk965650e2017-09-07 21:00:09 -0700295 aaudio_result_t result = mServiceInterface.startStream(mServiceStreamHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800296
Phil Burk3316d5e2017-02-15 11:23:01 -0800297 startTime = AudioClock::getNanoseconds();
Phil Burk204a1632017-01-03 17:23:43 -0800298 mClockModel.start(startTime);
Phil Burkbcc36742017-08-31 17:24:51 -0700299 mNeedCatchUp.request(); // Ask data processing code to catch up when first timestamp received.
Phil Burke4d7bb42017-03-28 11:32:39 -0700300
Phil Burk965650e2017-09-07 21:00:09 -0700301 // Start data callback thread.
Phil Burk134f1972017-12-08 13:06:11 -0800302 if (result == AAUDIO_OK && isDataCallbackSet()) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700303 // Launch the callback loop thread.
304 int64_t periodNanos = mCallbackFrames
305 * AAUDIO_NANOS_PER_SECOND
306 / getSampleRate();
307 mCallbackEnabled.store(true);
308 result = createThread(periodNanos, aaudio_callback_thread_proc, this);
309 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700310 if (result != AAUDIO_OK) {
311 setState(originalState);
312 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700313 return result;
Phil Burk204a1632017-01-03 17:23:43 -0800314}
315
Phil Burke4d7bb42017-03-28 11:32:39 -0700316int64_t AudioStreamInternal::calculateReasonableTimeout(int32_t framesPerOperation) {
317
318 // Wait for at least a second or some number of callbacks to join the thread.
Phil Burk71f35bb2017-04-13 16:05:07 -0700319 int64_t timeoutNanoseconds = (MIN_TIMEOUT_OPERATIONS
320 * framesPerOperation
321 * AAUDIO_NANOS_PER_SECOND)
322 / getSampleRate();
Phil Burke4d7bb42017-03-28 11:32:39 -0700323 if (timeoutNanoseconds < MIN_TIMEOUT_NANOS) { // arbitrary number of seconds
324 timeoutNanoseconds = MIN_TIMEOUT_NANOS;
325 }
326 return timeoutNanoseconds;
327}
328
Phil Burk87c9f642017-05-17 07:22:39 -0700329int64_t AudioStreamInternal::calculateReasonableTimeout() {
330 return calculateReasonableTimeout(getFramesPerBurst());
331}
332
Phil Burke4d7bb42017-03-28 11:32:39 -0700333aaudio_result_t AudioStreamInternal::stopCallback()
334{
335 if (isDataCallbackActive()) {
336 mCallbackEnabled.store(false);
Phil Burk87c9f642017-05-17 07:22:39 -0700337 return joinThread(NULL);
Phil Burke4d7bb42017-03-28 11:32:39 -0700338 } else {
339 return AAUDIO_OK;
340 }
341}
342
Phil Burk5cc83c32017-11-28 15:43:18 -0800343aaudio_result_t AudioStreamInternal::requestStop()
Phil Burk71f35bb2017-04-13 16:05:07 -0700344{
Phil Burk5cc83c32017-11-28 15:43:18 -0800345 aaudio_result_t result = stopCallback();
346 if (result != AAUDIO_OK) {
347 return result;
348 }
349
Phil Burk71f35bb2017-04-13 16:05:07 -0700350 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burkbcc36742017-08-31 17:24:51 -0700351 ALOGE("requestStopInternal() mServiceStreamHandle invalid = 0x%08X",
Phil Burk71f35bb2017-04-13 16:05:07 -0700352 mServiceStreamHandle);
353 return AAUDIO_ERROR_INVALID_STATE;
354 }
355
356 mClockModel.stop(AudioClock::getNanoseconds());
357 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burkbcc36742017-08-31 17:24:51 -0700358 mAtomicTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -0700359
360 return mServiceInterface.stopStream(mServiceStreamHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700361}
362
Phil Burk5ed503c2017-02-01 09:38:15 -0800363aaudio_result_t AudioStreamInternal::registerThread() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800364 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burkbcc36742017-08-31 17:24:51 -0700365 ALOGE("registerThread() mServiceStreamHandle invalid");
Phil Burk5ed503c2017-02-01 09:38:15 -0800366 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800367 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800368 return mServiceInterface.registerAudioThread(mServiceStreamHandle,
Phil Burkc0c70e32017-02-09 13:18:38 -0800369 gettid(),
370 getPeriodNanoseconds());
Phil Burk204a1632017-01-03 17:23:43 -0800371}
372
Phil Burk5ed503c2017-02-01 09:38:15 -0800373aaudio_result_t AudioStreamInternal::unregisterThread() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800374 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burkbcc36742017-08-31 17:24:51 -0700375 ALOGE("unregisterThread() mServiceStreamHandle invalid");
Phil Burk5ed503c2017-02-01 09:38:15 -0800376 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800377 }
Phil Burk2ac035f2017-06-23 14:51:14 -0700378 return mServiceInterface.unregisterAudioThread(mServiceStreamHandle, gettid());
Phil Burk204a1632017-01-03 17:23:43 -0800379}
380
Eric Laurentcb4dae22017-07-01 19:39:32 -0700381aaudio_result_t AudioStreamInternal::startClient(const android::AudioClient& client,
382 audio_port_handle_t *clientHandle) {
383 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
384 return AAUDIO_ERROR_INVALID_STATE;
385 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700386
Eric Laurentcb4dae22017-07-01 19:39:32 -0700387 return mServiceInterface.startClient(mServiceStreamHandle, client, clientHandle);
388}
389
390aaudio_result_t AudioStreamInternal::stopClient(audio_port_handle_t clientHandle) {
391 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
392 return AAUDIO_ERROR_INVALID_STATE;
393 }
394 return mServiceInterface.stopClient(mServiceStreamHandle, clientHandle);
395}
396
Phil Burk5ed503c2017-02-01 09:38:15 -0800397aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t clockId,
Phil Burk3316d5e2017-02-15 11:23:01 -0800398 int64_t *framePosition,
399 int64_t *timeNanoseconds) {
Phil Burk97350f92017-07-21 15:59:44 -0700400 // Generated in server and passed to client. Return latest.
401 if (mAtomicTimestamp.isValid()) {
402 Timestamp timestamp = mAtomicTimestamp.read();
Phil Burkbcc36742017-08-31 17:24:51 -0700403 int64_t position = timestamp.getPosition() + mFramesOffsetFromService;
404 if (position >= 0) {
405 *framePosition = position;
406 *timeNanoseconds = timestamp.getNanoseconds();
407 return AAUDIO_OK;
408 }
Phil Burk97350f92017-07-21 15:59:44 -0700409 }
Phil Burkc75d97f2017-09-08 15:48:36 -0700410 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800411}
412
Phil Burk0befec62017-07-28 15:12:13 -0700413aaudio_result_t AudioStreamInternal::updateStateMachine() {
Phil Burke4d7bb42017-03-28 11:32:39 -0700414 if (isDataCallbackActive()) {
415 return AAUDIO_OK; // state is getting updated by the callback thread read/write call
416 }
Phil Burk204a1632017-01-03 17:23:43 -0800417 return processCommands();
418}
419
Phil Burkec89b2e2017-06-20 15:05:06 -0700420void AudioStreamInternal::logTimestamp(AAudioServiceMessage &command) {
Phil Burk204a1632017-01-03 17:23:43 -0800421 static int64_t oldPosition = 0;
Phil Burk3316d5e2017-02-15 11:23:01 -0800422 static int64_t oldTime = 0;
Phil Burk204a1632017-01-03 17:23:43 -0800423 int64_t framePosition = command.timestamp.position;
Phil Burk3316d5e2017-02-15 11:23:01 -0800424 int64_t nanoTime = command.timestamp.timestamp;
Phil Burkbcc36742017-08-31 17:24:51 -0700425 ALOGD("logTimestamp: timestamp says framePosition = %8lld at nanoTime %lld",
Phil Burk204a1632017-01-03 17:23:43 -0800426 (long long) framePosition,
427 (long long) nanoTime);
428 int64_t nanosDelta = nanoTime - oldTime;
429 if (nanosDelta > 0 && oldTime > 0) {
430 int64_t framesDelta = framePosition - oldPosition;
Phil Burk5ed503c2017-02-01 09:38:15 -0800431 int64_t rate = (framesDelta * AAUDIO_NANOS_PER_SECOND) / nanosDelta;
Phil Burkbcc36742017-08-31 17:24:51 -0700432 ALOGD("logTimestamp: framesDelta = %8lld, nanosDelta = %8lld, rate = %lld",
Phil Burkec89b2e2017-06-20 15:05:06 -0700433 (long long) framesDelta, (long long) nanosDelta, (long long) rate);
Phil Burk204a1632017-01-03 17:23:43 -0800434 }
435 oldPosition = framePosition;
436 oldTime = nanoTime;
437}
Phil Burk204a1632017-01-03 17:23:43 -0800438
Phil Burk97350f92017-07-21 15:59:44 -0700439aaudio_result_t AudioStreamInternal::onTimestampService(AAudioServiceMessage *message) {
Phil Burk204a1632017-01-03 17:23:43 -0800440#if LOG_TIMESTAMPS
Phil Burkec89b2e2017-06-20 15:05:06 -0700441 logTimestamp(*message);
Phil Burk204a1632017-01-03 17:23:43 -0800442#endif
Phil Burk87c9f642017-05-17 07:22:39 -0700443 processTimestamp(message->timestamp.position, message->timestamp.timestamp);
Phil Burk5ed503c2017-02-01 09:38:15 -0800444 return AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800445}
446
Phil Burk97350f92017-07-21 15:59:44 -0700447aaudio_result_t AudioStreamInternal::onTimestampHardware(AAudioServiceMessage *message) {
448 Timestamp timestamp(message->timestamp.position, message->timestamp.timestamp);
449 mAtomicTimestamp.write(timestamp);
450 return AAUDIO_OK;
451}
452
Phil Burk5ed503c2017-02-01 09:38:15 -0800453aaudio_result_t AudioStreamInternal::onEventFromServer(AAudioServiceMessage *message) {
454 aaudio_result_t result = AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800455 switch (message->event.event) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800456 case AAUDIO_SERVICE_EVENT_STARTED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700457 ALOGD("%s - got AAUDIO_SERVICE_EVENT_STARTED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700458 if (getState() == AAUDIO_STREAM_STATE_STARTING) {
459 setState(AAUDIO_STREAM_STATE_STARTED);
460 }
Phil Burk204a1632017-01-03 17:23:43 -0800461 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800462 case AAUDIO_SERVICE_EVENT_PAUSED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700463 ALOGD("%s - got AAUDIO_SERVICE_EVENT_PAUSED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700464 if (getState() == AAUDIO_STREAM_STATE_PAUSING) {
465 setState(AAUDIO_STREAM_STATE_PAUSED);
466 }
Phil Burk204a1632017-01-03 17:23:43 -0800467 break;
Phil Burk71f35bb2017-04-13 16:05:07 -0700468 case AAUDIO_SERVICE_EVENT_STOPPED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700469 ALOGD("%s - got AAUDIO_SERVICE_EVENT_STOPPED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700470 if (getState() == AAUDIO_STREAM_STATE_STOPPING) {
471 setState(AAUDIO_STREAM_STATE_STOPPED);
472 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700473 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800474 case AAUDIO_SERVICE_EVENT_FLUSHED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700475 ALOGD("%s - got AAUDIO_SERVICE_EVENT_FLUSHED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700476 if (getState() == AAUDIO_STREAM_STATE_FLUSHING) {
477 setState(AAUDIO_STREAM_STATE_FLUSHED);
478 onFlushFromServer();
479 }
Phil Burk204a1632017-01-03 17:23:43 -0800480 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800481 case AAUDIO_SERVICE_EVENT_DISCONNECTED:
Phil Burkea04d972017-08-07 12:30:44 -0700482 // Prevent hardware from looping on old data and making buzzing sounds.
483 if (getDirection() == AAUDIO_DIRECTION_OUTPUT) {
484 mAudioEndpoint.eraseDataMemory();
485 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800486 result = AAUDIO_ERROR_DISCONNECTED;
Phil Burkc0c70e32017-02-09 13:18:38 -0800487 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
Phil Burkfbf031e2017-10-12 15:58:31 -0700488 ALOGW("%s - AAUDIO_SERVICE_EVENT_DISCONNECTED - FIFO cleared", __func__);
Phil Burk204a1632017-01-03 17:23:43 -0800489 break;
Phil Burkc0c70e32017-02-09 13:18:38 -0800490 case AAUDIO_SERVICE_EVENT_VOLUME:
Eric Laurenta2f296e2017-06-21 18:51:47 -0700491 mStreamVolume = (float)message->event.dataDouble;
492 doSetVolume();
Phil Burkfbf031e2017-10-12 15:58:31 -0700493 ALOGD("%s - AAUDIO_SERVICE_EVENT_VOLUME %lf", __func__, message->event.dataDouble);
Phil Burkc0c70e32017-02-09 13:18:38 -0800494 break;
Phil Burk23296382017-11-20 15:45:11 -0800495 case AAUDIO_SERVICE_EVENT_XRUN:
496 mXRunCount = static_cast<int32_t>(message->event.dataLong);
497 break;
Phil Burk204a1632017-01-03 17:23:43 -0800498 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700499 ALOGE("%s - Unrecognized event = %d", __func__, (int) message->event.event);
Phil Burk204a1632017-01-03 17:23:43 -0800500 break;
501 }
502 return result;
503}
504
Phil Burkbcc36742017-08-31 17:24:51 -0700505aaudio_result_t AudioStreamInternal::drainTimestampsFromService() {
506 aaudio_result_t result = AAUDIO_OK;
507
508 while (result == AAUDIO_OK) {
509 AAudioServiceMessage message;
510 if (mAudioEndpoint.readUpCommand(&message) != 1) {
511 break; // no command this time, no problem
512 }
513 switch (message.what) {
514 // ignore most messages
515 case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
516 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
517 break;
518
519 case AAudioServiceMessage::code::EVENT:
520 result = onEventFromServer(&message);
521 break;
522
523 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700524 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
Phil Burkbcc36742017-08-31 17:24:51 -0700525 result = AAUDIO_ERROR_INTERNAL;
526 break;
527 }
528 }
529 return result;
530}
531
Phil Burk204a1632017-01-03 17:23:43 -0800532// Process all the commands coming from the server.
Phil Burk5ed503c2017-02-01 09:38:15 -0800533aaudio_result_t AudioStreamInternal::processCommands() {
534 aaudio_result_t result = AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800535
Phil Burk5ed503c2017-02-01 09:38:15 -0800536 while (result == AAUDIO_OK) {
537 AAudioServiceMessage message;
Phil Burk204a1632017-01-03 17:23:43 -0800538 if (mAudioEndpoint.readUpCommand(&message) != 1) {
539 break; // no command this time, no problem
540 }
541 switch (message.what) {
Phil Burk97350f92017-07-21 15:59:44 -0700542 case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
543 result = onTimestampService(&message);
544 break;
545
546 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
547 result = onTimestampHardware(&message);
Phil Burk204a1632017-01-03 17:23:43 -0800548 break;
549
Phil Burk5ed503c2017-02-01 09:38:15 -0800550 case AAudioServiceMessage::code::EVENT:
Phil Burk204a1632017-01-03 17:23:43 -0800551 result = onEventFromServer(&message);
552 break;
553
554 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700555 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
Phil Burk17fff382017-05-16 14:06:45 -0700556 result = AAUDIO_ERROR_INTERNAL;
Phil Burk204a1632017-01-03 17:23:43 -0800557 break;
558 }
559 }
560 return result;
561}
562
Phil Burk87c9f642017-05-17 07:22:39 -0700563// Read or write the data, block if needed and timeoutMillis > 0
564aaudio_result_t AudioStreamInternal::processData(void *buffer, int32_t numFrames,
565 int64_t timeoutNanoseconds)
Phil Burk204a1632017-01-03 17:23:43 -0800566{
Phil Burkfd34a932017-07-19 07:03:52 -0700567 const char * traceName = "aaProc";
568 const char * fifoName = "aaRdy";
Phil Burk4485d412017-05-09 15:55:02 -0700569 ATRACE_BEGIN(traceName);
Phil Burk4485d412017-05-09 15:55:02 -0700570 if (ATRACE_ENABLED()) {
Phil Burkfd34a932017-07-19 07:03:52 -0700571 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable();
572 ATRACE_INT(fifoName, fullFrames);
Phil Burk4485d412017-05-09 15:55:02 -0700573 }
574
Phil Burkec89b2e2017-06-20 15:05:06 -0700575 aaudio_result_t result = AAUDIO_OK;
576 int32_t loopCount = 0;
577 uint8_t* audioData = (uint8_t*)buffer;
578 int64_t currentTimeNanos = AudioClock::getNanoseconds();
579 const int64_t entryTimeNanos = currentTimeNanos;
580 const int64_t deadlineNanos = currentTimeNanos + timeoutNanoseconds;
581 int32_t framesLeft = numFrames;
582
Phil Burk87c9f642017-05-17 07:22:39 -0700583 // Loop until all the data has been processed or until a timeout occurs.
Phil Burk204a1632017-01-03 17:23:43 -0800584 while (framesLeft > 0) {
Phil Burkec89b2e2017-06-20 15:05:06 -0700585 // The call to processDataNow() will not block. It will just process as much as it can.
Phil Burk3316d5e2017-02-15 11:23:01 -0800586 int64_t wakeTimeNanos = 0;
Phil Burk87c9f642017-05-17 07:22:39 -0700587 aaudio_result_t framesProcessed = processDataNow(audioData, framesLeft,
588 currentTimeNanos, &wakeTimeNanos);
589 if (framesProcessed < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700590 result = framesProcessed;
Phil Burk204a1632017-01-03 17:23:43 -0800591 break;
592 }
Phil Burk87c9f642017-05-17 07:22:39 -0700593 framesLeft -= (int32_t) framesProcessed;
594 audioData += framesProcessed * getBytesPerFrame();
Phil Burk204a1632017-01-03 17:23:43 -0800595
596 // Should we block?
597 if (timeoutNanoseconds == 0) {
598 break; // don't block
599 } else if (framesLeft > 0) {
Phil Burkfd34a932017-07-19 07:03:52 -0700600 if (!mAudioEndpoint.isFreeRunning()) {
601 // If there is software on the other end of the FIFO then it may get delayed.
602 // So wake up just a little after we expect it to be ready.
603 wakeTimeNanos += mWakeupDelayNanos;
Phil Burk204a1632017-01-03 17:23:43 -0800604 }
Phil Burkfd34a932017-07-19 07:03:52 -0700605
Phil Burk2bc7c182017-08-28 11:45:01 -0700606 currentTimeNanos = AudioClock::getNanoseconds();
607 int64_t earliestWakeTime = currentTimeNanos + mMinimumSleepNanos;
608 // Guarantee a minimum sleep time.
609 if (wakeTimeNanos < earliestWakeTime) {
610 wakeTimeNanos = earliestWakeTime;
611 }
612
Phil Burk204a1632017-01-03 17:23:43 -0800613 if (wakeTimeNanos > deadlineNanos) {
614 // If we time out, just return the framesWritten so far.
Phil Burkcf5f6d22017-05-26 12:35:07 -0700615 // TODO remove after we fix the deadline bug
Phil Burkfbf031e2017-10-12 15:58:31 -0700616 ALOGW("processData(): entered at %lld nanos, currently %lld",
Phil Burkec89b2e2017-06-20 15:05:06 -0700617 (long long) entryTimeNanos, (long long) currentTimeNanos);
Phil Burkfbf031e2017-10-12 15:58:31 -0700618 ALOGW("processData(): TIMEOUT after %lld nanos",
Phil Burkc0c70e32017-02-09 13:18:38 -0800619 (long long) timeoutNanoseconds);
Phil Burkfbf031e2017-10-12 15:58:31 -0700620 ALOGW("processData(): wakeTime = %lld, deadline = %lld nanos",
Phil Burk87c9f642017-05-17 07:22:39 -0700621 (long long) wakeTimeNanos, (long long) deadlineNanos);
Phil Burkfbf031e2017-10-12 15:58:31 -0700622 ALOGW("processData(): past deadline by %d micros",
Phil Burk87c9f642017-05-17 07:22:39 -0700623 (int)((wakeTimeNanos - deadlineNanos) / AAUDIO_NANOS_PER_MICROSECOND));
Phil Burkec89b2e2017-06-20 15:05:06 -0700624 mClockModel.dump();
625 mAudioEndpoint.dump();
Phil Burk204a1632017-01-03 17:23:43 -0800626 break;
627 }
628
Phil Burkfd34a932017-07-19 07:03:52 -0700629 if (ATRACE_ENABLED()) {
630 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable();
631 ATRACE_INT(fifoName, fullFrames);
632 int64_t sleepForNanos = wakeTimeNanos - currentTimeNanos;
633 ATRACE_INT("aaSlpNs", (int32_t)sleepForNanos);
634 }
635
636 AudioClock::sleepUntilNanoTime(wakeTimeNanos);
Phil Burk204a1632017-01-03 17:23:43 -0800637 currentTimeNanos = AudioClock::getNanoseconds();
638 }
639 }
640
Phil Burkfd34a932017-07-19 07:03:52 -0700641 if (ATRACE_ENABLED()) {
642 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable();
643 ATRACE_INT(fifoName, fullFrames);
644 }
645
Phil Burk87c9f642017-05-17 07:22:39 -0700646 // return error or framesProcessed
Phil Burkc0c70e32017-02-09 13:18:38 -0800647 (void) loopCount;
Phil Burk4485d412017-05-09 15:55:02 -0700648 ATRACE_END();
Phil Burk204a1632017-01-03 17:23:43 -0800649 return (result < 0) ? result : numFrames - framesLeft;
650}
651
Phil Burk3316d5e2017-02-15 11:23:01 -0800652void AudioStreamInternal::processTimestamp(uint64_t position, int64_t time) {
Phil Burk87c9f642017-05-17 07:22:39 -0700653 mClockModel.processTimestamp(position, time);
Phil Burk204a1632017-01-03 17:23:43 -0800654}
655
Phil Burk3316d5e2017-02-15 11:23:01 -0800656aaudio_result_t AudioStreamInternal::setBufferSize(int32_t requestedFrames) {
Phil Burk6479d502017-11-20 09:32:52 -0800657 int32_t adjustedFrames = requestedFrames;
Phil Burk3316d5e2017-02-15 11:23:01 -0800658 int32_t actualFrames = 0;
Phil Burk6479d502017-11-20 09:32:52 -0800659 int32_t maximumSize = getBufferCapacity();
660
661 // Clip to minimum size so that rounding up will work better.
662 if (adjustedFrames < 1) {
663 adjustedFrames = 1;
Phil Burk71f35bb2017-04-13 16:05:07 -0700664 }
665
Phil Burk6479d502017-11-20 09:32:52 -0800666 if (adjustedFrames > maximumSize) {
667 // Clip to maximum size.
668 adjustedFrames = maximumSize;
669 } else {
670 // Round to the next highest burst size.
671 int32_t numBursts = (adjustedFrames + mFramesPerBurst - 1) / mFramesPerBurst;
672 adjustedFrames = numBursts * mFramesPerBurst;
673 // Rounding may have gone above maximum.
674 if (adjustedFrames > maximumSize) {
675 adjustedFrames = maximumSize;
676 }
677 }
678
679 aaudio_result_t result = mAudioEndpoint.setBufferSizeInFrames(adjustedFrames, &actualFrames);
Phil Burkbcc36742017-08-31 17:24:51 -0700680 ALOGD("setBufferSize() req = %d => %d", requestedFrames, actualFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800681 if (result < 0) {
682 return result;
683 } else {
684 return (aaudio_result_t) actualFrames;
685 }
Phil Burk204a1632017-01-03 17:23:43 -0800686}
687
Phil Burk87c9f642017-05-17 07:22:39 -0700688int32_t AudioStreamInternal::getBufferSize() const {
Phil Burk204a1632017-01-03 17:23:43 -0800689 return mAudioEndpoint.getBufferSizeInFrames();
690}
691
Phil Burk87c9f642017-05-17 07:22:39 -0700692int32_t AudioStreamInternal::getBufferCapacity() const {
Phil Burk204a1632017-01-03 17:23:43 -0800693 return mAudioEndpoint.getBufferCapacityInFrames();
694}
695
Phil Burk87c9f642017-05-17 07:22:39 -0700696int32_t AudioStreamInternal::getFramesPerBurst() const {
Phil Burk6479d502017-11-20 09:32:52 -0800697 return mFramesPerBurst;
Phil Burk204a1632017-01-03 17:23:43 -0800698}
699
Phil Burk87c9f642017-05-17 07:22:39 -0700700aaudio_result_t AudioStreamInternal::joinThread(void** returnArg) {
701 return AudioStream::joinThread(returnArg, calculateReasonableTimeout(getFramesPerBurst()));
Phil Burk4c5129b2017-04-28 15:17:32 -0700702}