blob: d6b73b4773845621980c61d9b9cbda9da0118cb4 [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 Burk79224ca2020-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
Phil Burk87c9f642017-05-17 07:22:39 -070035using android::WrappingBuffer;
36
37using namespace aaudio;
38
39AudioStreamInternalPlay::AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface,
40 bool inService)
41 : AudioStreamInternal(serviceInterface, inService) {
42
43}
44
45AudioStreamInternalPlay::~AudioStreamInternalPlay() {}
46
Phil Burk02fec702018-02-16 18:25:55 -080047constexpr int kRampMSec = 10; // time to apply a change in volume
48
49aaudio_result_t AudioStreamInternalPlay::open(const AudioStreamBuilder &builder) {
50 aaudio_result_t result = AudioStreamInternal::open(builder);
51 if (result == AAUDIO_OK) {
Phil Burk0127c1b2018-03-29 13:48:06 -070052 result = mFlowGraph.configure(getFormat(),
53 getSamplesPerFrame(),
54 getDeviceFormat(),
55 getDeviceChannelCount());
56
57 if (result != AAUDIO_OK) {
Phil Burk8b4e05e2019-12-17 12:12:09 -080058 releaseCloseFinal();
Phil Burk0127c1b2018-03-29 13:48:06 -070059 }
Phil Burk02fec702018-02-16 18:25:55 -080060 // Sample rate is constrained to common values by now and should not overflow.
61 int32_t numFrames = kRampMSec * getSampleRate() / AAUDIO_MILLIS_PER_SECOND;
Phil Burk0127c1b2018-03-29 13:48:06 -070062 mFlowGraph.setRampLengthInFrames(numFrames);
Phil Burk02fec702018-02-16 18:25:55 -080063 }
64 return result;
65}
66
Phil Burk13d3d832019-06-10 14:36:48 -070067// This must be called under mStreamLock.
Phil Burk5cc83c32017-11-28 15:43:18 -080068aaudio_result_t AudioStreamInternalPlay::requestPause()
Phil Burkb336e892017-07-05 15:35:43 -070069{
Phil Burk5cc83c32017-11-28 15:43:18 -080070 aaudio_result_t result = stopCallback();
71 if (result != AAUDIO_OK) {
72 return result;
73 }
Phil Burkb336e892017-07-05 15:35:43 -070074 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070075 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070076 return AAUDIO_ERROR_INVALID_STATE;
77 }
78
79 mClockModel.stop(AudioClock::getNanoseconds());
80 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burka53ffa62018-10-10 16:21:37 -070081 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -070082 return mServiceInterface.pauseStream(mServiceStreamHandle);
Phil Burkb336e892017-07-05 15:35:43 -070083}
84
Phil Burkb336e892017-07-05 15:35:43 -070085aaudio_result_t AudioStreamInternalPlay::requestFlush() {
86 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070087 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070088 return AAUDIO_ERROR_INVALID_STATE;
89 }
90
91 setState(AAUDIO_STREAM_STATE_FLUSHING);
92 return mServiceInterface.flushStream(mServiceStreamHandle);
93}
94
Phil Burkbcc36742017-08-31 17:24:51 -070095void AudioStreamInternalPlay::advanceClientToMatchServerPosition() {
Phil Burk5edc4ea2020-04-17 08:15:42 -070096 int64_t readCounter = mAudioEndpoint->getDataReadCounter();
97 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter();
Phil Burkb336e892017-07-05 15:35:43 -070098
99 // Bump offset so caller does not see the retrograde motion in getFramesRead().
Phil Burkbcc36742017-08-31 17:24:51 -0700100 int64_t offset = writeCounter - readCounter;
101 mFramesOffsetFromService += offset;
Phil Burk19e990e2018-03-22 13:59:34 -0700102 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
Phil Burkb336e892017-07-05 15:35:43 -0700103 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
104
Phil Burkbcc36742017-08-31 17:24:51 -0700105 // Force writeCounter to match readCounter.
106 // This is because we cannot change the read counter in the hardware.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700107 mAudioEndpoint->setDataWriteCounter(readCounter);
Phil Burkb336e892017-07-05 15:35:43 -0700108}
109
Phil Burkbcc36742017-08-31 17:24:51 -0700110void AudioStreamInternalPlay::onFlushFromServer() {
111 advanceClientToMatchServerPosition();
112}
113
Phil Burk87c9f642017-05-17 07:22:39 -0700114// Write the data, block if needed and timeoutMillis > 0
115aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
Phil Burk19e990e2018-03-22 13:59:34 -0700116 int64_t timeoutNanoseconds) {
Phil Burk87c9f642017-05-17 07:22:39 -0700117 return processData((void *)buffer, numFrames, timeoutNanoseconds);
118}
119
120// Write as much data as we can without blocking.
121aaudio_result_t AudioStreamInternalPlay::processDataNow(void *buffer, int32_t numFrames,
122 int64_t currentNanoTime, int64_t *wakeTimePtr) {
123 aaudio_result_t result = processCommands();
124 if (result != AAUDIO_OK) {
125 return result;
126 }
127
Phil Burkfd34a932017-07-19 07:03:52 -0700128 const char *traceName = "aaWrNow";
129 ATRACE_BEGIN(traceName);
130
Phil Burkbcc36742017-08-31 17:24:51 -0700131 if (mClockModel.isStarting()) {
132 // Still haven't got any timestamps from server.
133 // Keep waiting until we get some valid timestamps then start writing to the
134 // current buffer position.
Phil Burk55e5eab2018-04-10 15:16:38 -0700135 ALOGV("%s() wait for valid timestamps", __func__);
Phil Burkbcc36742017-08-31 17:24:51 -0700136 // Sleep very briefly and hope we get a timestamp soon.
137 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
138 ATRACE_END();
139 return 0;
140 }
141 // If we have gotten this far then we have at least one timestamp from server.
142
Phil Burkfd34a932017-07-19 07:03:52 -0700143 // 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 -0700144 if (mAudioEndpoint->isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700145 // Update data queue based on the timing model.
146 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
Phil Burkec89b2e2017-06-20 15:05:06 -0700147 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
Phil Burk5edc4ea2020-04-17 08:15:42 -0700148 mAudioEndpoint->setDataReadCounter(estimatedReadCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700149 }
Phil Burk87c9f642017-05-17 07:22:39 -0700150
Phil Burkbcc36742017-08-31 17:24:51 -0700151 if (mNeedCatchUp.isRequested()) {
152 // Catch an MMAP pointer that is already advancing.
153 // This will avoid initial underruns caused by a slow cold start.
154 advanceClientToMatchServerPosition();
155 mNeedCatchUp.acknowledge();
156 }
157
Phil Burk87c9f642017-05-17 07:22:39 -0700158 // If the read index passed the write index then consider it an underrun.
Phil Burk23296382017-11-20 15:45:11 -0800159 // For shared streams, the xRunCount is passed up from the service.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700160 if (mAudioEndpoint->isFreeRunning() && mAudioEndpoint->getFullFramesAvailable() < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700161 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700162 if (ATRACE_ENABLED()) {
163 ATRACE_INT("aaUnderRuns", mXRunCount);
164 }
Phil Burk87c9f642017-05-17 07:22:39 -0700165 }
166
167 // Write some data to the buffer.
168 //ALOGD("AudioStreamInternal::processDataNow() - writeNowWithConversion(%d)", numFrames);
169 int32_t framesWritten = writeNowWithConversion(buffer, numFrames);
170 //ALOGD("AudioStreamInternal::processDataNow() - tried to write %d frames, wrote %d",
171 // numFrames, framesWritten);
Phil Burkfd34a932017-07-19 07:03:52 -0700172 if (ATRACE_ENABLED()) {
173 ATRACE_INT("aaWrote", framesWritten);
174 }
Phil Burk87c9f642017-05-17 07:22:39 -0700175
Phil Burk8d4f0062019-10-03 15:55:41 -0700176 // Sleep if there is too much data in the buffer.
Phil Burk87c9f642017-05-17 07:22:39 -0700177 // Calculate an ideal time to wake up.
Phil Burk8d4f0062019-10-03 15:55:41 -0700178 if (wakeTimePtr != nullptr
Phil Burk5edc4ea2020-04-17 08:15:42 -0700179 && (mAudioEndpoint->getFullFramesAvailable() >= getBufferSize())) {
Phil Burk87c9f642017-05-17 07:22:39 -0700180 // By default wake up a few milliseconds from now. // TODO review
181 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
182 aaudio_stream_state_t state = getState();
183 //ALOGD("AudioStreamInternal::processDataNow() - wakeTime based on %s",
184 // AAudio_convertStreamStateToText(state));
185 switch (state) {
186 case AAUDIO_STREAM_STATE_OPEN:
187 case AAUDIO_STREAM_STATE_STARTING:
188 if (framesWritten != 0) {
189 // Don't wait to write more data. Just prime the buffer.
190 wakeTime = currentNanoTime;
191 }
192 break;
Phil Burkfd34a932017-07-19 07:03:52 -0700193 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700194 {
Phil Burk8d4f0062019-10-03 15:55:41 -0700195 // Sleep until the readCounter catches up and we only have
196 // the getBufferSize() frames of data sitting in the buffer.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700197 int64_t nextReadPosition = mAudioEndpoint->getDataWriteCounter() - getBufferSize();
Phil Burk8d4f0062019-10-03 15:55:41 -0700198 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700199 }
200 break;
201 default:
202 break;
203 }
204 *wakeTimePtr = wakeTime;
205
206 }
Phil Burkfd34a932017-07-19 07:03:52 -0700207
208 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700209 return framesWritten;
210}
211
212
213aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
214 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700215 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800216 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700217 int32_t framesLeft = numFrames;
218
Phil Burk5edc4ea2020-04-17 08:15:42 -0700219 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700220
Phil Burkfd34a932017-07-19 07:03:52 -0700221 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700222 int partIndex = 0;
223 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
224 int32_t framesToWrite = framesLeft;
225 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
226 if (framesAvailable > 0) {
227 if (framesToWrite > framesAvailable) {
228 framesToWrite = framesAvailable;
229 }
Phil Burk41f19d82018-02-13 14:59:10 -0800230
Phil Burk87c9f642017-05-17 07:22:39 -0700231 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800232
Phil Burk0127c1b2018-03-29 13:48:06 -0700233 mFlowGraph.process((void *)byteBuffer,
234 wrappingBuffer.data[partIndex],
235 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800236
237 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700238 framesLeft -= framesToWrite;
239 } else {
240 break;
241 }
242 partIndex++;
243 }
244 int32_t framesWritten = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700245 mAudioEndpoint->advanceWriteIndex(framesWritten);
Phil Burk87c9f642017-05-17 07:22:39 -0700246
Phil Burk87c9f642017-05-17 07:22:39 -0700247 return framesWritten;
248}
249
Phil Burk377c1c22018-12-12 16:06:54 -0800250int64_t AudioStreamInternalPlay::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700251 if (mAudioEndpoint) {
252 const int64_t framesReadHardware = isClockModelInControl()
253 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
254 : mAudioEndpoint->getDataReadCounter();
255 // Add service offset and prevent retrograde motion.
256 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
257 }
Phil Burk377c1c22018-12-12 16:06:54 -0800258 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700259}
260
Phil Burk377c1c22018-12-12 16:06:54 -0800261int64_t AudioStreamInternalPlay::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700262 if (mAudioEndpoint) {
263 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
264 + mFramesOffsetFromService;
265 }
266 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700267}
268
269
270// Render audio in the application callback and then write the data to the stream.
271void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700272 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700273 aaudio_result_t result = AAUDIO_OK;
274 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
Phil Burk134f1972017-12-08 13:06:11 -0800275 if (!isDataCallbackSet()) return NULL;
Phil Burkfd34a932017-07-19 07:03:52 -0700276 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700277
278 // result might be a frame count
279 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
280 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700281 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700282
283 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700284 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burkbf821e22020-04-17 11:51:43 -0700285 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700286 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700287 if (result >= 0) {
288 // Only wrote some of the frames requested. Must have timed out.
289 result = AAUDIO_ERROR_TIMEOUT;
290 }
Phil Burk134f1972017-12-08 13:06:11 -0800291 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700292 break;
293 }
294 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800295 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk1e83bee2018-12-17 14:15:20 -0800296 result = systemStopFromCallback();
Phil Burk87c9f642017-05-17 07:22:39 -0700297 break;
298 }
299 }
300
Phil Burk19e990e2018-03-22 13:59:34 -0700301 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
302 __func__, result, (int) isActive());
Phil Burk87c9f642017-05-17 07:22:39 -0700303 return NULL;
304}
Phil Burk965650e2017-09-07 21:00:09 -0700305
306//------------------------------------------------------------------------------
307// Implementation of PlayerBase
308status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700309 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
310 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
311 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700312 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700313 return android::NO_ERROR;
314}