blob: b81e5e48b70e9f95b25aaedeb1cad37b115390e3 [file] [log] [blame]
Phil Burk87c9f642017-05-17 07:22:39 -07001/*
2 * Copyright (C) 2017 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 Burk87c9f642017-05-17 07:22:39 -070017//#define LOG_NDEBUG 0
18#include <utils/Log.h>
19
Phil Burkfd34a932017-07-19 07:03:52 -070020#define ATRACE_TAG ATRACE_TAG_AUDIO
21
22#include <utils/Trace.h>
23
Phil Burk87c9f642017-05-17 07:22:39 -070024#include "client/AudioStreamInternalPlay.h"
25#include "utility/AudioClock.h"
26
Phil Burk58f5ce12020-08-12 14:29:10 +000027// We do this after the #includes because if a header uses ALOG.
28// it would fail on the reference to mInService.
29#undef LOG_TAG
30// This file is used in both client and server processes.
31// This is needed to make sense of the logs more easily.
32#define LOG_TAG (mInService ? "AudioStreamInternalPlay_Service" \
33 : "AudioStreamInternalPlay_Client")
34
Ytai Ben-Tsvic5f45872020-08-18 10:39:44 -070035using android::status_t;
Phil Burk87c9f642017-05-17 07:22:39 -070036using android::WrappingBuffer;
37
38using namespace aaudio;
39
40AudioStreamInternalPlay::AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface,
41 bool inService)
42 : AudioStreamInternal(serviceInterface, inService) {
43
44}
45
46AudioStreamInternalPlay::~AudioStreamInternalPlay() {}
47
Phil Burk02fec702018-02-16 18:25:55 -080048constexpr int kRampMSec = 10; // time to apply a change in volume
49
50aaudio_result_t AudioStreamInternalPlay::open(const AudioStreamBuilder &builder) {
51 aaudio_result_t result = AudioStreamInternal::open(builder);
52 if (result == AAUDIO_OK) {
Phil Burk0127c1b2018-03-29 13:48:06 -070053 result = mFlowGraph.configure(getFormat(),
54 getSamplesPerFrame(),
55 getDeviceFormat(),
56 getDeviceChannelCount());
57
58 if (result != AAUDIO_OK) {
Phil Burkdd582922020-10-15 20:29:51 +000059 safeReleaseClose();
Phil Burk0127c1b2018-03-29 13:48:06 -070060 }
Phil Burk02fec702018-02-16 18:25:55 -080061 // Sample rate is constrained to common values by now and should not overflow.
62 int32_t numFrames = kRampMSec * getSampleRate() / AAUDIO_MILLIS_PER_SECOND;
Phil Burk0127c1b2018-03-29 13:48:06 -070063 mFlowGraph.setRampLengthInFrames(numFrames);
Phil Burk02fec702018-02-16 18:25:55 -080064 }
65 return result;
66}
67
Phil Burk13d3d832019-06-10 14:36:48 -070068// This must be called under mStreamLock.
Phil Burkdd582922020-10-15 20:29:51 +000069aaudio_result_t AudioStreamInternalPlay::requestPause_l()
Phil Burkb336e892017-07-05 15:35:43 -070070{
Phil Burkdd582922020-10-15 20:29:51 +000071 aaudio_result_t result = stopCallback_l();
Phil Burk5cc83c32017-11-28 15:43:18 -080072 if (result != AAUDIO_OK) {
73 return result;
74 }
Phil Burkb336e892017-07-05 15:35:43 -070075 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070076 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070077 return AAUDIO_ERROR_INVALID_STATE;
78 }
79
80 mClockModel.stop(AudioClock::getNanoseconds());
81 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burka53ffa62018-10-10 16:21:37 -070082 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -070083 return mServiceInterface.pauseStream(mServiceStreamHandle);
Phil Burkb336e892017-07-05 15:35:43 -070084}
85
Phil Burkdd582922020-10-15 20:29:51 +000086aaudio_result_t AudioStreamInternalPlay::requestFlush_l() {
Phil Burkb336e892017-07-05 15:35:43 -070087 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070088 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070089 return AAUDIO_ERROR_INVALID_STATE;
90 }
91
92 setState(AAUDIO_STREAM_STATE_FLUSHING);
93 return mServiceInterface.flushStream(mServiceStreamHandle);
94}
95
Phil Burkec8ca522020-05-19 10:05:58 -070096void AudioStreamInternalPlay::prepareBuffersForStart() {
97 // Prevent stale data from being played.
98 mAudioEndpoint->eraseDataMemory();
99}
100
101void AudioStreamInternalPlay::advanceClientToMatchServerPosition(int32_t serverMargin) {
102 int64_t readCounter = mAudioEndpoint->getDataReadCounter() + serverMargin;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700103 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter();
Phil Burkb336e892017-07-05 15:35:43 -0700104
105 // Bump offset so caller does not see the retrograde motion in getFramesRead().
Phil Burkbcc36742017-08-31 17:24:51 -0700106 int64_t offset = writeCounter - readCounter;
107 mFramesOffsetFromService += offset;
Phil Burk19e990e2018-03-22 13:59:34 -0700108 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
Phil Burkb336e892017-07-05 15:35:43 -0700109 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
110
Phil Burkbcc36742017-08-31 17:24:51 -0700111 // Force writeCounter to match readCounter.
112 // This is because we cannot change the read counter in the hardware.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700113 mAudioEndpoint->setDataWriteCounter(readCounter);
Phil Burkb336e892017-07-05 15:35:43 -0700114}
115
Phil Burkbcc36742017-08-31 17:24:51 -0700116void AudioStreamInternalPlay::onFlushFromServer() {
117 advanceClientToMatchServerPosition();
118}
119
Phil Burk87c9f642017-05-17 07:22:39 -0700120// Write the data, block if needed and timeoutMillis > 0
121aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
Phil Burk19e990e2018-03-22 13:59:34 -0700122 int64_t timeoutNanoseconds) {
Phil Burk87c9f642017-05-17 07:22:39 -0700123 return processData((void *)buffer, numFrames, timeoutNanoseconds);
124}
125
126// Write as much data as we can without blocking.
127aaudio_result_t AudioStreamInternalPlay::processDataNow(void *buffer, int32_t numFrames,
128 int64_t currentNanoTime, int64_t *wakeTimePtr) {
129 aaudio_result_t result = processCommands();
130 if (result != AAUDIO_OK) {
131 return result;
132 }
133
Phil Burkfd34a932017-07-19 07:03:52 -0700134 const char *traceName = "aaWrNow";
135 ATRACE_BEGIN(traceName);
136
Phil Burkbcc36742017-08-31 17:24:51 -0700137 if (mClockModel.isStarting()) {
138 // Still haven't got any timestamps from server.
139 // Keep waiting until we get some valid timestamps then start writing to the
140 // current buffer position.
Phil Burk55e5eab2018-04-10 15:16:38 -0700141 ALOGV("%s() wait for valid timestamps", __func__);
Phil Burkbcc36742017-08-31 17:24:51 -0700142 // Sleep very briefly and hope we get a timestamp soon.
143 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
144 ATRACE_END();
145 return 0;
146 }
147 // If we have gotten this far then we have at least one timestamp from server.
148
Phil Burkfd34a932017-07-19 07:03:52 -0700149 // If a DMA channel or DSP is reading the other end then we have to update the readCounter.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700150 if (mAudioEndpoint->isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700151 // Update data queue based on the timing model.
152 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
Phil Burkec89b2e2017-06-20 15:05:06 -0700153 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
Phil Burk5edc4ea2020-04-17 08:15:42 -0700154 mAudioEndpoint->setDataReadCounter(estimatedReadCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700155 }
Phil Burk87c9f642017-05-17 07:22:39 -0700156
Phil Burkbcc36742017-08-31 17:24:51 -0700157 if (mNeedCatchUp.isRequested()) {
158 // Catch an MMAP pointer that is already advancing.
159 // This will avoid initial underruns caused by a slow cold start.
Phil Burkec8ca522020-05-19 10:05:58 -0700160 // We add a one burst margin in case the DSP advances before we can write the data.
161 // This can help prevent the beginning of the stream from being skipped.
162 advanceClientToMatchServerPosition(getFramesPerBurst());
Phil Burkbcc36742017-08-31 17:24:51 -0700163 mNeedCatchUp.acknowledge();
164 }
165
Phil Burk87c9f642017-05-17 07:22:39 -0700166 // If the read index passed the write index then consider it an underrun.
Phil Burk23296382017-11-20 15:45:11 -0800167 // For shared streams, the xRunCount is passed up from the service.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700168 if (mAudioEndpoint->isFreeRunning() && mAudioEndpoint->getFullFramesAvailable() < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700169 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700170 if (ATRACE_ENABLED()) {
171 ATRACE_INT("aaUnderRuns", mXRunCount);
172 }
Phil Burk87c9f642017-05-17 07:22:39 -0700173 }
174
175 // Write some data to the buffer.
176 //ALOGD("AudioStreamInternal::processDataNow() - writeNowWithConversion(%d)", numFrames);
177 int32_t framesWritten = writeNowWithConversion(buffer, numFrames);
178 //ALOGD("AudioStreamInternal::processDataNow() - tried to write %d frames, wrote %d",
179 // numFrames, framesWritten);
Phil Burkfd34a932017-07-19 07:03:52 -0700180 if (ATRACE_ENABLED()) {
181 ATRACE_INT("aaWrote", framesWritten);
182 }
Phil Burk87c9f642017-05-17 07:22:39 -0700183
Phil Burk8d4f0062019-10-03 15:55:41 -0700184 // Sleep if there is too much data in the buffer.
Phil Burk87c9f642017-05-17 07:22:39 -0700185 // Calculate an ideal time to wake up.
Phil Burk8d4f0062019-10-03 15:55:41 -0700186 if (wakeTimePtr != nullptr
Phil Burk5edc4ea2020-04-17 08:15:42 -0700187 && (mAudioEndpoint->getFullFramesAvailable() >= getBufferSize())) {
Phil Burk87c9f642017-05-17 07:22:39 -0700188 // By default wake up a few milliseconds from now. // TODO review
189 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
190 aaudio_stream_state_t state = getState();
191 //ALOGD("AudioStreamInternal::processDataNow() - wakeTime based on %s",
192 // AAudio_convertStreamStateToText(state));
193 switch (state) {
194 case AAUDIO_STREAM_STATE_OPEN:
195 case AAUDIO_STREAM_STATE_STARTING:
196 if (framesWritten != 0) {
197 // Don't wait to write more data. Just prime the buffer.
198 wakeTime = currentNanoTime;
199 }
200 break;
Phil Burkfd34a932017-07-19 07:03:52 -0700201 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700202 {
Phil Burk8d4f0062019-10-03 15:55:41 -0700203 // Sleep until the readCounter catches up and we only have
204 // the getBufferSize() frames of data sitting in the buffer.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700205 int64_t nextReadPosition = mAudioEndpoint->getDataWriteCounter() - getBufferSize();
Phil Burk8d4f0062019-10-03 15:55:41 -0700206 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700207 }
208 break;
209 default:
210 break;
211 }
212 *wakeTimePtr = wakeTime;
213
214 }
Phil Burkfd34a932017-07-19 07:03:52 -0700215
216 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700217 return framesWritten;
218}
219
220
221aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
222 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700223 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800224 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700225 int32_t framesLeft = numFrames;
226
Phil Burk5edc4ea2020-04-17 08:15:42 -0700227 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700228
Phil Burkfd34a932017-07-19 07:03:52 -0700229 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700230 int partIndex = 0;
231 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
232 int32_t framesToWrite = framesLeft;
233 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
234 if (framesAvailable > 0) {
235 if (framesToWrite > framesAvailable) {
236 framesToWrite = framesAvailable;
237 }
Phil Burk41f19d82018-02-13 14:59:10 -0800238
Phil Burk87c9f642017-05-17 07:22:39 -0700239 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800240
Phil Burk0127c1b2018-03-29 13:48:06 -0700241 mFlowGraph.process((void *)byteBuffer,
242 wrappingBuffer.data[partIndex],
243 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800244
245 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700246 framesLeft -= framesToWrite;
247 } else {
248 break;
249 }
250 partIndex++;
251 }
252 int32_t framesWritten = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700253 mAudioEndpoint->advanceWriteIndex(framesWritten);
Phil Burk87c9f642017-05-17 07:22:39 -0700254
Phil Burk87c9f642017-05-17 07:22:39 -0700255 return framesWritten;
256}
257
Phil Burk377c1c22018-12-12 16:06:54 -0800258int64_t AudioStreamInternalPlay::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700259 if (mAudioEndpoint) {
260 const int64_t framesReadHardware = isClockModelInControl()
261 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
262 : mAudioEndpoint->getDataReadCounter();
263 // Add service offset and prevent retrograde motion.
264 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
265 }
Phil Burk377c1c22018-12-12 16:06:54 -0800266 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700267}
268
Phil Burk377c1c22018-12-12 16:06:54 -0800269int64_t AudioStreamInternalPlay::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700270 if (mAudioEndpoint) {
271 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
272 + mFramesOffsetFromService;
273 }
274 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700275}
276
277
278// Render audio in the application callback and then write the data to the stream.
279void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700280 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700281 aaudio_result_t result = AAUDIO_OK;
282 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
Phil Burk134f1972017-12-08 13:06:11 -0800283 if (!isDataCallbackSet()) return NULL;
Phil Burkfd34a932017-07-19 07:03:52 -0700284 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700285
286 // result might be a frame count
287 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
288 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700289 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700290
291 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700292 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burkbf821e22020-04-17 11:51:43 -0700293 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700294 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700295 if (result >= 0) {
296 // Only wrote some of the frames requested. Must have timed out.
297 result = AAUDIO_ERROR_TIMEOUT;
298 }
Phil Burk134f1972017-12-08 13:06:11 -0800299 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700300 break;
301 }
302 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800303 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk1e83bee2018-12-17 14:15:20 -0800304 result = systemStopFromCallback();
Phil Burk87c9f642017-05-17 07:22:39 -0700305 break;
306 }
307 }
308
Phil Burk19e990e2018-03-22 13:59:34 -0700309 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
310 __func__, result, (int) isActive());
Phil Burk87c9f642017-05-17 07:22:39 -0700311 return NULL;
312}
Phil Burk965650e2017-09-07 21:00:09 -0700313
314//------------------------------------------------------------------------------
315// Implementation of PlayerBase
316status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700317 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
318 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
319 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700320 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700321 return android::NO_ERROR;
322}