blob: f89cde7c71bd2959bd89fb980cafec56cfe892c6 [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()
Phil Burk5ed503c2017-02-01 09:38:15 -080061 , mServiceStreamHandle(AAUDIO_HANDLE_INVALID)
Phil Burkec89b2e2017-06-20 15:05:06 -070062 , mInService(inService)
Phil Burkfd34a932017-07-19 07:03:52 -070063 , mServiceInterface(serviceInterface)
Phil Burka53ffa62018-10-10 16:21:37 -070064 , mAtomicInternalTimestamp()
Phil Burkfd34a932017-07-19 07:03:52 -070065 , mWakeupDelayNanos(AAudioProperty_getWakeupDelayMicros() * AAUDIO_NANOS_PER_MICROSECOND)
66 , mMinimumSleepNanos(AAudioProperty_getMinimumSleepMicros() * AAUDIO_NANOS_PER_MICROSECOND)
67 {
Phil Burk204a1632017-01-03 17:23:43 -080068}
69
70AudioStreamInternal::~AudioStreamInternal() {
71}
72
Phil Burk5ed503c2017-02-01 09:38:15 -080073aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) {
Phil Burk204a1632017-01-03 17:23:43 -080074
Phil Burk5ed503c2017-02-01 09:38:15 -080075 aaudio_result_t result = AAUDIO_OK;
Phil Burk6479d502017-11-20 09:32:52 -080076 int32_t framesPerBurst;
Phil Burk3c4e6b52019-01-22 15:53:36 -080077 int32_t framesPerHardwareBurst;
Phil Burk5ed503c2017-02-01 09:38:15 -080078 AAudioStreamRequest request;
Phil Burk99306c82017-08-14 12:38:58 -070079 AAudioStreamConfiguration configurationOutput;
Phil Burk204a1632017-01-03 17:23:43 -080080
Phil Burk99306c82017-08-14 12:38:58 -070081 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
Phil Burkfbf031e2017-10-12 15:58:31 -070082 ALOGE("%s - already open! state = %d", __func__, getState());
Phil Burk99306c82017-08-14 12:38:58 -070083 return AAUDIO_ERROR_INVALID_STATE;
84 }
85
86 // Copy requested parameters to the stream.
Phil Burk204a1632017-01-03 17:23:43 -080087 result = AudioStream::open(builder);
88 if (result < 0) {
89 return result;
90 }
91
Phil Burk3c4e6b52019-01-22 15:53:36 -080092 const int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
93 int32_t burstMicros = 0;
94
Phil Burkc0c70e32017-02-09 13:18:38 -080095 // We have to do volume scaling. So we prefer FLOAT format.
Phil Burk0127c1b2018-03-29 13:48:06 -070096 if (getFormat() == AUDIO_FORMAT_DEFAULT) {
97 setFormat(AUDIO_FORMAT_PCM_FLOAT);
Phil Burkc0c70e32017-02-09 13:18:38 -080098 }
Phil Burk71f35bb2017-04-13 16:05:07 -070099 // Request FLOAT for the shared mixer.
Phil Burk0127c1b2018-03-29 13:48:06 -0700100 request.getConfiguration().setFormat(AUDIO_FORMAT_PCM_FLOAT);
Phil Burkc0c70e32017-02-09 13:18:38 -0800101
Phil Burkdec33ab2017-01-17 14:48:16 -0800102 // Build the request to send to the server.
Phil Burk204a1632017-01-03 17:23:43 -0800103 request.setUserId(getuid());
104 request.setProcessId(getpid());
Phil Burk71f35bb2017-04-13 16:05:07 -0700105 request.setSharingModeMatchRequired(isSharingModeMatchRequired());
Phil Burk41f19d82018-02-13 14:59:10 -0800106 request.setInService(isInService());
Phil Burkc0c70e32017-02-09 13:18:38 -0800107
Phil Burk204a1632017-01-03 17:23:43 -0800108 request.getConfiguration().setDeviceId(getDeviceId());
109 request.getConfiguration().setSampleRate(getSampleRate());
110 request.getConfiguration().setSamplesPerFrame(getSamplesPerFrame());
Phil Burk39f02dd2017-08-04 09:13:31 -0700111 request.getConfiguration().setDirection(getDirection());
Phil Burk71f35bb2017-04-13 16:05:07 -0700112 request.getConfiguration().setSharingMode(getSharingMode());
113
Phil Burka62fb952018-01-16 12:44:06 -0800114 request.getConfiguration().setUsage(getUsage());
115 request.getConfiguration().setContentType(getContentType());
116 request.getConfiguration().setInputPreset(getInputPreset());
Eric Laurentd17c8502019-10-24 15:58:35 -0700117 request.getConfiguration().setPrivacySensitive(isPrivacySensitive());
Phil Burka62fb952018-01-16 12:44:06 -0800118
Phil Burk3df348f2017-02-08 11:41:55 -0800119 request.getConfiguration().setBufferCapacity(builder.getBufferCapacity());
Phil Burk204a1632017-01-03 17:23:43 -0800120
Phil Burk41f19d82018-02-13 14:59:10 -0800121 mDeviceChannelCount = getSamplesPerFrame(); // Assume it will be the same. Update if not.
122
Phil Burk99306c82017-08-14 12:38:58 -0700123 mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
Phil Burk41f19d82018-02-13 14:59:10 -0800124 if (mServiceStreamHandle < 0
125 && request.getConfiguration().getSamplesPerFrame() == 1 // mono?
126 && getDirection() == AAUDIO_DIRECTION_OUTPUT
127 && !isInService()) {
128 // if that failed then try switching from mono to stereo if OUTPUT.
129 // Only do this in the client. Otherwise we end up with a mono mixer in the service
130 // that writes to a stereo MMAP stream.
Phil Burk0127c1b2018-03-29 13:48:06 -0700131 ALOGD("%s() - openStream() returned %d, try switching from MONO to STEREO",
Phil Burk41f19d82018-02-13 14:59:10 -0800132 __func__, mServiceStreamHandle);
133 request.getConfiguration().setSamplesPerFrame(2); // stereo
134 mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
135 }
Phil Burk204a1632017-01-03 17:23:43 -0800136 if (mServiceStreamHandle < 0) {
Phil Burk41f19d82018-02-13 14:59:10 -0800137 return mServiceStreamHandle;
Phil Burk204a1632017-01-03 17:23:43 -0800138 }
Phil Burk99306c82017-08-14 12:38:58 -0700139
140 result = configurationOutput.validate();
141 if (result != AAUDIO_OK) {
142 goto error;
143 }
144 // Save results of the open.
Phil Burk41f19d82018-02-13 14:59:10 -0800145 if (getSamplesPerFrame() == AAUDIO_UNSPECIFIED) {
146 setSamplesPerFrame(configurationOutput.getSamplesPerFrame());
147 }
148 mDeviceChannelCount = configurationOutput.getSamplesPerFrame();
149
Phil Burk99306c82017-08-14 12:38:58 -0700150 setSampleRate(configurationOutput.getSampleRate());
Phil Burk99306c82017-08-14 12:38:58 -0700151 setDeviceId(configurationOutput.getDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800152 setSessionId(configurationOutput.getSessionId());
Phil Burk99306c82017-08-14 12:38:58 -0700153 setSharingMode(configurationOutput.getSharingMode());
154
Phil Burka62fb952018-01-16 12:44:06 -0800155 setUsage(configurationOutput.getUsage());
156 setContentType(configurationOutput.getContentType());
157 setInputPreset(configurationOutput.getInputPreset());
158
Phil Burk99306c82017-08-14 12:38:58 -0700159 // Save device format so we can do format conversion and volume scaling together.
Phil Burk3d786cb2018-04-09 11:58:09 -0700160 setDeviceFormat(configurationOutput.getFormat());
Phil Burk99306c82017-08-14 12:38:58 -0700161
162 result = mServiceInterface.getStreamDescription(mServiceStreamHandle, mEndPointParcelable);
163 if (result != AAUDIO_OK) {
164 goto error;
165 }
166
167 // Resolve parcelable into a descriptor.
168 result = mEndPointParcelable.resolve(&mEndpointDescriptor);
169 if (result != AAUDIO_OK) {
170 goto error;
171 }
172
173 // Configure endpoint based on descriptor.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700174 mAudioEndpoint = std::make_unique<AudioEndpoint>();
175 result = mAudioEndpoint->configure(&mEndpointDescriptor, getDirection());
Phil Burk99306c82017-08-14 12:38:58 -0700176 if (result != AAUDIO_OK) {
177 goto error;
178 }
179
Phil Burk3c4e6b52019-01-22 15:53:36 -0800180 framesPerHardwareBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst;
181
182 // Scale up the burst size to meet the minimum equivalent in microseconds.
183 // This is to avoid waking the CPU too often when the HW burst is very small
184 // or at high sample rates.
185 framesPerBurst = framesPerHardwareBurst;
186 do {
187 if (burstMicros > 0) { // skip first loop
188 framesPerBurst *= 2;
189 }
190 burstMicros = framesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
191 } while (burstMicros < burstMinMicros);
192 ALOGD("%s() original HW burst = %d, minMicros = %d => SW burst = %d\n",
193 __func__, framesPerHardwareBurst, burstMinMicros, framesPerBurst);
194
195 // Validate final burst size.
Phil Burk6479d502017-11-20 09:32:52 -0800196 if (framesPerBurst < MIN_FRAMES_PER_BURST || framesPerBurst > MAX_FRAMES_PER_BURST) {
197 ALOGE("%s - framesPerBurst out of range = %d", __func__, framesPerBurst);
Phil Burk99306c82017-08-14 12:38:58 -0700198 result = AAUDIO_ERROR_OUT_OF_RANGE;
199 goto error;
200 }
Phil Burk6479d502017-11-20 09:32:52 -0800201 mFramesPerBurst = framesPerBurst; // only save good value
202
Phil Burk5edc4ea2020-04-17 08:15:42 -0700203 mBufferCapacityInFrames = mEndpointDescriptor.dataQueueDescriptor.capacityInFrames;
204 if (mBufferCapacityInFrames < mFramesPerBurst
205 || mBufferCapacityInFrames > MAX_BUFFER_CAPACITY_IN_FRAMES) {
206 ALOGE("%s - bufferCapacity out of range = %d", __func__, mBufferCapacityInFrames);
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 Burkbf821e22020-04-17 11:51:43 -0700233 mCallbackBuffer = std::make_unique<uint8_t[]>(callbackBufferSize);
Phil Burk99306c82017-08-14 12:38:58 -0700234 }
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.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700242 if (mAudioEndpoint->isFreeRunning()) { // MMAP?
Phil Burkb31b66f2019-09-30 09:33:41 -0700243 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 Burk5edc4ea2020-04-17 08:15:42 -0700254 setBufferSize(mBufferCapacityInFrames / 2); // Default buffer size to match Q
Phil Burk6c63ae32019-10-28 10:28:21 -0700255
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 Burkbf821e22020-04-17 11:51:43 -0700282 mCallbackBuffer.reset();
Phil Burk5edc4ea2020-04-17 08:15:42 -0700283
284 // Update local frame counters so we can query them after releasing the endpoint.
285 getFramesRead();
286 getFramesWritten();
287 mAudioEndpoint.reset();
Phil Burk965650e2017-09-07 21:00:09 -0700288 result = mEndPointParcelable.close();
Phil Burk8b4e05e2019-12-17 12:12:09 -0800289 aaudio_result_t result2 = AudioStream::release_l();
Phil Burk965650e2017-09-07 21:00:09 -0700290 return (result != AAUDIO_OK) ? result : result2;
Phil Burk204a1632017-01-03 17:23:43 -0800291 } else {
Phil Burk5ed503c2017-02-01 09:38:15 -0800292 return AAUDIO_ERROR_INVALID_HANDLE;
Phil Burk204a1632017-01-03 17:23:43 -0800293 }
294}
295
Phil Burke4d7bb42017-03-28 11:32:39 -0700296static void *aaudio_callback_thread_proc(void *context)
297{
298 AudioStreamInternal *stream = (AudioStreamInternal *)context;
Phil Burkfbf031e2017-10-12 15:58:31 -0700299 //LOGD("oboe_callback_thread, stream = %p", stream);
Phil Burke4d7bb42017-03-28 11:32:39 -0700300 if (stream != NULL) {
301 return stream->callbackLoop();
302 } else {
303 return NULL;
304 }
305}
306
Phil Burkbcc36742017-08-31 17:24:51 -0700307/*
308 * It normally takes about 20-30 msec to start a stream on the server.
309 * But the first time can take as much as 200-300 msec. The HW
310 * starts right away so by the time the client gets a chance to write into
311 * the buffer, it is already in a deep underflow state. That can cause the
312 * XRunCount to be non-zero, which could lead an app to tune its latency higher.
313 * To avoid this problem, we set a request for the processing code to start the
314 * client stream at the same position as the server stream.
315 * The processing code will then save the current offset
316 * between client and server and apply that to any position given to the app.
317 */
Phil Burk5ed503c2017-02-01 09:38:15 -0800318aaudio_result_t AudioStreamInternal::requestStart()
Phil Burk204a1632017-01-03 17:23:43 -0800319{
Phil Burk3316d5e2017-02-15 11:23:01 -0800320 int64_t startTime;
Phil Burk5ed503c2017-02-01 09:38:15 -0800321 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700322 ALOGD("requestStart() mServiceStreamHandle invalid");
Phil Burk5ed503c2017-02-01 09:38:15 -0800323 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800324 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700325 if (isActive()) {
Phil Burk29ccc292019-04-15 08:58:08 -0700326 ALOGD("requestStart() already active");
Phil Burkec89b2e2017-06-20 15:05:06 -0700327 return AAUDIO_ERROR_INVALID_STATE;
328 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700329
Phil Burkbcc36742017-08-31 17:24:51 -0700330 aaudio_stream_state_t originalState = getState();
331 if (originalState == AAUDIO_STREAM_STATE_DISCONNECTED) {
Phil Burk29ccc292019-04-15 08:58:08 -0700332 ALOGD("requestStart() but DISCONNECTED");
Phil Burkbcc36742017-08-31 17:24:51 -0700333 return AAUDIO_ERROR_DISCONNECTED;
334 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700335 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burkbcc36742017-08-31 17:24:51 -0700336
337 // Clear any stale timestamps from the previous run.
338 drainTimestampsFromService();
339
Phil Burk965650e2017-09-07 21:00:09 -0700340 aaudio_result_t result = mServiceInterface.startStream(mServiceStreamHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800341
Phil Burk3316d5e2017-02-15 11:23:01 -0800342 startTime = AudioClock::getNanoseconds();
Phil Burk204a1632017-01-03 17:23:43 -0800343 mClockModel.start(startTime);
Phil Burkbcc36742017-08-31 17:24:51 -0700344 mNeedCatchUp.request(); // Ask data processing code to catch up when first timestamp received.
Phil Burke4d7bb42017-03-28 11:32:39 -0700345
Phil Burk965650e2017-09-07 21:00:09 -0700346 // Start data callback thread.
Phil Burk134f1972017-12-08 13:06:11 -0800347 if (result == AAUDIO_OK && isDataCallbackSet()) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700348 // Launch the callback loop thread.
349 int64_t periodNanos = mCallbackFrames
350 * AAUDIO_NANOS_PER_SECOND
351 / getSampleRate();
352 mCallbackEnabled.store(true);
353 result = createThread(periodNanos, aaudio_callback_thread_proc, this);
354 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700355 if (result != AAUDIO_OK) {
356 setState(originalState);
357 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700358 return result;
Phil Burk204a1632017-01-03 17:23:43 -0800359}
360
Phil Burke4d7bb42017-03-28 11:32:39 -0700361int64_t AudioStreamInternal::calculateReasonableTimeout(int32_t framesPerOperation) {
362
363 // Wait for at least a second or some number of callbacks to join the thread.
Phil Burk71f35bb2017-04-13 16:05:07 -0700364 int64_t timeoutNanoseconds = (MIN_TIMEOUT_OPERATIONS
365 * framesPerOperation
366 * AAUDIO_NANOS_PER_SECOND)
367 / getSampleRate();
Phil Burke4d7bb42017-03-28 11:32:39 -0700368 if (timeoutNanoseconds < MIN_TIMEOUT_NANOS) { // arbitrary number of seconds
369 timeoutNanoseconds = MIN_TIMEOUT_NANOS;
370 }
371 return timeoutNanoseconds;
372}
373
Phil Burk87c9f642017-05-17 07:22:39 -0700374int64_t AudioStreamInternal::calculateReasonableTimeout() {
375 return calculateReasonableTimeout(getFramesPerBurst());
376}
377
Phil Burk13d3d832019-06-10 14:36:48 -0700378// This must be called under mStreamLock.
Phil Burke4d7bb42017-03-28 11:32:39 -0700379aaudio_result_t AudioStreamInternal::stopCallback()
380{
Phil Burk13d3d832019-06-10 14:36:48 -0700381 if (isDataCallbackSet()
382 && (isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700383 mCallbackEnabled.store(false);
Phil Burk13d3d832019-06-10 14:36:48 -0700384 return joinThread(NULL); // may temporarily unlock mStreamLock
Phil Burke4d7bb42017-03-28 11:32:39 -0700385 } else {
386 return AAUDIO_OK;
387 }
388}
389
Phil Burk13d3d832019-06-10 14:36:48 -0700390// This must be called under mStreamLock.
Phil Burk1e83bee2018-12-17 14:15:20 -0800391aaudio_result_t AudioStreamInternal::requestStop() {
Phil Burk5cc83c32017-11-28 15:43:18 -0800392 aaudio_result_t result = stopCallback();
393 if (result != AAUDIO_OK) {
394 return result;
395 }
Phil Burk13d3d832019-06-10 14:36:48 -0700396 // The stream may have been unlocked temporarily to let a callback finish
397 // and the callback may have stopped the stream.
398 // Check to make sure the stream still needs to be stopped.
399 // See also AudioStream::safeStop().
400 if (!(isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) {
401 return AAUDIO_OK;
402 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800403
Phil Burk71f35bb2017-04-13 16:05:07 -0700404 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700405 ALOGW("%s() mServiceStreamHandle invalid = 0x%08X",
406 __func__, mServiceStreamHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700407 return AAUDIO_ERROR_INVALID_STATE;
408 }
409
410 mClockModel.stop(AudioClock::getNanoseconds());
411 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burka53ffa62018-10-10 16:21:37 -0700412 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -0700413
414 return mServiceInterface.stopStream(mServiceStreamHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700415}
416
Phil Burk5ed503c2017-02-01 09:38:15 -0800417aaudio_result_t AudioStreamInternal::registerThread() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800418 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700419 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800420 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800421 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800422 return mServiceInterface.registerAudioThread(mServiceStreamHandle,
Phil Burkc0c70e32017-02-09 13:18:38 -0800423 gettid(),
424 getPeriodNanoseconds());
Phil Burk204a1632017-01-03 17:23:43 -0800425}
426
Phil Burk5ed503c2017-02-01 09:38:15 -0800427aaudio_result_t AudioStreamInternal::unregisterThread() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800428 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -0700429 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800430 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800431 }
Phil Burk2ac035f2017-06-23 14:51:14 -0700432 return mServiceInterface.unregisterAudioThread(mServiceStreamHandle, gettid());
Phil Burk204a1632017-01-03 17:23:43 -0800433}
434
Eric Laurentcb4dae22017-07-01 19:39:32 -0700435aaudio_result_t AudioStreamInternal::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700436 const audio_attributes_t *attr,
Phil Burkbbd52862018-04-13 11:37:42 -0700437 audio_port_handle_t *portHandle) {
438 ALOGV("%s() called", __func__);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700439 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
440 return AAUDIO_ERROR_INVALID_STATE;
441 }
Phil Burkbbd52862018-04-13 11:37:42 -0700442 aaudio_result_t result = mServiceInterface.startClient(mServiceStreamHandle,
jiabind1f1cb62020-03-24 11:57:57 -0700443 client, attr, portHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700444 ALOGV("%s(%d) returning %d", __func__, *portHandle, result);
445 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700446}
447
Phil Burkbbd52862018-04-13 11:37:42 -0700448aaudio_result_t AudioStreamInternal::stopClient(audio_port_handle_t portHandle) {
449 ALOGV("%s(%d) called", __func__, portHandle);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700450 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
451 return AAUDIO_ERROR_INVALID_STATE;
452 }
Phil Burkbbd52862018-04-13 11:37:42 -0700453 aaudio_result_t result = mServiceInterface.stopClient(mServiceStreamHandle, portHandle);
454 ALOGV("%s(%d) returning %d", __func__, portHandle, result);
455 return result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700456}
457
Phil Burk5ed503c2017-02-01 09:38:15 -0800458aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t clockId,
Phil Burk3316d5e2017-02-15 11:23:01 -0800459 int64_t *framePosition,
460 int64_t *timeNanoseconds) {
Phil Burk97350f92017-07-21 15:59:44 -0700461 // Generated in server and passed to client. Return latest.
Phil Burka53ffa62018-10-10 16:21:37 -0700462 if (mAtomicInternalTimestamp.isValid()) {
463 Timestamp timestamp = mAtomicInternalTimestamp.read();
Phil Burkbcc36742017-08-31 17:24:51 -0700464 int64_t position = timestamp.getPosition() + mFramesOffsetFromService;
465 if (position >= 0) {
466 *framePosition = position;
467 *timeNanoseconds = timestamp.getNanoseconds();
468 return AAUDIO_OK;
469 }
Phil Burk97350f92017-07-21 15:59:44 -0700470 }
Phil Burkc75d97f2017-09-08 15:48:36 -0700471 return AAUDIO_ERROR_INVALID_STATE;
Phil Burk204a1632017-01-03 17:23:43 -0800472}
473
Phil Burk0befec62017-07-28 15:12:13 -0700474aaudio_result_t AudioStreamInternal::updateStateMachine() {
Phil Burke4d7bb42017-03-28 11:32:39 -0700475 if (isDataCallbackActive()) {
476 return AAUDIO_OK; // state is getting updated by the callback thread read/write call
477 }
Phil Burk204a1632017-01-03 17:23:43 -0800478 return processCommands();
479}
480
Phil Burkec89b2e2017-06-20 15:05:06 -0700481void AudioStreamInternal::logTimestamp(AAudioServiceMessage &command) {
Phil Burk204a1632017-01-03 17:23:43 -0800482 static int64_t oldPosition = 0;
Phil Burk3316d5e2017-02-15 11:23:01 -0800483 static int64_t oldTime = 0;
Phil Burk204a1632017-01-03 17:23:43 -0800484 int64_t framePosition = command.timestamp.position;
Phil Burk3316d5e2017-02-15 11:23:01 -0800485 int64_t nanoTime = command.timestamp.timestamp;
Phil Burkbcc36742017-08-31 17:24:51 -0700486 ALOGD("logTimestamp: timestamp says framePosition = %8lld at nanoTime %lld",
Phil Burk204a1632017-01-03 17:23:43 -0800487 (long long) framePosition,
488 (long long) nanoTime);
489 int64_t nanosDelta = nanoTime - oldTime;
490 if (nanosDelta > 0 && oldTime > 0) {
491 int64_t framesDelta = framePosition - oldPosition;
Phil Burk5ed503c2017-02-01 09:38:15 -0800492 int64_t rate = (framesDelta * AAUDIO_NANOS_PER_SECOND) / nanosDelta;
Phil Burkbcc36742017-08-31 17:24:51 -0700493 ALOGD("logTimestamp: framesDelta = %8lld, nanosDelta = %8lld, rate = %lld",
Phil Burkec89b2e2017-06-20 15:05:06 -0700494 (long long) framesDelta, (long long) nanosDelta, (long long) rate);
Phil Burk204a1632017-01-03 17:23:43 -0800495 }
496 oldPosition = framePosition;
497 oldTime = nanoTime;
498}
Phil Burk204a1632017-01-03 17:23:43 -0800499
Phil Burk97350f92017-07-21 15:59:44 -0700500aaudio_result_t AudioStreamInternal::onTimestampService(AAudioServiceMessage *message) {
Phil Burk204a1632017-01-03 17:23:43 -0800501#if LOG_TIMESTAMPS
Phil Burkec89b2e2017-06-20 15:05:06 -0700502 logTimestamp(*message);
Phil Burk204a1632017-01-03 17:23:43 -0800503#endif
Phil Burkb31b66f2019-09-30 09:33:41 -0700504 processTimestamp(message->timestamp.position,
505 message->timestamp.timestamp + mTimeOffsetNanos);
Phil Burk5ed503c2017-02-01 09:38:15 -0800506 return AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800507}
508
Phil Burk97350f92017-07-21 15:59:44 -0700509aaudio_result_t AudioStreamInternal::onTimestampHardware(AAudioServiceMessage *message) {
510 Timestamp timestamp(message->timestamp.position, message->timestamp.timestamp);
Phil Burka53ffa62018-10-10 16:21:37 -0700511 mAtomicInternalTimestamp.write(timestamp);
Phil Burk97350f92017-07-21 15:59:44 -0700512 return AAUDIO_OK;
513}
514
Phil Burk5ed503c2017-02-01 09:38:15 -0800515aaudio_result_t AudioStreamInternal::onEventFromServer(AAudioServiceMessage *message) {
516 aaudio_result_t result = AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800517 switch (message->event.event) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800518 case AAUDIO_SERVICE_EVENT_STARTED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700519 ALOGD("%s - got AAUDIO_SERVICE_EVENT_STARTED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700520 if (getState() == AAUDIO_STREAM_STATE_STARTING) {
521 setState(AAUDIO_STREAM_STATE_STARTED);
522 }
Phil Burk204a1632017-01-03 17:23:43 -0800523 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800524 case AAUDIO_SERVICE_EVENT_PAUSED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700525 ALOGD("%s - got AAUDIO_SERVICE_EVENT_PAUSED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700526 if (getState() == AAUDIO_STREAM_STATE_PAUSING) {
527 setState(AAUDIO_STREAM_STATE_PAUSED);
528 }
Phil Burk204a1632017-01-03 17:23:43 -0800529 break;
Phil Burk71f35bb2017-04-13 16:05:07 -0700530 case AAUDIO_SERVICE_EVENT_STOPPED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700531 ALOGD("%s - got AAUDIO_SERVICE_EVENT_STOPPED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700532 if (getState() == AAUDIO_STREAM_STATE_STOPPING) {
533 setState(AAUDIO_STREAM_STATE_STOPPED);
534 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700535 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800536 case AAUDIO_SERVICE_EVENT_FLUSHED:
Phil Burkfbf031e2017-10-12 15:58:31 -0700537 ALOGD("%s - got AAUDIO_SERVICE_EVENT_FLUSHED", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700538 if (getState() == AAUDIO_STREAM_STATE_FLUSHING) {
539 setState(AAUDIO_STREAM_STATE_FLUSHED);
540 onFlushFromServer();
541 }
Phil Burk204a1632017-01-03 17:23:43 -0800542 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800543 case AAUDIO_SERVICE_EVENT_DISCONNECTED:
Phil Burkea04d972017-08-07 12:30:44 -0700544 // Prevent hardware from looping on old data and making buzzing sounds.
545 if (getDirection() == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700546 mAudioEndpoint->eraseDataMemory();
Phil Burkea04d972017-08-07 12:30:44 -0700547 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800548 result = AAUDIO_ERROR_DISCONNECTED;
Phil Burkc0c70e32017-02-09 13:18:38 -0800549 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
Phil Burkfbf031e2017-10-12 15:58:31 -0700550 ALOGW("%s - AAUDIO_SERVICE_EVENT_DISCONNECTED - FIFO cleared", __func__);
Phil Burk204a1632017-01-03 17:23:43 -0800551 break;
Phil Burkc0c70e32017-02-09 13:18:38 -0800552 case AAUDIO_SERVICE_EVENT_VOLUME:
Phil Burk55e5eab2018-04-10 15:16:38 -0700553 ALOGD("%s - AAUDIO_SERVICE_EVENT_VOLUME %lf", __func__, message->event.dataDouble);
Eric Laurenta2f296e2017-06-21 18:51:47 -0700554 mStreamVolume = (float)message->event.dataDouble;
555 doSetVolume();
Phil Burkc0c70e32017-02-09 13:18:38 -0800556 break;
Phil Burk23296382017-11-20 15:45:11 -0800557 case AAUDIO_SERVICE_EVENT_XRUN:
558 mXRunCount = static_cast<int32_t>(message->event.dataLong);
559 break;
Phil Burk204a1632017-01-03 17:23:43 -0800560 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700561 ALOGE("%s - Unrecognized event = %d", __func__, (int) message->event.event);
Phil Burk204a1632017-01-03 17:23:43 -0800562 break;
563 }
564 return result;
565}
566
Phil Burkbcc36742017-08-31 17:24:51 -0700567aaudio_result_t AudioStreamInternal::drainTimestampsFromService() {
568 aaudio_result_t result = AAUDIO_OK;
569
570 while (result == AAUDIO_OK) {
571 AAudioServiceMessage message;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700572 if (!mAudioEndpoint) {
573 break;
574 }
575 if (mAudioEndpoint->readUpCommand(&message) != 1) {
Phil Burkbcc36742017-08-31 17:24:51 -0700576 break; // no command this time, no problem
577 }
578 switch (message.what) {
579 // ignore most messages
580 case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
581 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
582 break;
583
584 case AAudioServiceMessage::code::EVENT:
585 result = onEventFromServer(&message);
586 break;
587
588 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700589 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
Phil Burkbcc36742017-08-31 17:24:51 -0700590 result = AAUDIO_ERROR_INTERNAL;
591 break;
592 }
593 }
594 return result;
595}
596
Phil Burk204a1632017-01-03 17:23:43 -0800597// Process all the commands coming from the server.
Phil Burk5ed503c2017-02-01 09:38:15 -0800598aaudio_result_t AudioStreamInternal::processCommands() {
599 aaudio_result_t result = AAUDIO_OK;
Phil Burk204a1632017-01-03 17:23:43 -0800600
Phil Burk5ed503c2017-02-01 09:38:15 -0800601 while (result == AAUDIO_OK) {
602 AAudioServiceMessage message;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700603 if (!mAudioEndpoint) {
604 break;
605 }
606 if (mAudioEndpoint->readUpCommand(&message) != 1) {
Phil Burk204a1632017-01-03 17:23:43 -0800607 break; // no command this time, no problem
608 }
609 switch (message.what) {
Phil Burk97350f92017-07-21 15:59:44 -0700610 case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
611 result = onTimestampService(&message);
612 break;
613
614 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
615 result = onTimestampHardware(&message);
Phil Burk204a1632017-01-03 17:23:43 -0800616 break;
617
Phil Burk5ed503c2017-02-01 09:38:15 -0800618 case AAudioServiceMessage::code::EVENT:
Phil Burk204a1632017-01-03 17:23:43 -0800619 result = onEventFromServer(&message);
620 break;
621
622 default:
Phil Burkfbf031e2017-10-12 15:58:31 -0700623 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
Phil Burk17fff382017-05-16 14:06:45 -0700624 result = AAUDIO_ERROR_INTERNAL;
Phil Burk204a1632017-01-03 17:23:43 -0800625 break;
626 }
627 }
628 return result;
629}
630
Phil Burk87c9f642017-05-17 07:22:39 -0700631// Read or write the data, block if needed and timeoutMillis > 0
632aaudio_result_t AudioStreamInternal::processData(void *buffer, int32_t numFrames,
633 int64_t timeoutNanoseconds)
Phil Burk204a1632017-01-03 17:23:43 -0800634{
Phil Burkfd34a932017-07-19 07:03:52 -0700635 const char * traceName = "aaProc";
636 const char * fifoName = "aaRdy";
Phil Burk4485d412017-05-09 15:55:02 -0700637 ATRACE_BEGIN(traceName);
Phil Burk4485d412017-05-09 15:55:02 -0700638 if (ATRACE_ENABLED()) {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700639 int32_t fullFrames = mAudioEndpoint->getFullFramesAvailable();
Phil Burkfd34a932017-07-19 07:03:52 -0700640 ATRACE_INT(fifoName, fullFrames);
Phil Burk4485d412017-05-09 15:55:02 -0700641 }
642
Phil Burkec89b2e2017-06-20 15:05:06 -0700643 aaudio_result_t result = AAUDIO_OK;
644 int32_t loopCount = 0;
645 uint8_t* audioData = (uint8_t*)buffer;
646 int64_t currentTimeNanos = AudioClock::getNanoseconds();
647 const int64_t entryTimeNanos = currentTimeNanos;
648 const int64_t deadlineNanos = currentTimeNanos + timeoutNanoseconds;
649 int32_t framesLeft = numFrames;
650
Phil Burk87c9f642017-05-17 07:22:39 -0700651 // Loop until all the data has been processed or until a timeout occurs.
Phil Burk204a1632017-01-03 17:23:43 -0800652 while (framesLeft > 0) {
Phil Burkec89b2e2017-06-20 15:05:06 -0700653 // The call to processDataNow() will not block. It will just process as much as it can.
Phil Burk3316d5e2017-02-15 11:23:01 -0800654 int64_t wakeTimeNanos = 0;
Phil Burk87c9f642017-05-17 07:22:39 -0700655 aaudio_result_t framesProcessed = processDataNow(audioData, framesLeft,
656 currentTimeNanos, &wakeTimeNanos);
657 if (framesProcessed < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700658 result = framesProcessed;
Phil Burk204a1632017-01-03 17:23:43 -0800659 break;
660 }
Phil Burk87c9f642017-05-17 07:22:39 -0700661 framesLeft -= (int32_t) framesProcessed;
662 audioData += framesProcessed * getBytesPerFrame();
Phil Burk204a1632017-01-03 17:23:43 -0800663
664 // Should we block?
665 if (timeoutNanoseconds == 0) {
666 break; // don't block
Phil Burk8d4f0062019-10-03 15:55:41 -0700667 } else if (wakeTimeNanos != 0) {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700668 if (!mAudioEndpoint->isFreeRunning()) {
Phil Burkfd34a932017-07-19 07:03:52 -0700669 // If there is software on the other end of the FIFO then it may get delayed.
670 // So wake up just a little after we expect it to be ready.
671 wakeTimeNanos += mWakeupDelayNanos;
Phil Burk204a1632017-01-03 17:23:43 -0800672 }
Phil Burkfd34a932017-07-19 07:03:52 -0700673
Phil Burk2bc7c182017-08-28 11:45:01 -0700674 currentTimeNanos = AudioClock::getNanoseconds();
675 int64_t earliestWakeTime = currentTimeNanos + mMinimumSleepNanos;
676 // Guarantee a minimum sleep time.
677 if (wakeTimeNanos < earliestWakeTime) {
678 wakeTimeNanos = earliestWakeTime;
679 }
680
Phil Burk204a1632017-01-03 17:23:43 -0800681 if (wakeTimeNanos > deadlineNanos) {
682 // If we time out, just return the framesWritten so far.
Phil Burkcf5f6d22017-05-26 12:35:07 -0700683 // TODO remove after we fix the deadline bug
Phil Burkfbf031e2017-10-12 15:58:31 -0700684 ALOGW("processData(): entered at %lld nanos, currently %lld",
Phil Burkec89b2e2017-06-20 15:05:06 -0700685 (long long) entryTimeNanos, (long long) currentTimeNanos);
Phil Burkfbf031e2017-10-12 15:58:31 -0700686 ALOGW("processData(): TIMEOUT after %lld nanos",
Phil Burkc0c70e32017-02-09 13:18:38 -0800687 (long long) timeoutNanoseconds);
Phil Burkfbf031e2017-10-12 15:58:31 -0700688 ALOGW("processData(): wakeTime = %lld, deadline = %lld nanos",
Phil Burk87c9f642017-05-17 07:22:39 -0700689 (long long) wakeTimeNanos, (long long) deadlineNanos);
Phil Burkfbf031e2017-10-12 15:58:31 -0700690 ALOGW("processData(): past deadline by %d micros",
Phil Burk87c9f642017-05-17 07:22:39 -0700691 (int)((wakeTimeNanos - deadlineNanos) / AAUDIO_NANOS_PER_MICROSECOND));
Phil Burkec89b2e2017-06-20 15:05:06 -0700692 mClockModel.dump();
Phil Burk5edc4ea2020-04-17 08:15:42 -0700693 mAudioEndpoint->dump();
Phil Burk204a1632017-01-03 17:23:43 -0800694 break;
695 }
696
Phil Burkfd34a932017-07-19 07:03:52 -0700697 if (ATRACE_ENABLED()) {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700698 int32_t fullFrames = mAudioEndpoint->getFullFramesAvailable();
Phil Burkfd34a932017-07-19 07:03:52 -0700699 ATRACE_INT(fifoName, fullFrames);
700 int64_t sleepForNanos = wakeTimeNanos - currentTimeNanos;
701 ATRACE_INT("aaSlpNs", (int32_t)sleepForNanos);
702 }
703
704 AudioClock::sleepUntilNanoTime(wakeTimeNanos);
Phil Burk204a1632017-01-03 17:23:43 -0800705 currentTimeNanos = AudioClock::getNanoseconds();
706 }
707 }
708
Phil Burkfd34a932017-07-19 07:03:52 -0700709 if (ATRACE_ENABLED()) {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700710 int32_t fullFrames = mAudioEndpoint->getFullFramesAvailable();
Phil Burkfd34a932017-07-19 07:03:52 -0700711 ATRACE_INT(fifoName, fullFrames);
712 }
713
Phil Burk87c9f642017-05-17 07:22:39 -0700714 // return error or framesProcessed
Phil Burkc0c70e32017-02-09 13:18:38 -0800715 (void) loopCount;
Phil Burk4485d412017-05-09 15:55:02 -0700716 ATRACE_END();
Phil Burk204a1632017-01-03 17:23:43 -0800717 return (result < 0) ? result : numFrames - framesLeft;
718}
719
Phil Burk3316d5e2017-02-15 11:23:01 -0800720void AudioStreamInternal::processTimestamp(uint64_t position, int64_t time) {
Phil Burk87c9f642017-05-17 07:22:39 -0700721 mClockModel.processTimestamp(position, time);
Phil Burk204a1632017-01-03 17:23:43 -0800722}
723
Phil Burk3316d5e2017-02-15 11:23:01 -0800724aaudio_result_t AudioStreamInternal::setBufferSize(int32_t requestedFrames) {
Phil Burk6479d502017-11-20 09:32:52 -0800725 int32_t adjustedFrames = requestedFrames;
Phil Burk8d4f0062019-10-03 15:55:41 -0700726 const int32_t maximumSize = getBufferCapacity() - mFramesPerBurst;
Phil Burk5347dca2020-04-08 16:31:07 -0700727 // Minimum size should be a multiple number of bursts.
728 const int32_t minimumSize = 1 * mFramesPerBurst;
Phil Burk6479d502017-11-20 09:32:52 -0800729
730 // Clip to minimum size so that rounding up will work better.
Phil Burk8d4f0062019-10-03 15:55:41 -0700731 adjustedFrames = std::max(minimumSize, adjustedFrames);
Phil Burk71f35bb2017-04-13 16:05:07 -0700732
Phil Burk8d4f0062019-10-03 15:55:41 -0700733 // Prevent arithmetic overflow by clipping before we round.
734 if (adjustedFrames >= maximumSize) {
Phil Burk6479d502017-11-20 09:32:52 -0800735 adjustedFrames = maximumSize;
736 } else {
737 // Round to the next highest burst size.
738 int32_t numBursts = (adjustedFrames + mFramesPerBurst - 1) / mFramesPerBurst;
739 adjustedFrames = numBursts * mFramesPerBurst;
Phil Burk5347dca2020-04-08 16:31:07 -0700740 // Clip just in case maximumSize is not a multiple of mFramesPerBurst.
741 adjustedFrames = std::min(maximumSize, adjustedFrames);
Phil Burk6479d502017-11-20 09:32:52 -0800742 }
743
Phil Burk5edc4ea2020-04-17 08:15:42 -0700744 if (mAudioEndpoint) {
745 // Clip against the actual size from the endpoint.
746 int32_t actualFrames = 0;
747 // Set to maximum size so we can write extra data when ready in order to reduce glitches.
748 // The amount we keep in the buffer is controlled by mBufferSizeInFrames.
749 mAudioEndpoint->setBufferSizeInFrames(maximumSize, &actualFrames);
750 // actualFrames should be <= actual maximum size of endpoint
751 adjustedFrames = std::min(actualFrames, adjustedFrames);
752 }
Phil Burk8d4f0062019-10-03 15:55:41 -0700753
754 mBufferSizeInFrames = adjustedFrames;
Phil Burk6c63ae32019-10-28 10:28:21 -0700755 ALOGV("%s(%d) returns %d", __func__, requestedFrames, adjustedFrames);
Phil Burk8d4f0062019-10-03 15:55:41 -0700756 return (aaudio_result_t) adjustedFrames;
Phil Burk204a1632017-01-03 17:23:43 -0800757}
758
Phil Burk87c9f642017-05-17 07:22:39 -0700759int32_t AudioStreamInternal::getBufferSize() const {
Phil Burk8d4f0062019-10-03 15:55:41 -0700760 return mBufferSizeInFrames;
Phil Burk204a1632017-01-03 17:23:43 -0800761}
762
Phil Burk87c9f642017-05-17 07:22:39 -0700763int32_t AudioStreamInternal::getBufferCapacity() const {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700764 return mBufferCapacityInFrames;
Phil Burk204a1632017-01-03 17:23:43 -0800765}
766
Phil Burk87c9f642017-05-17 07:22:39 -0700767int32_t AudioStreamInternal::getFramesPerBurst() const {
Phil Burk6479d502017-11-20 09:32:52 -0800768 return mFramesPerBurst;
Phil Burk204a1632017-01-03 17:23:43 -0800769}
770
Phil Burk13d3d832019-06-10 14:36:48 -0700771// This must be called under mStreamLock.
Phil Burk87c9f642017-05-17 07:22:39 -0700772aaudio_result_t AudioStreamInternal::joinThread(void** returnArg) {
773 return AudioStream::joinThread(returnArg, calculateReasonableTimeout(getFramesPerBurst()));
Phil Burk4c5129b2017-04-28 15:17:32 -0700774}
Phil Burk377c1c22018-12-12 16:06:54 -0800775
776bool AudioStreamInternal::isClockModelInControl() const {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700777 return isActive() && mAudioEndpoint->isFreeRunning() && mClockModel.isRunning();
Phil Burk377c1c22018-12-12 16:06:54 -0800778}