blob: 6337b538c215d09cf230bea58d9a5e18182b2f80 [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 Burkfbf031e2017-10-12 15:58:31 -070017#define LOG_TAG (mInService ? "AudioStreamInternalPlay_Service" \
18 : "AudioStreamInternalPlay_Client")
Phil Burk87c9f642017-05-17 07:22:39 -070019//#define LOG_NDEBUG 0
20#include <utils/Log.h>
21
Phil Burkfd34a932017-07-19 07:03:52 -070022#define ATRACE_TAG ATRACE_TAG_AUDIO
23
24#include <utils/Trace.h>
25
Phil Burk87c9f642017-05-17 07:22:39 -070026#include "client/AudioStreamInternalPlay.h"
27#include "utility/AudioClock.h"
28
29using android::WrappingBuffer;
30
31using namespace aaudio;
32
33AudioStreamInternalPlay::AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface,
34 bool inService)
35 : AudioStreamInternal(serviceInterface, inService) {
36
37}
38
39AudioStreamInternalPlay::~AudioStreamInternalPlay() {}
40
Phil Burk02fec702018-02-16 18:25:55 -080041constexpr int kRampMSec = 10; // time to apply a change in volume
42
43aaudio_result_t AudioStreamInternalPlay::open(const AudioStreamBuilder &builder) {
44 aaudio_result_t result = AudioStreamInternal::open(builder);
45 if (result == AAUDIO_OK) {
Phil Burk0127c1b2018-03-29 13:48:06 -070046 result = mFlowGraph.configure(getFormat(),
47 getSamplesPerFrame(),
48 getDeviceFormat(),
49 getDeviceChannelCount());
50
51 if (result != AAUDIO_OK) {
Phil Burk8b4e05e2019-12-17 12:12:09 -080052 releaseCloseFinal();
Phil Burk0127c1b2018-03-29 13:48:06 -070053 }
Phil Burk02fec702018-02-16 18:25:55 -080054 // Sample rate is constrained to common values by now and should not overflow.
55 int32_t numFrames = kRampMSec * getSampleRate() / AAUDIO_MILLIS_PER_SECOND;
Phil Burk0127c1b2018-03-29 13:48:06 -070056 mFlowGraph.setRampLengthInFrames(numFrames);
Phil Burk02fec702018-02-16 18:25:55 -080057 }
58 return result;
59}
60
Phil Burk13d3d832019-06-10 14:36:48 -070061// This must be called under mStreamLock.
Phil Burk5cc83c32017-11-28 15:43:18 -080062aaudio_result_t AudioStreamInternalPlay::requestPause()
Phil Burkb336e892017-07-05 15:35:43 -070063{
Phil Burk5cc83c32017-11-28 15:43:18 -080064 aaudio_result_t result = stopCallback();
65 if (result != AAUDIO_OK) {
66 return result;
67 }
Phil Burkb336e892017-07-05 15:35:43 -070068 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070069 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070070 return AAUDIO_ERROR_INVALID_STATE;
71 }
72
73 mClockModel.stop(AudioClock::getNanoseconds());
74 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burka53ffa62018-10-10 16:21:37 -070075 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -070076 return mServiceInterface.pauseStream(mServiceStreamHandle);
Phil Burkb336e892017-07-05 15:35:43 -070077}
78
Phil Burkb336e892017-07-05 15:35:43 -070079aaudio_result_t AudioStreamInternalPlay::requestFlush() {
80 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070081 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070082 return AAUDIO_ERROR_INVALID_STATE;
83 }
84
85 setState(AAUDIO_STREAM_STATE_FLUSHING);
86 return mServiceInterface.flushStream(mServiceStreamHandle);
87}
88
Phil Burkec8ca522020-05-19 10:05:58 -070089void AudioStreamInternalPlay::prepareBuffersForStart() {
90 // Prevent stale data from being played.
91 mAudioEndpoint->eraseDataMemory();
92}
93
94void AudioStreamInternalPlay::advanceClientToMatchServerPosition(int32_t serverMargin) {
95 int64_t readCounter = mAudioEndpoint->getDataReadCounter() + serverMargin;
Phil Burk5edc4ea2020-04-17 08:15:42 -070096 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter();
Phil Burkb336e892017-07-05 15:35:43 -070097
98 // Bump offset so caller does not see the retrograde motion in getFramesRead().
Phil Burkbcc36742017-08-31 17:24:51 -070099 int64_t offset = writeCounter - readCounter;
100 mFramesOffsetFromService += offset;
Phil Burk19e990e2018-03-22 13:59:34 -0700101 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
Phil Burkb336e892017-07-05 15:35:43 -0700102 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
103
Phil Burkbcc36742017-08-31 17:24:51 -0700104 // Force writeCounter to match readCounter.
105 // This is because we cannot change the read counter in the hardware.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700106 mAudioEndpoint->setDataWriteCounter(readCounter);
Phil Burkb336e892017-07-05 15:35:43 -0700107}
108
Phil Burkbcc36742017-08-31 17:24:51 -0700109void AudioStreamInternalPlay::onFlushFromServer() {
110 advanceClientToMatchServerPosition();
111}
112
Phil Burk87c9f642017-05-17 07:22:39 -0700113// Write the data, block if needed and timeoutMillis > 0
114aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
Phil Burk19e990e2018-03-22 13:59:34 -0700115 int64_t timeoutNanoseconds) {
Phil Burk87c9f642017-05-17 07:22:39 -0700116 return processData((void *)buffer, numFrames, timeoutNanoseconds);
117}
118
119// Write as much data as we can without blocking.
120aaudio_result_t AudioStreamInternalPlay::processDataNow(void *buffer, int32_t numFrames,
121 int64_t currentNanoTime, int64_t *wakeTimePtr) {
122 aaudio_result_t result = processCommands();
123 if (result != AAUDIO_OK) {
124 return result;
125 }
126
Phil Burkfd34a932017-07-19 07:03:52 -0700127 const char *traceName = "aaWrNow";
128 ATRACE_BEGIN(traceName);
129
Phil Burkbcc36742017-08-31 17:24:51 -0700130 if (mClockModel.isStarting()) {
131 // Still haven't got any timestamps from server.
132 // Keep waiting until we get some valid timestamps then start writing to the
133 // current buffer position.
Phil Burk55e5eab2018-04-10 15:16:38 -0700134 ALOGV("%s() wait for valid timestamps", __func__);
Phil Burkbcc36742017-08-31 17:24:51 -0700135 // Sleep very briefly and hope we get a timestamp soon.
136 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
137 ATRACE_END();
138 return 0;
139 }
140 // If we have gotten this far then we have at least one timestamp from server.
141
Phil Burkfd34a932017-07-19 07:03:52 -0700142 // 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 -0700143 if (mAudioEndpoint->isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700144 // Update data queue based on the timing model.
145 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
Phil Burkec89b2e2017-06-20 15:05:06 -0700146 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
Phil Burk5edc4ea2020-04-17 08:15:42 -0700147 mAudioEndpoint->setDataReadCounter(estimatedReadCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700148 }
Phil Burk87c9f642017-05-17 07:22:39 -0700149
Phil Burkbcc36742017-08-31 17:24:51 -0700150 if (mNeedCatchUp.isRequested()) {
151 // Catch an MMAP pointer that is already advancing.
152 // This will avoid initial underruns caused by a slow cold start.
Phil Burkec8ca522020-05-19 10:05:58 -0700153 // We add a one burst margin in case the DSP advances before we can write the data.
154 // This can help prevent the beginning of the stream from being skipped.
155 advanceClientToMatchServerPosition(getFramesPerBurst());
Phil Burkbcc36742017-08-31 17:24:51 -0700156 mNeedCatchUp.acknowledge();
157 }
158
Phil Burk87c9f642017-05-17 07:22:39 -0700159 // If the read index passed the write index then consider it an underrun.
Phil Burk23296382017-11-20 15:45:11 -0800160 // For shared streams, the xRunCount is passed up from the service.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700161 if (mAudioEndpoint->isFreeRunning() && mAudioEndpoint->getFullFramesAvailable() < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700162 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700163 if (ATRACE_ENABLED()) {
164 ATRACE_INT("aaUnderRuns", mXRunCount);
165 }
Phil Burk87c9f642017-05-17 07:22:39 -0700166 }
167
168 // Write some data to the buffer.
169 //ALOGD("AudioStreamInternal::processDataNow() - writeNowWithConversion(%d)", numFrames);
170 int32_t framesWritten = writeNowWithConversion(buffer, numFrames);
171 //ALOGD("AudioStreamInternal::processDataNow() - tried to write %d frames, wrote %d",
172 // numFrames, framesWritten);
Phil Burkfd34a932017-07-19 07:03:52 -0700173 if (ATRACE_ENABLED()) {
174 ATRACE_INT("aaWrote", framesWritten);
175 }
Phil Burk87c9f642017-05-17 07:22:39 -0700176
Phil Burk8d4f0062019-10-03 15:55:41 -0700177 // Sleep if there is too much data in the buffer.
Phil Burk87c9f642017-05-17 07:22:39 -0700178 // Calculate an ideal time to wake up.
Phil Burk8d4f0062019-10-03 15:55:41 -0700179 if (wakeTimePtr != nullptr
Phil Burk5edc4ea2020-04-17 08:15:42 -0700180 && (mAudioEndpoint->getFullFramesAvailable() >= getBufferSize())) {
Phil Burk87c9f642017-05-17 07:22:39 -0700181 // By default wake up a few milliseconds from now. // TODO review
182 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
183 aaudio_stream_state_t state = getState();
184 //ALOGD("AudioStreamInternal::processDataNow() - wakeTime based on %s",
185 // AAudio_convertStreamStateToText(state));
186 switch (state) {
187 case AAUDIO_STREAM_STATE_OPEN:
188 case AAUDIO_STREAM_STATE_STARTING:
189 if (framesWritten != 0) {
190 // Don't wait to write more data. Just prime the buffer.
191 wakeTime = currentNanoTime;
192 }
193 break;
Phil Burkfd34a932017-07-19 07:03:52 -0700194 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700195 {
Phil Burk8d4f0062019-10-03 15:55:41 -0700196 // Sleep until the readCounter catches up and we only have
197 // the getBufferSize() frames of data sitting in the buffer.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700198 int64_t nextReadPosition = mAudioEndpoint->getDataWriteCounter() - getBufferSize();
Phil Burk8d4f0062019-10-03 15:55:41 -0700199 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700200 }
201 break;
202 default:
203 break;
204 }
205 *wakeTimePtr = wakeTime;
206
207 }
Phil Burkfd34a932017-07-19 07:03:52 -0700208
209 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700210 return framesWritten;
211}
212
213
214aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
215 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700216 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800217 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700218 int32_t framesLeft = numFrames;
219
Phil Burk5edc4ea2020-04-17 08:15:42 -0700220 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700221
Phil Burkfd34a932017-07-19 07:03:52 -0700222 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700223 int partIndex = 0;
224 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
225 int32_t framesToWrite = framesLeft;
226 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
227 if (framesAvailable > 0) {
228 if (framesToWrite > framesAvailable) {
229 framesToWrite = framesAvailable;
230 }
Phil Burk41f19d82018-02-13 14:59:10 -0800231
Phil Burk87c9f642017-05-17 07:22:39 -0700232 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800233
Phil Burk0127c1b2018-03-29 13:48:06 -0700234 mFlowGraph.process((void *)byteBuffer,
235 wrappingBuffer.data[partIndex],
236 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800237
238 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700239 framesLeft -= framesToWrite;
240 } else {
241 break;
242 }
243 partIndex++;
244 }
245 int32_t framesWritten = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700246 mAudioEndpoint->advanceWriteIndex(framesWritten);
Phil Burk87c9f642017-05-17 07:22:39 -0700247
Phil Burk87c9f642017-05-17 07:22:39 -0700248 return framesWritten;
249}
250
Phil Burk377c1c22018-12-12 16:06:54 -0800251int64_t AudioStreamInternalPlay::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700252 if (mAudioEndpoint) {
253 const int64_t framesReadHardware = isClockModelInControl()
254 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
255 : mAudioEndpoint->getDataReadCounter();
256 // Add service offset and prevent retrograde motion.
257 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
258 }
Phil Burk377c1c22018-12-12 16:06:54 -0800259 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700260}
261
Phil Burk377c1c22018-12-12 16:06:54 -0800262int64_t AudioStreamInternalPlay::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700263 if (mAudioEndpoint) {
264 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
265 + mFramesOffsetFromService;
266 }
267 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700268}
269
270
271// Render audio in the application callback and then write the data to the stream.
272void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700273 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700274 aaudio_result_t result = AAUDIO_OK;
275 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
Phil Burk134f1972017-12-08 13:06:11 -0800276 if (!isDataCallbackSet()) return NULL;
Phil Burkfd34a932017-07-19 07:03:52 -0700277 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700278
279 // result might be a frame count
280 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
281 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700282 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700283
284 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700285 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burkbf821e22020-04-17 11:51:43 -0700286 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700287 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700288 if (result >= 0) {
289 // Only wrote some of the frames requested. Must have timed out.
290 result = AAUDIO_ERROR_TIMEOUT;
291 }
Phil Burk134f1972017-12-08 13:06:11 -0800292 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700293 break;
294 }
295 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800296 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk1e83bee2018-12-17 14:15:20 -0800297 result = systemStopFromCallback();
Phil Burk87c9f642017-05-17 07:22:39 -0700298 break;
299 }
300 }
301
Phil Burk19e990e2018-03-22 13:59:34 -0700302 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
303 __func__, result, (int) isActive());
Phil Burk87c9f642017-05-17 07:22:39 -0700304 return NULL;
305}
Phil Burk965650e2017-09-07 21:00:09 -0700306
307//------------------------------------------------------------------------------
308// Implementation of PlayerBase
309status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700310 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
311 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
312 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700313 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700314 return android::NO_ERROR;
315}