blob: 6723ec92251de38b1a2d08f82778348673b7db83 [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
Phil Burkc0c70e32017-02-09 13:18:38 -080043#include "AudioStreamInternal.h"
Phil Burk204a1632017-01-03 17:23:43 -080044
Phil Burk204a1632017-01-03 17:23:43 -080045using android::String16;
Phil Burkdec33ab2017-01-17 14:48:16 -080046using android::Mutex;
Phil Burkc0c70e32017-02-09 13:18:38 -080047using android::WrappingBuffer;
Phil Burk204a1632017-01-03 17:23:43 -080048
Phil Burk5ed503c2017-02-01 09:38:15 -080049using namespace aaudio;
Phil Burk204a1632017-01-03 17:23:43 -080050
Phil Burke4d7bb42017-03-28 11:32:39 -070051#define MIN_TIMEOUT_NANOS (1000 * AAUDIO_NANOS_PER_MILLISECOND)
52
53// Wait at least this many times longer than the operation should take.
54#define MIN_TIMEOUT_OPERATIONS 4
55
Phil Burkbcc36742017-08-31 17:24:51 -070056#define LOG_TIMESTAMPS 0
Phil Burk87c9f642017-05-17 07:22:39 -070057
Phil Burkc0c70e32017-02-09 13:18:38 -080058AudioStreamInternal::AudioStreamInternal(AAudioServiceInterface &serviceInterface, bool inService)
Phil Burk204a1632017-01-03 17:23:43 -080059 : AudioStream()
60 , mClockModel()
61 , mAudioEndpoint()
Phil Burk5ed503c2017-02-01 09:38:15 -080062 , mServiceStreamHandle(AAUDIO_HANDLE_INVALID)
Phil Burkec89b2e2017-06-20 15:05:06 -070063 , mInService(inService)
Phil Burkfd34a932017-07-19 07:03:52 -070064 , mServiceInterface(serviceInterface)
Phil Burka53ffa62018-10-10 16:21:37 -070065 , mAtomicInternalTimestamp()
Phil Burkfd34a932017-07-19 07:03:52 -070066 , mWakeupDelayNanos(AAudioProperty_getWakeupDelayMicros() * AAUDIO_NANOS_PER_MICROSECOND)
67 , mMinimumSleepNanos(AAudioProperty_getMinimumSleepMicros() * AAUDIO_NANOS_PER_MICROSECOND)
68 {
Phil Burk204a1632017-01-03 17:23:43 -080069}
70
71AudioStreamInternal::~AudioStreamInternal() {
72}
73
Phil Burk5ed503c2017-02-01 09:38:15 -080074aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) {
Phil Burk204a1632017-01-03 17:23:43 -080075
Phil Burk5ed503c2017-02-01 09:38:15 -080076 aaudio_result_t result = AAUDIO_OK;
Phil Burk99306c82017-08-14 12:38:58 -070077 int32_t capacity;
Phil Burk6479d502017-11-20 09:32:52 -080078 int32_t framesPerBurst;
Phil Burk3c4e6b52019-01-22 15:53:36 -080079 int32_t framesPerHardwareBurst;
Phil Burk5ed503c2017-02-01 09:38:15 -080080 AAudioStreamRequest request;
Phil Burk99306c82017-08-14 12:38:58 -070081 AAudioStreamConfiguration configurationOutput;
Phil Burk204a1632017-01-03 17:23:43 -080082
Phil Burk99306c82017-08-14 12:38:58 -070083 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
Phil Burkfbf031e2017-10-12 15:58:31 -070084 ALOGE("%s - already open! state = %d", __func__, getState());
Phil Burk99306c82017-08-14 12:38:58 -070085 return AAUDIO_ERROR_INVALID_STATE;
86 }
87
88 // Copy requested parameters to the stream.
Phil Burk204a1632017-01-03 17:23:43 -080089 result = AudioStream::open(builder);
90 if (result < 0) {
91 return result;
92 }
93
Phil Burk3c4e6b52019-01-22 15:53:36 -080094 const int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
95 int32_t burstMicros = 0;
96
Phil Burkc0c70e32017-02-09 13:18:38 -080097 // We have to do volume scaling. So we prefer FLOAT format.
Phil Burk0127c1b2018-03-29 13:48:06 -070098 if (getFormat() == AUDIO_FORMAT_DEFAULT) {
99 setFormat(AUDIO_FORMAT_PCM_FLOAT);
Phil Burkc0c70e32017-02-09 13:18:38 -0800100 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700101 // Request FLOAT for the shared mixer.
Phil Burk0127c1b2018-03-29 13:48:06 -0700102 request.getConfiguration().setFormat(AUDIO_FORMAT_PCM_FLOAT);
Phil Burkc0c70e32017-02-09 13:18:38 -0800103
Phil Burkdec33ab2017-01-17 14:48:16 -0800104 // Build the request to send to the server.
Phil Burk204a1632017-01-03 17:23:43 -0800105 request.setUserId(getuid());
106 request.setProcessId(getpid());
Phil Burk71f35bb2017-04-13 16:05:07 -0700107 request.setSharingModeMatchRequired(isSharingModeMatchRequired());
Phil Burk41f19d82018-02-13 14:59:10 -0800108 request.setInService(isInService());
Phil Burkc0c70e32017-02-09 13:18:38 -0800109
Phil Burk204a1632017-01-03 17:23:43 -0800110 request.getConfiguration().setDeviceId(getDeviceId());
111 request.getConfiguration().setSampleRate(getSampleRate());
112 request.getConfiguration().setSamplesPerFrame(getSamplesPerFrame());
Phil Burk39f02dd2017-08-04 09:13:31 -0700113 request.getConfiguration().setDirection(getDirection());
Phil Burk71f35bb2017-04-13 16:05:07 -0700114 request.getConfiguration().setSharingMode(getSharingMode());
115
Phil Burka62fb952018-01-16 12:44:06 -0800116 request.getConfiguration().setUsage(getUsage());
117 request.getConfiguration().setContentType(getContentType());
118 request.getConfiguration().setInputPreset(getInputPreset());
Eric Laurentd17c8502019-10-24 15:58:35 -0700119 request.getConfiguration().setPrivacySensitive(isPrivacySensitive());
Phil Burka62fb952018-01-16 12:44:06 -0800120
Phil Burk3df348f2017-02-08 11:41:55 -0800121 request.getConfiguration().setBufferCapacity(builder.getBufferCapacity());
Phil Burk204a1632017-01-03 17:23:43 -0800122
Phil Burk41f19d82018-02-13 14:59:10 -0800123 mDeviceChannelCount = getSamplesPerFrame(); // Assume it will be the same. Update if not.
124
Phil Burk99306c82017-08-14 12:38:58 -0700125 mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
Phil Burk41f19d82018-02-13 14:59:10 -0800126 if (mServiceStreamHandle < 0
127 && request.getConfiguration().getSamplesPerFrame() == 1 // mono?
128 && getDirection() == AAUDIO_DIRECTION_OUTPUT
129 && !isInService()) {
130 // if that failed then try switching from mono to stereo if OUTPUT.
131 // Only do this in the client. Otherwise we end up with a mono mixer in the service
132 // that writes to a stereo MMAP stream.
Phil Burk0127c1b2018-03-29 13:48:06 -0700133 ALOGD("%s() - openStream() returned %d, try switching from MONO to STEREO",
Phil Burk41f19d82018-02-13 14:59:10 -0800134 __func__, mServiceStreamHandle);
135 request.getConfiguration().setSamplesPerFrame(2); // stereo
136 mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
137 }
Phil Burk204a1632017-01-03 17:23:43 -0800138 if (mServiceStreamHandle < 0) {
Phil Burk41f19d82018-02-13 14:59:10 -0800139 return mServiceStreamHandle;
Phil Burk204a1632017-01-03 17:23:43 -0800140 }
Phil Burk99306c82017-08-14 12:38:58 -0700141
142 result = configurationOutput.validate();
143 if (result != AAUDIO_OK) {
144 goto error;
145 }
146 // Save results of the open.
Phil Burk41f19d82018-02-13 14:59:10 -0800147 if (getSamplesPerFrame() == AAUDIO_UNSPECIFIED) {
148 setSamplesPerFrame(configurationOutput.getSamplesPerFrame());
149 }
150 mDeviceChannelCount = configurationOutput.getSamplesPerFrame();
151
Phil Burk99306c82017-08-14 12:38:58 -0700152 setSampleRate(configurationOutput.getSampleRate());
Phil Burk99306c82017-08-14 12:38:58 -0700153 setDeviceId(configurationOutput.getDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800154 setSessionId(configurationOutput.getSessionId());
Phil Burk99306c82017-08-14 12:38:58 -0700155 setSharingMode(configurationOutput.getSharingMode());
156
Phil Burka62fb952018-01-16 12:44:06 -0800157 setUsage(configurationOutput.getUsage());
158 setContentType(configurationOutput.getContentType());
159 setInputPreset(configurationOutput.getInputPreset());
160
Phil Burk99306c82017-08-14 12:38:58 -0700161 // Save device format so we can do format conversion and volume scaling together.
Phil Burk3d786cb2018-04-09 11:58:09 -0700162 setDeviceFormat(configurationOutput.getFormat());
Phil Burk99306c82017-08-14 12:38:58 -0700163
164 result = mServiceInterface.getStreamDescription(mServiceStreamHandle, mEndPointParcelable);
165 if (result != AAUDIO_OK) {
166 goto error;
167 }
168
169 // Resolve parcelable into a descriptor.
170 result = mEndPointParcelable.resolve(&mEndpointDescriptor);
171 if (result != AAUDIO_OK) {
172 goto error;
173 }
174
175 // Configure endpoint based on descriptor.
176 result = mAudioEndpoint.configure(&mEndpointDescriptor, getDirection());
177 if (result != AAUDIO_OK) {
178 goto error;
179 }
180
Phil Burk3c4e6b52019-01-22 15:53:36 -0800181 framesPerHardwareBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst;
182
183 // Scale up the burst size to meet the minimum equivalent in microseconds.
184 // This is to avoid waking the CPU too often when the HW burst is very small
185 // or at high sample rates.
186 framesPerBurst = framesPerHardwareBurst;
187 do {
188 if (burstMicros > 0) { // skip first loop
189 framesPerBurst *= 2;
190 }
191 burstMicros = framesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
192 } while (burstMicros < burstMinMicros);
193 ALOGD("%s() original HW burst = %d, minMicros = %d => SW burst = %d\n",
194 __func__, framesPerHardwareBurst, burstMinMicros, framesPerBurst);
195
196 // Validate final burst size.
Phil Burk6479d502017-11-20 09:32:52 -0800197 if (framesPerBurst < MIN_FRAMES_PER_BURST || framesPerBurst > MAX_FRAMES_PER_BURST) {
198 ALOGE("%s - framesPerBurst out of range = %d", __func__, framesPerBurst);
Phil Burk99306c82017-08-14 12:38:58 -0700199 result = AAUDIO_ERROR_OUT_OF_RANGE;
200 goto error;
201 }
Phil Burk6479d502017-11-20 09:32:52 -0800202 mFramesPerBurst = framesPerBurst; // only save good value
203
204 capacity = mEndpointDescriptor.dataQueueDescriptor.capacityInFrames;
205 if (capacity < mFramesPerBurst || capacity > MAX_BUFFER_CAPACITY_IN_FRAMES) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700206 ALOGE("%s - bufferCapacity out of range = %d", __func__, capacity);
Phil Burk99306c82017-08-14 12:38:58 -0700207 result = AAUDIO_ERROR_OUT_OF_RANGE;
208 goto error;
209 }
210
211 mClockModel.setSampleRate(getSampleRate());
Phil Burk3c4e6b52019-01-22 15:53:36 -0800212 mClockModel.setFramesPerBurst(framesPerHardwareBurst);
Phil Burk99306c82017-08-14 12:38:58 -0700213
Phil Burk134f1972017-12-08 13:06:11 -0800214 if (isDataCallbackSet()) {
Phil Burk99306c82017-08-14 12:38:58 -0700215 mCallbackFrames = builder.getFramesPerDataCallback();
216 if (mCallbackFrames > getBufferCapacity() / 2) {
Phil Burk29ccc292019-04-15 08:58:08 -0700217 ALOGW("%s - framesPerCallback too big = %d, capacity = %d",
Phil Burkfbf031e2017-10-12 15:58:31 -0700218 __func__, mCallbackFrames, getBufferCapacity());
Phil Burk99306c82017-08-14 12:38:58 -0700219 result = AAUDIO_ERROR_OUT_OF_RANGE;
220 goto error;
221
222 } else if (mCallbackFrames < 0) {
Phil Burk29ccc292019-04-15 08:58:08 -0700223 ALOGW("%s - framesPerCallback negative", __func__);
Phil Burk99306c82017-08-14 12:38:58 -0700224 result = AAUDIO_ERROR_OUT_OF_RANGE;
225 goto error;
226
227 }
228 if (mCallbackFrames == AAUDIO_UNSPECIFIED) {
229 mCallbackFrames = mFramesPerBurst;
230 }
231
Phil Burk0127c1b2018-03-29 13:48:06 -0700232 const int32_t callbackBufferSize = mCallbackFrames * getBytesPerFrame();
Phil Burk99306c82017-08-14 12:38:58 -0700233 mCallbackBuffer = new uint8_t[callbackBufferSize];
234 }
235
Phil Burkb31b66f2019-09-30 09:33:41 -0700236 // For debugging and analyzing the distribution of MMAP timestamps.
237 // For OUTPUT, use a NEGATIVE offset to move the CPU writes further BEFORE the HW reads.
238 // For INPUT, use a POSITIVE offset to move the CPU reads further AFTER the HW writes.
239 // You can use this offset to reduce glitching.
240 // You can also use this offset to force glitching. By iterating over multiple
241 // values you can reveal the distribution of the hardware timing jitter.
242 if (mAudioEndpoint.isFreeRunning()) { // MMAP?
243 int32_t offsetMicros = (getDirection() == AAUDIO_DIRECTION_OUTPUT)
244 ? AAudioProperty_getOutputMMapOffsetMicros()
245 : AAudioProperty_getInputMMapOffsetMicros();
246 // This log is used to debug some tricky glitch issues. Please leave.
247 ALOGD_IF(offsetMicros, "%s() - %s mmap offset = %d micros",
248 __func__,
249 (getDirection() == AAUDIO_DIRECTION_OUTPUT) ? "output" : "input",
250 offsetMicros);
251 mTimeOffsetNanos = offsetMicros * AAUDIO_NANOS_PER_MICROSECOND;
252 }
253
Phil Burk6c63ae32019-10-28 10:28:21 -0700254 setBufferSize(capacity / 2); // Default buffer size to match Q
255
Phil Burk99306c82017-08-14 12:38:58 -0700256 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burk99306c82017-08-14 12:38:58 -0700257
258 return result;
259
260error:
Phil Burk8b4e05e2019-12-17 12:12:09 -0800261 releaseCloseFinal();
Phil Burk204a1632017-01-03 17:23:43 -0800262 return result;
263}
264
Phil Burk13d3d832019-06-10 14:36:48 -0700265// This must be called under mStreamLock.
Phil Burk8b4e05e2019-12-17 12:12:09 -0800266aaudio_result_t AudioStreamInternal::release_l() {
Phil Burk965650e2017-09-07 21:00:09 -0700267 aaudio_result_t result = AAUDIO_OK;
Phil Burk29ccc292019-04-15 08:58:08 -0700268 ALOGV("%s(): mServiceStreamHandle = 0x%08X", __func__, mServiceStreamHandle);
Phil Burk5ed503c2017-02-01 09:38:15 -0800269 if (mServiceStreamHandle != AAUDIO_HANDLE_INVALID) {
Phil Burk4485d412017-05-09 15:55:02 -0700270 aaudio_stream_state_t currentState = getState();
Phil Burk8b4e05e2019-12-17 12:12:09 -0800271 // Don't release a stream while it is running. Stop it first.
Phil Burk13d3d832019-06-10 14:36:48 -0700272 // If DISCONNECTED then we should still try to stop in case the
273 // error callback is still running.
274 if (isActive() || currentState == AAUDIO_STREAM_STATE_DISCONNECTED) {
Phil Burk4485d412017-05-09 15:55:02 -0700275 requestStop();
Phil Burk4485d412017-05-09 15:55:02 -0700276 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700277 setState(AAUDIO_STREAM_STATE_CLOSING);
Phil Burk5ed503c2017-02-01 09:38:15 -0800278 aaudio_handle_t serviceStreamHandle = mServiceStreamHandle;
279 mServiceStreamHandle = AAUDIO_HANDLE_INVALID;
Phil Burkc0c70e32017-02-09 13:18:38 -0800280
281 mServiceInterface.closeStream(serviceStreamHandle);
Phil Burke4d7bb42017-03-28 11:32:39 -0700282 delete[] mCallbackBuffer;
Phil Burk4485d412017-05-09 15:55:02 -0700283 mCallbackBuffer = nullptr;
Phil Burk965650e2017-09-07 21:00:09 -0700284 result = mEndPointParcelable.close();
Phil Burk8b4e05e2019-12-17 12:12:09 -0800285 aaudio_result_t result2 = AudioStream::release_l();
Phil Burk965650e2017-09-07 21:00:09 -0700286 return (result != AAUDIO_OK) ? result : result2;
Phil Burk204a1632017-01-03 17:23:43 -0800287 } else {
Phil Burk5ed503c2017-02-01 09:38:15 -0800288 return AAUDIO_ERROR_INVALID_HANDLE;
Phil Burk204a1632017-01-03 17:23:43 -0800289 }
290}
291
Phil Burke4d7bb42017-03-28 11:32:39 -0700292static void *aaudio_callback_thread_proc(void *context)
293{
294 AudioStreamInternal *stream = (AudioStreamInternal *)context;
Phil Burkfbf031e2017-10-12 15:58:31 -0700295 //LOGD("oboe_callback_thread, stream = %p", stream);
Phil Burke4d7bb42017-03-28 11:32:39 -0700296 if (stream != NULL) {
297 return stream->callbackLoop();
298 } else {
299 return NULL;
300 }
301}
302
Phil Burkbcc36742017-08-31 17:24:51 -0700303/*
304 * It normally takes about 20-30 msec to start a stream on the server.
305 * But the first time can take as much as 200-300 msec. The HW
306 * starts right away so by the time the client gets a chance to write into
307 * the buffer, it is already in a deep underflow state. That can cause the
308 * XRunCount to be non-zero, which could lead an app to tune its latency higher.
309 * To avoid this problem, we set a request for the processing code to start the
310 * client stream at the same position as the server stream.
311 * The processing code will then save the current offset
312 * between client and server and apply that to any position given to the app.
313 */
Phil Burk5ed503c2017-02-01 09:38:15 -0800314aaudio_result_t AudioStreamInternal::requestStart()
Phil Burk204a1632017-01-03 17:23:43 -0800315{
Phil Burk3316d5e2017-02-15 11:23:01 -0800316 int64_t startTime;
Phil Burk5ed503c2017-02-01 09:38:15 -0800317 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700318 ALOGD("requestStart() mServiceStreamHandle invalid");
Phil Burk5ed503c2017-02-01 09:38:15 -0800319 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800320 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700321 if (isActive()) {
Phil Burk29ccc292019-04-15 08:58:08 -0700322 ALOGD("requestStart() already active");
Phil Burkec89b2e2017-06-20 15:05:06 -0700323 return AAUDIO_ERROR_INVALID_STATE;
324 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700325
Phil Burkbcc36742017-08-31 17:24:51 -0700326 aaudio_stream_state_t originalState = getState();
327 if (originalState == AAUDIO_STREAM_STATE_DISCONNECTED) {
Phil Burk29ccc292019-04-15 08:58:08 -0700328 ALOGD("requestStart() but DISCONNECTED");
Phil Burkbcc36742017-08-31 17:24:51 -0700329 return AAUDIO_ERROR_DISCONNECTED;
330 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700331 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burkbcc36742017-08-31 17:24:51 -0700332
333 // Clear any stale timestamps from the previous run.
334 drainTimestampsFromService();
335
Phil Burk965650e2017-09-07 21:00:09 -0700336 aaudio_result_t result = mServiceInterface.startStream(mServiceStreamHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800337
Phil Burk3316d5e2017-02-15 11:23:01 -0800338 startTime = AudioClock::getNanoseconds();
Phil Burk204a1632017-01-03 17:23:43 -0800339 mClockModel.start(startTime);
Phil Burkbcc36742017-08-31 17:24:51 -0700340 mNeedCatchUp.request(); // Ask data processing code to catch up when first timestamp received.
Phil Burke4d7bb42017-03-28 11:32:39 -0700341
Phil Burk965650e2017-09-07 21:00:09 -0700342 // Start data callback thread.
Phil Burk134f1972017-12-08 13:06:11 -0800343 if (result == AAUDIO_OK && isDataCallbackSet()) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700344 // Launch the callback loop thread.
345 int64_t periodNanos = mCallbackFrames
346 * AAUDIO_NANOS_PER_SECOND
347 / getSampleRate();
348 mCallbackEnabled.store(true);
349 result = createThread(periodNanos, aaudio_callback_thread_proc, this);
350 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700351 if (result != AAUDIO_OK) {
352 setState(originalState);
353 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700354 return result;
Phil Burk204a1632017-01-03 17:23:43 -0800355}
356
Phil Burke4d7bb42017-03-28 11:32:39 -0700357int64_t AudioStreamInternal::calculateReasonableTimeout(int32_t framesPerOperation) {
358
359 // Wait for at least a second or some number of callbacks to join the thread.
Phil Burk71f35bb2017-04-13 16:05:07 -0700360 int64_t timeoutNanoseconds = (MIN_TIMEOUT_OPERATIONS
361 * framesPerOperation
362 * AAUDIO_NANOS_PER_SECOND)
363 / getSampleRate();
Phil Burke4d7bb42017-03-28 11:32:39 -0700364 if (timeoutNanoseconds < MIN_TIMEOUT_NANOS) { // arbitrary number of seconds
365 timeoutNanoseconds = MIN_TIMEOUT_NANOS;
366 }
367 return timeoutNanoseconds;
368}
369
Phil Burk87c9f642017-05-17 07:22:39 -0700370int64_t AudioStreamInternal::calculateReasonableTimeout() {
371 return calculateReasonableTimeout(getFramesPerBurst());
372}
373
Phil Burk13d3d832019-06-10 14:36:48 -0700374// This must be called under mStreamLock.
Phil Burke4d7bb42017-03-28 11:32:39 -0700375aaudio_result_t AudioStreamInternal::stopCallback()
376{
Phil Burk13d3d832019-06-10 14:36:48 -0700377 if (isDataCallbackSet()
378 && (isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700379 mCallbackEnabled.store(false);
Phil Burk13d3d832019-06-10 14:36:48 -0700380 return joinThread(NULL); // may temporarily unlock mStreamLock
Phil Burke4d7bb42017-03-28 11:32:39 -0700381 } else {
382 return AAUDIO_OK;
383 }
384}
385
Phil Burk13d3d832019-06-10 14:36:48 -0700386// This must be called under mStreamLock.
Phil Burk1e83bee2018-12-17 14:15:20 -0800387aaudio_result_t AudioStreamInternal::requestStop() {
Phil Burk5cc83c32017-11-28 15:43:18 -0800388 aaudio_result_t result = stopCallback();
389 if (result != AAUDIO_OK) {
390 return result;
391 }
Phil Burk13d3d832019-06-10 14:36:48 -0700392 // The stream may have been unlocked temporarily to let a callback finish
393 // and the callback may have stopped the stream.
394 // Check to make sure the stream still needs to be stopped.
395 // See also AudioStream::safeStop().
396 if (!(isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) {
397 return AAUDIO_OK;
398 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800399
Phil Burk71f35bb2017-04-13 16:05:07 -0700400 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700401 ALOGW("%s() mServiceStreamHandle invalid = 0x%08X",
402 __func__, mServiceStreamHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700403 return AAUDIO_ERROR_INVALID_STATE;
404 }
405
406 mClockModel.stop(AudioClock::getNanoseconds());
407 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burka53ffa62018-10-10 16:21:37 -0700408 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -0700409
410 return mServiceInterface.stopStream(mServiceStreamHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700411}
412
Phil Burk5ed503c2017-02-01 09:38:15 -0800413aaudio_result_t AudioStreamInternal::registerThread() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800414 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700415 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800416 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800417 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800418 return mServiceInterface.registerAudioThread(mServiceStreamHandle,
Phil Burkc0c70e32017-02-09 13:18:38 -0800419 gettid(),
420 getPeriodNanoseconds());
Phil Burk204a1632017-01-03 17:23:43 -0800421}
422
Phil Burk5ed503c2017-02-01 09:38:15 -0800423aaudio_result_t AudioStreamInternal::unregisterThread() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800424 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700425 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800426 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800427 }
Phil Burk2ac035f2017-06-23 14:51:14 -0700428 return mServiceInterface.unregisterAudioThread(mServiceStreamHandle, gettid());
Phil Burk204a1632017-01-03 17:23:43 -0800429}
430
Eric Laurentcb4dae22017-07-01 19:39:32 -0700431aaudio_result_t AudioStreamInternal::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700432 const audio_attributes_t *attr,
Phil Burkbbd52862018-04-13 11:37:42 -0700433 audio_port_handle_t *portHandle) {
434 ALOGV("%s() called", __func__);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700435 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
436 return AAUDIO_ERROR_INVALID_STATE;
437 }
Phil Burkbbd52862018-04-13 11:37:42 -0700438 aaudio_result_t result = mServiceInterface.startClient(mServiceStreamHandle,
jiabind1f1cb62020-03-24 11:57:57 -0700439 client, attr, portHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700440 ALOGV("%s(%d) returning %d", __func__, *portHandle, result);
441 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700442}
443
Phil Burkbbd52862018-04-13 11:37:42 -0700444aaudio_result_t AudioStreamInternal::stopClient(audio_port_handle_t portHandle) {
445 ALOGV("%s(%d) called", __func__, portHandle);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700446 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
447 return AAUDIO_ERROR_INVALID_STATE;
448 }
Phil Burkbbd52862018-04-13 11:37:42 -0700449 aaudio_result_t result = mServiceInterface.stopClient(mServiceStreamHandle, portHandle);
450 ALOGV("%s(%d) returning %d", __func__, portHandle, result);
451 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700452}
453
Phil Burk5ed503c2017-02-01 09:38:15 -0800454aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t clockId,
Phil Burk3316d5e2017-02-15 11:23:01 -0800455 int64_t *framePosition,
456 int64_t *timeNanoseconds) {
Phil Burk97350f92017-07-21 15:59:44 -0700457 // Generated in server and passed to client. Return latest.
Phil Burka53ffa62018-10-10 16:21:37 -0700458 if (mAtomicInternalTimestamp.isValid()) {
459 Timestamp timestamp = mAtomicInternalTimestamp.read();
Phil Burkbcc36742017-08-31 17:24:51 -0700460 int64_t position = timestamp.getPosition() + mFramesOffsetFromService;
461 if (position >= 0) {
462 *framePosition = position;
463 *timeNanoseconds = timestamp.getNanoseconds();
464 return AAUDIO_OK;
465 }
Phil Burk97350f92017-07-21 15:59:44 -0700466 }
Phil Burkc75d97f2017-09-08 15:48:36 -0700467 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800468}
469
Phil Burk0befec62017-07-28 15:12:13 -0700470aaudio_result_t AudioStreamInternal::updateStateMachine() {
Phil Burke4d7bb42017-03-28 11:32:39 -0700471 if (isDataCallbackActive()) {
472 return AAUDIO_OK; // state is getting updated by the callback thread read/write call
473 }
Phil Burk204a1632017-01-03 17:23:43 -0800474 return processCommands();
475}
476
Phil Burkec89b2e2017-06-20 15:05:06 -0700477void AudioStreamInternal::logTimestamp(AAudioServiceMessage &command) {
Phil Burk204a1632017-01-03 17:23:43 -0800478 static int64_t oldPosition = 0;
Phil Burk3316d5e2017-02-15 11:23:01 -0800479 static int64_t oldTime = 0;
Phil Burk204a1632017-01-03 17:23:43 -0800480 int64_t framePosition = command.timestamp.position;
Phil Burk3316d5e2017-02-15 11:23:01 -0800481 int64_t nanoTime = command.timestamp.timestamp;
Phil Burkbcc36742017-08-31 17:24:51 -0700482 ALOGD("logTimestamp: timestamp says framePosition = %8lld at nanoTime %lld",
Phil Burk204a1632017-01-03 17:23:43 -0800483 (long long) framePosition,
484 (long long) nanoTime);
485 int64_t nanosDelta = nanoTime - oldTime;
486 if (nanosDelta > 0 && oldTime > 0) {
487 int64_t framesDelta = framePosition - oldPosition;
Phil Burk5ed503c2017-02-01 09:38:15 -0800488 int64_t rate = (framesDelta * AAUDIO_NANOS_PER_SECOND) / nanosDelta;
Phil Burkbcc36742017-08-31 17:24:51 -0700489 ALOGD("logTimestamp: framesDelta = %8lld, nanosDelta = %8lld, rate = %lld",
Phil Burkec89b2e2017-06-20 15:05:06 -0700490 (long long) framesDelta, (long long) nanosDelta, (long long) rate);
Phil Burk204a1632017-01-03 17:23:43 -0800491 }
492 oldPosition = framePosition;
493 oldTime = nanoTime;
494}
Phil Burk204a1632017-01-03 17:23:43 -0800495
Phil Burk97350f92017-07-21 15:59:44 -0700496aaudio_result_t AudioStreamInternal::onTimestampService(AAudioServiceMessage *message) {
Phil Burk204a1632017-01-03 17:23:43 -0800497#if LOG_TIMESTAMPS
Phil Burkec89b2e2017-06-20 15:05:06 -0700498 logTimestamp(*message);
Phil Burk204a1632017-01-03 17:23:43 -0800499#endif
Phil Burkb31b66f2019-09-30 09:33:41 -0700500 processTimestamp(message->timestamp.position,
501 message->timestamp.timestamp + mTimeOffsetNanos);
Phil Burk5ed503c2017-02-01 09:38:15 -0800502 return AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800503}
504
Phil Burk97350f92017-07-21 15:59:44 -0700505aaudio_result_t AudioStreamInternal::onTimestampHardware(AAudioServiceMessage *message) {
506 Timestamp timestamp(message->timestamp.position, message->timestamp.timestamp);
Phil Burka53ffa62018-10-10 16:21:37 -0700507 mAtomicInternalTimestamp.write(timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700508 return AAUDIO_OK;
509}
510
Phil Burk5ed503c2017-02-01 09:38:15 -0800511aaudio_result_t AudioStreamInternal::onEventFromServer(AAudioServiceMessage *message) {
512 aaudio_result_t result = AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800513 switch (message->event.event) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800514 case AAUDIO_SERVICE_EVENT_STARTED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700515 ALOGD("%s - got AAUDIO_SERVICE_EVENT_STARTED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700516 if (getState() == AAUDIO_STREAM_STATE_STARTING) {
517 setState(AAUDIO_STREAM_STATE_STARTED);
518 }
Phil Burk204a1632017-01-03 17:23:43 -0800519 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800520 case AAUDIO_SERVICE_EVENT_PAUSED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700521 ALOGD("%s - got AAUDIO_SERVICE_EVENT_PAUSED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700522 if (getState() == AAUDIO_STREAM_STATE_PAUSING) {
523 setState(AAUDIO_STREAM_STATE_PAUSED);
524 }
Phil Burk204a1632017-01-03 17:23:43 -0800525 break;
Phil Burk71f35bb2017-04-13 16:05:07 -0700526 case AAUDIO_SERVICE_EVENT_STOPPED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700527 ALOGD("%s - got AAUDIO_SERVICE_EVENT_STOPPED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700528 if (getState() == AAUDIO_STREAM_STATE_STOPPING) {
529 setState(AAUDIO_STREAM_STATE_STOPPED);
530 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700531 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800532 case AAUDIO_SERVICE_EVENT_FLUSHED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700533 ALOGD("%s - got AAUDIO_SERVICE_EVENT_FLUSHED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700534 if (getState() == AAUDIO_STREAM_STATE_FLUSHING) {
535 setState(AAUDIO_STREAM_STATE_FLUSHED);
536 onFlushFromServer();
537 }
Phil Burk204a1632017-01-03 17:23:43 -0800538 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800539 case AAUDIO_SERVICE_EVENT_DISCONNECTED:
Phil Burkea04d972017-08-07 12:30:44 -0700540 // Prevent hardware from looping on old data and making buzzing sounds.
541 if (getDirection() == AAUDIO_DIRECTION_OUTPUT) {
542 mAudioEndpoint.eraseDataMemory();
543 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800544 result = AAUDIO_ERROR_DISCONNECTED;
Phil Burkc0c70e32017-02-09 13:18:38 -0800545 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
Phil Burkfbf031e2017-10-12 15:58:31 -0700546 ALOGW("%s - AAUDIO_SERVICE_EVENT_DISCONNECTED - FIFO cleared", __func__);
Phil Burk204a1632017-01-03 17:23:43 -0800547 break;
Phil Burkc0c70e32017-02-09 13:18:38 -0800548 case AAUDIO_SERVICE_EVENT_VOLUME:
Phil Burk55e5eab2018-04-10 15:16:38 -0700549 ALOGD("%s - AAUDIO_SERVICE_EVENT_VOLUME %lf", __func__, message->event.dataDouble);
Eric Laurenta2f296e2017-06-21 18:51:47 -0700550 mStreamVolume = (float)message->event.dataDouble;
551 doSetVolume();
Phil Burkc0c70e32017-02-09 13:18:38 -0800552 break;
Phil Burk23296382017-11-20 15:45:11 -0800553 case AAUDIO_SERVICE_EVENT_XRUN:
554 mXRunCount = static_cast<int32_t>(message->event.dataLong);
555 break;
Phil Burk204a1632017-01-03 17:23:43 -0800556 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700557 ALOGE("%s - Unrecognized event = %d", __func__, (int) message->event.event);
Phil Burk204a1632017-01-03 17:23:43 -0800558 break;
559 }
560 return result;
561}
562
Phil Burkbcc36742017-08-31 17:24:51 -0700563aaudio_result_t AudioStreamInternal::drainTimestampsFromService() {
564 aaudio_result_t result = AAUDIO_OK;
565
566 while (result == AAUDIO_OK) {
567 AAudioServiceMessage message;
568 if (mAudioEndpoint.readUpCommand(&message) != 1) {
569 break; // no command this time, no problem
570 }
571 switch (message.what) {
572 // ignore most messages
573 case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
574 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
575 break;
576
577 case AAudioServiceMessage::code::EVENT:
578 result = onEventFromServer(&message);
579 break;
580
581 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700582 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
Phil Burkbcc36742017-08-31 17:24:51 -0700583 result = AAUDIO_ERROR_INTERNAL;
584 break;
585 }
586 }
587 return result;
588}
589
Phil Burk204a1632017-01-03 17:23:43 -0800590// Process all the commands coming from the server.
Phil Burk5ed503c2017-02-01 09:38:15 -0800591aaudio_result_t AudioStreamInternal::processCommands() {
592 aaudio_result_t result = AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800593
Phil Burk5ed503c2017-02-01 09:38:15 -0800594 while (result == AAUDIO_OK) {
595 AAudioServiceMessage message;
Phil Burk204a1632017-01-03 17:23:43 -0800596 if (mAudioEndpoint.readUpCommand(&message) != 1) {
597 break; // no command this time, no problem
598 }
599 switch (message.what) {
Phil Burk97350f92017-07-21 15:59:44 -0700600 case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
601 result = onTimestampService(&message);
602 break;
603
604 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
605 result = onTimestampHardware(&message);
Phil Burk204a1632017-01-03 17:23:43 -0800606 break;
607
Phil Burk5ed503c2017-02-01 09:38:15 -0800608 case AAudioServiceMessage::code::EVENT:
Phil Burk204a1632017-01-03 17:23:43 -0800609 result = onEventFromServer(&message);
610 break;
611
612 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700613 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
Phil Burk17fff382017-05-16 14:06:45 -0700614 result = AAUDIO_ERROR_INTERNAL;
Phil Burk204a1632017-01-03 17:23:43 -0800615 break;
616 }
617 }
618 return result;
619}
620
Phil Burk87c9f642017-05-17 07:22:39 -0700621// Read or write the data, block if needed and timeoutMillis > 0
622aaudio_result_t AudioStreamInternal::processData(void *buffer, int32_t numFrames,
623 int64_t timeoutNanoseconds)
Phil Burk204a1632017-01-03 17:23:43 -0800624{
Phil Burkfd34a932017-07-19 07:03:52 -0700625 const char * traceName = "aaProc";
626 const char * fifoName = "aaRdy";
Phil Burk4485d412017-05-09 15:55:02 -0700627 ATRACE_BEGIN(traceName);
Phil Burk4485d412017-05-09 15:55:02 -0700628 if (ATRACE_ENABLED()) {
Phil Burkfd34a932017-07-19 07:03:52 -0700629 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable();
630 ATRACE_INT(fifoName, fullFrames);
Phil Burk4485d412017-05-09 15:55:02 -0700631 }
632
Phil Burkec89b2e2017-06-20 15:05:06 -0700633 aaudio_result_t result = AAUDIO_OK;
634 int32_t loopCount = 0;
635 uint8_t* audioData = (uint8_t*)buffer;
636 int64_t currentTimeNanos = AudioClock::getNanoseconds();
637 const int64_t entryTimeNanos = currentTimeNanos;
638 const int64_t deadlineNanos = currentTimeNanos + timeoutNanoseconds;
639 int32_t framesLeft = numFrames;
640
Phil Burk87c9f642017-05-17 07:22:39 -0700641 // Loop until all the data has been processed or until a timeout occurs.
Phil Burk204a1632017-01-03 17:23:43 -0800642 while (framesLeft > 0) {
Phil Burkec89b2e2017-06-20 15:05:06 -0700643 // The call to processDataNow() will not block. It will just process as much as it can.
Phil Burk3316d5e2017-02-15 11:23:01 -0800644 int64_t wakeTimeNanos = 0;
Phil Burk87c9f642017-05-17 07:22:39 -0700645 aaudio_result_t framesProcessed = processDataNow(audioData, framesLeft,
646 currentTimeNanos, &wakeTimeNanos);
647 if (framesProcessed < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700648 result = framesProcessed;
Phil Burk204a1632017-01-03 17:23:43 -0800649 break;
650 }
Phil Burk87c9f642017-05-17 07:22:39 -0700651 framesLeft -= (int32_t) framesProcessed;
652 audioData += framesProcessed * getBytesPerFrame();
Phil Burk204a1632017-01-03 17:23:43 -0800653
654 // Should we block?
655 if (timeoutNanoseconds == 0) {
656 break; // don't block
Phil Burk8d4f0062019-10-03 15:55:41 -0700657 } else if (wakeTimeNanos != 0) {
Phil Burkfd34a932017-07-19 07:03:52 -0700658 if (!mAudioEndpoint.isFreeRunning()) {
659 // If there is software on the other end of the FIFO then it may get delayed.
660 // So wake up just a little after we expect it to be ready.
661 wakeTimeNanos += mWakeupDelayNanos;
Phil Burk204a1632017-01-03 17:23:43 -0800662 }
Phil Burkfd34a932017-07-19 07:03:52 -0700663
Phil Burk2bc7c182017-08-28 11:45:01 -0700664 currentTimeNanos = AudioClock::getNanoseconds();
665 int64_t earliestWakeTime = currentTimeNanos + mMinimumSleepNanos;
666 // Guarantee a minimum sleep time.
667 if (wakeTimeNanos < earliestWakeTime) {
668 wakeTimeNanos = earliestWakeTime;
669 }
670
Phil Burk204a1632017-01-03 17:23:43 -0800671 if (wakeTimeNanos > deadlineNanos) {
672 // If we time out, just return the framesWritten so far.
Phil Burkcf5f6d22017-05-26 12:35:07 -0700673 // TODO remove after we fix the deadline bug
Phil Burkfbf031e2017-10-12 15:58:31 -0700674 ALOGW("processData(): entered at %lld nanos, currently %lld",
Phil Burkec89b2e2017-06-20 15:05:06 -0700675 (long long) entryTimeNanos, (long long) currentTimeNanos);
Phil Burkfbf031e2017-10-12 15:58:31 -0700676 ALOGW("processData(): TIMEOUT after %lld nanos",
Phil Burkc0c70e32017-02-09 13:18:38 -0800677 (long long) timeoutNanoseconds);
Phil Burkfbf031e2017-10-12 15:58:31 -0700678 ALOGW("processData(): wakeTime = %lld, deadline = %lld nanos",
Phil Burk87c9f642017-05-17 07:22:39 -0700679 (long long) wakeTimeNanos, (long long) deadlineNanos);
Phil Burkfbf031e2017-10-12 15:58:31 -0700680 ALOGW("processData(): past deadline by %d micros",
Phil Burk87c9f642017-05-17 07:22:39 -0700681 (int)((wakeTimeNanos - deadlineNanos) / AAUDIO_NANOS_PER_MICROSECOND));
Phil Burkec89b2e2017-06-20 15:05:06 -0700682 mClockModel.dump();
683 mAudioEndpoint.dump();
Phil Burk204a1632017-01-03 17:23:43 -0800684 break;
685 }
686
Phil Burkfd34a932017-07-19 07:03:52 -0700687 if (ATRACE_ENABLED()) {
688 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable();
689 ATRACE_INT(fifoName, fullFrames);
690 int64_t sleepForNanos = wakeTimeNanos - currentTimeNanos;
691 ATRACE_INT("aaSlpNs", (int32_t)sleepForNanos);
692 }
693
694 AudioClock::sleepUntilNanoTime(wakeTimeNanos);
Phil Burk204a1632017-01-03 17:23:43 -0800695 currentTimeNanos = AudioClock::getNanoseconds();
696 }
697 }
698
Phil Burkfd34a932017-07-19 07:03:52 -0700699 if (ATRACE_ENABLED()) {
700 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable();
701 ATRACE_INT(fifoName, fullFrames);
702 }
703
Phil Burk87c9f642017-05-17 07:22:39 -0700704 // return error or framesProcessed
Phil Burkc0c70e32017-02-09 13:18:38 -0800705 (void) loopCount;
Phil Burk4485d412017-05-09 15:55:02 -0700706 ATRACE_END();
Phil Burk204a1632017-01-03 17:23:43 -0800707 return (result < 0) ? result : numFrames - framesLeft;
708}
709
Phil Burk3316d5e2017-02-15 11:23:01 -0800710void AudioStreamInternal::processTimestamp(uint64_t position, int64_t time) {
Phil Burk87c9f642017-05-17 07:22:39 -0700711 mClockModel.processTimestamp(position, time);
Phil Burk204a1632017-01-03 17:23:43 -0800712}
713
Phil Burk3316d5e2017-02-15 11:23:01 -0800714aaudio_result_t AudioStreamInternal::setBufferSize(int32_t requestedFrames) {
Phil Burk6479d502017-11-20 09:32:52 -0800715 int32_t adjustedFrames = requestedFrames;
Phil Burk8d4f0062019-10-03 15:55:41 -0700716 const int32_t maximumSize = getBufferCapacity() - mFramesPerBurst;
Phil Burk5347dca2020-04-08 16:31:07 -0700717 // Minimum size should be a multiple number of bursts.
718 const int32_t minimumSize = 1 * mFramesPerBurst;
Phil Burk6479d502017-11-20 09:32:52 -0800719
720 // Clip to minimum size so that rounding up will work better.
Phil Burk8d4f0062019-10-03 15:55:41 -0700721 adjustedFrames = std::max(minimumSize, adjustedFrames);
Phil Burk71f35bb2017-04-13 16:05:07 -0700722
Phil Burk8d4f0062019-10-03 15:55:41 -0700723 // Prevent arithmetic overflow by clipping before we round.
724 if (adjustedFrames >= maximumSize) {
Phil Burk6479d502017-11-20 09:32:52 -0800725 adjustedFrames = maximumSize;
726 } else {
727 // Round to the next highest burst size.
728 int32_t numBursts = (adjustedFrames + mFramesPerBurst - 1) / mFramesPerBurst;
729 adjustedFrames = numBursts * mFramesPerBurst;
Phil Burk5347dca2020-04-08 16:31:07 -0700730 // Clip just in case maximumSize is not a multiple of mFramesPerBurst.
731 adjustedFrames = std::min(maximumSize, adjustedFrames);
Phil Burk6479d502017-11-20 09:32:52 -0800732 }
733
Phil Burk8d4f0062019-10-03 15:55:41 -0700734 // Clip against the actual size from the endpoint.
735 int32_t actualFrames = 0;
736 mAudioEndpoint.setBufferSizeInFrames(maximumSize, &actualFrames);
Phil Burk5347dca2020-04-08 16:31:07 -0700737 // actualFrames should be <= actual maximum size of endpoint
Phil Burk8d4f0062019-10-03 15:55:41 -0700738 adjustedFrames = std::min(actualFrames, adjustedFrames);
739
740 mBufferSizeInFrames = adjustedFrames;
Phil Burk6c63ae32019-10-28 10:28:21 -0700741 ALOGV("%s(%d) returns %d", __func__, requestedFrames, adjustedFrames);
Phil Burk8d4f0062019-10-03 15:55:41 -0700742 return (aaudio_result_t) adjustedFrames;
Phil Burk204a1632017-01-03 17:23:43 -0800743}
744
Phil Burk87c9f642017-05-17 07:22:39 -0700745int32_t AudioStreamInternal::getBufferSize() const {
Phil Burk8d4f0062019-10-03 15:55:41 -0700746 return mBufferSizeInFrames;
Phil Burk204a1632017-01-03 17:23:43 -0800747}
748
Phil Burk87c9f642017-05-17 07:22:39 -0700749int32_t AudioStreamInternal::getBufferCapacity() const {
Phil Burk204a1632017-01-03 17:23:43 -0800750 return mAudioEndpoint.getBufferCapacityInFrames();
751}
752
Phil Burk87c9f642017-05-17 07:22:39 -0700753int32_t AudioStreamInternal::getFramesPerBurst() const {
Phil Burk6479d502017-11-20 09:32:52 -0800754 return mFramesPerBurst;
Phil Burk204a1632017-01-03 17:23:43 -0800755}
756
Phil Burk13d3d832019-06-10 14:36:48 -0700757// This must be called under mStreamLock.
Phil Burk87c9f642017-05-17 07:22:39 -0700758aaudio_result_t AudioStreamInternal::joinThread(void** returnArg) {
759 return AudioStream::joinThread(returnArg, calculateReasonableTimeout(getFramesPerBurst()));
Phil Burk4c5129b2017-04-28 15:17:32 -0700760}
Phil Burk377c1c22018-12-12 16:06:54 -0800761
762bool AudioStreamInternal::isClockModelInControl() const {
763 return isActive() && mAudioEndpoint.isFreeRunning() && mClockModel.isRunning();
764}