blob: 450d39012209c2a5c2a25873f7458fa7a8bdb5c9 [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
jiabin97247ea2021-04-07 00:33:38 +000022#include <media/MediaMetricsItem.h>
Phil Burkfd34a932017-07-19 07:03:52 -070023#include <utils/Trace.h>
24
Phil Burk87c9f642017-05-17 07:22:39 -070025#include "client/AudioStreamInternalPlay.h"
26#include "utility/AudioClock.h"
27
Phil Burk58f5ce12020-08-12 14:29:10 +000028// We do this after the #includes because if a header uses ALOG.
29// it would fail on the reference to mInService.
30#undef LOG_TAG
31// This file is used in both client and server processes.
32// This is needed to make sense of the logs more easily.
33#define LOG_TAG (mInService ? "AudioStreamInternalPlay_Service" \
34 : "AudioStreamInternalPlay_Client")
35
Ytai Ben-Tsvic5f45872020-08-18 10:39:44 -070036using android::status_t;
Phil Burk87c9f642017-05-17 07:22:39 -070037using android::WrappingBuffer;
38
39using namespace aaudio;
40
41AudioStreamInternalPlay::AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface,
42 bool inService)
43 : AudioStreamInternal(serviceInterface, inService) {
44
45}
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(),
Robert Wud7400832021-12-04 01:11:19 +000055 getDeviceChannelCount(),
Robert Wu8393bed2021-12-08 02:08:48 +000056 getRequireMonoBlend(),
Robert Wub7e30fa2021-12-09 01:00:16 +000057 getAudioBalance(),
58 (getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE));
Phil Burk0127c1b2018-03-29 13:48:06 -070059
60 if (result != AAUDIO_OK) {
Phil Burkdd582922020-10-15 20:29:51 +000061 safeReleaseClose();
Phil Burk0127c1b2018-03-29 13:48:06 -070062 }
Phil Burk02fec702018-02-16 18:25:55 -080063 // Sample rate is constrained to common values by now and should not overflow.
64 int32_t numFrames = kRampMSec * getSampleRate() / AAUDIO_MILLIS_PER_SECOND;
Phil Burk0127c1b2018-03-29 13:48:06 -070065 mFlowGraph.setRampLengthInFrames(numFrames);
Phil Burk02fec702018-02-16 18:25:55 -080066 }
67 return result;
68}
69
Phil Burk13d3d832019-06-10 14:36:48 -070070// This must be called under mStreamLock.
Phil Burkdd582922020-10-15 20:29:51 +000071aaudio_result_t AudioStreamInternalPlay::requestPause_l()
Phil Burkb336e892017-07-05 15:35:43 -070072{
Phil Burkdd582922020-10-15 20:29:51 +000073 aaudio_result_t result = stopCallback_l();
Phil Burk5cc83c32017-11-28 15:43:18 -080074 if (result != AAUDIO_OK) {
75 return result;
76 }
Phil Burkb336e892017-07-05 15:35:43 -070077 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070078 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070079 return AAUDIO_ERROR_INVALID_STATE;
80 }
81
82 mClockModel.stop(AudioClock::getNanoseconds());
83 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burka53ffa62018-10-10 16:21:37 -070084 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -070085 return mServiceInterface.pauseStream(mServiceStreamHandle);
Phil Burkb336e892017-07-05 15:35:43 -070086}
87
Phil Burkdd582922020-10-15 20:29:51 +000088aaudio_result_t AudioStreamInternalPlay::requestFlush_l() {
Phil Burkb336e892017-07-05 15:35:43 -070089 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070090 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070091 return AAUDIO_ERROR_INVALID_STATE;
92 }
93
94 setState(AAUDIO_STREAM_STATE_FLUSHING);
95 return mServiceInterface.flushStream(mServiceStreamHandle);
96}
97
Phil Burkec8ca522020-05-19 10:05:58 -070098void AudioStreamInternalPlay::prepareBuffersForStart() {
99 // Prevent stale data from being played.
100 mAudioEndpoint->eraseDataMemory();
101}
102
103void AudioStreamInternalPlay::advanceClientToMatchServerPosition(int32_t serverMargin) {
104 int64_t readCounter = mAudioEndpoint->getDataReadCounter() + serverMargin;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700105 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter();
Phil Burkb336e892017-07-05 15:35:43 -0700106
107 // Bump offset so caller does not see the retrograde motion in getFramesRead().
Phil Burkbcc36742017-08-31 17:24:51 -0700108 int64_t offset = writeCounter - readCounter;
109 mFramesOffsetFromService += offset;
Phil Burk19e990e2018-03-22 13:59:34 -0700110 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
Phil Burkb336e892017-07-05 15:35:43 -0700111 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
112
Phil Burkbcc36742017-08-31 17:24:51 -0700113 // Force writeCounter to match readCounter.
114 // This is because we cannot change the read counter in the hardware.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700115 mAudioEndpoint->setDataWriteCounter(readCounter);
Phil Burkb336e892017-07-05 15:35:43 -0700116}
117
Phil Burkbcc36742017-08-31 17:24:51 -0700118void AudioStreamInternalPlay::onFlushFromServer() {
jiabind5bd06a2021-04-27 22:04:08 +0000119 advanceClientToMatchServerPosition(0 /*serverMargin*/);
Phil Burkbcc36742017-08-31 17:24:51 -0700120}
121
Phil Burk87c9f642017-05-17 07:22:39 -0700122// Write the data, block if needed and timeoutMillis > 0
123aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
Phil Burk19e990e2018-03-22 13:59:34 -0700124 int64_t timeoutNanoseconds) {
Phil Burk87c9f642017-05-17 07:22:39 -0700125 return processData((void *)buffer, numFrames, timeoutNanoseconds);
126}
127
128// Write as much data as we can without blocking.
129aaudio_result_t AudioStreamInternalPlay::processDataNow(void *buffer, int32_t numFrames,
130 int64_t currentNanoTime, int64_t *wakeTimePtr) {
131 aaudio_result_t result = processCommands();
132 if (result != AAUDIO_OK) {
133 return result;
134 }
135
Phil Burkfd34a932017-07-19 07:03:52 -0700136 const char *traceName = "aaWrNow";
137 ATRACE_BEGIN(traceName);
138
Phil Burkbcc36742017-08-31 17:24:51 -0700139 if (mClockModel.isStarting()) {
140 // Still haven't got any timestamps from server.
141 // Keep waiting until we get some valid timestamps then start writing to the
142 // current buffer position.
Phil Burk55e5eab2018-04-10 15:16:38 -0700143 ALOGV("%s() wait for valid timestamps", __func__);
Phil Burkbcc36742017-08-31 17:24:51 -0700144 // Sleep very briefly and hope we get a timestamp soon.
145 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
146 ATRACE_END();
147 return 0;
148 }
149 // If we have gotten this far then we have at least one timestamp from server.
150
Phil Burkfd34a932017-07-19 07:03:52 -0700151 // 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 -0700152 if (mAudioEndpoint->isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700153 // Update data queue based on the timing model.
154 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
Phil Burkec89b2e2017-06-20 15:05:06 -0700155 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
Phil Burk5edc4ea2020-04-17 08:15:42 -0700156 mAudioEndpoint->setDataReadCounter(estimatedReadCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700157 }
Phil Burk87c9f642017-05-17 07:22:39 -0700158
Phil Burkbcc36742017-08-31 17:24:51 -0700159 if (mNeedCatchUp.isRequested()) {
160 // Catch an MMAP pointer that is already advancing.
161 // This will avoid initial underruns caused by a slow cold start.
Phil Burkec8ca522020-05-19 10:05:58 -0700162 // We add a one burst margin in case the DSP advances before we can write the data.
163 // This can help prevent the beginning of the stream from being skipped.
164 advanceClientToMatchServerPosition(getFramesPerBurst());
Phil Burkbcc36742017-08-31 17:24:51 -0700165 mNeedCatchUp.acknowledge();
166 }
167
Phil Burk87c9f642017-05-17 07:22:39 -0700168 // If the read index passed the write index then consider it an underrun.
Phil Burk23296382017-11-20 15:45:11 -0800169 // For shared streams, the xRunCount is passed up from the service.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700170 if (mAudioEndpoint->isFreeRunning() && mAudioEndpoint->getFullFramesAvailable() < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700171 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700172 if (ATRACE_ENABLED()) {
173 ATRACE_INT("aaUnderRuns", mXRunCount);
174 }
Phil Burk87c9f642017-05-17 07:22:39 -0700175 }
176
177 // Write some data to the buffer.
178 //ALOGD("AudioStreamInternal::processDataNow() - writeNowWithConversion(%d)", numFrames);
179 int32_t framesWritten = writeNowWithConversion(buffer, numFrames);
180 //ALOGD("AudioStreamInternal::processDataNow() - tried to write %d frames, wrote %d",
181 // numFrames, framesWritten);
Phil Burkfd34a932017-07-19 07:03:52 -0700182 if (ATRACE_ENABLED()) {
183 ATRACE_INT("aaWrote", framesWritten);
184 }
Phil Burk87c9f642017-05-17 07:22:39 -0700185
Phil Burk8d4f0062019-10-03 15:55:41 -0700186 // Sleep if there is too much data in the buffer.
Phil Burk87c9f642017-05-17 07:22:39 -0700187 // Calculate an ideal time to wake up.
Phil Burk8d4f0062019-10-03 15:55:41 -0700188 if (wakeTimePtr != nullptr
Phil Burk5edc4ea2020-04-17 08:15:42 -0700189 && (mAudioEndpoint->getFullFramesAvailable() >= getBufferSize())) {
Phil Burk87c9f642017-05-17 07:22:39 -0700190 // By default wake up a few milliseconds from now. // TODO review
191 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
192 aaudio_stream_state_t state = getState();
193 //ALOGD("AudioStreamInternal::processDataNow() - wakeTime based on %s",
194 // AAudio_convertStreamStateToText(state));
195 switch (state) {
196 case AAUDIO_STREAM_STATE_OPEN:
197 case AAUDIO_STREAM_STATE_STARTING:
198 if (framesWritten != 0) {
199 // Don't wait to write more data. Just prime the buffer.
200 wakeTime = currentNanoTime;
201 }
202 break;
Phil Burkfd34a932017-07-19 07:03:52 -0700203 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700204 {
Phil Burk8d4f0062019-10-03 15:55:41 -0700205 // Sleep until the readCounter catches up and we only have
206 // the getBufferSize() frames of data sitting in the buffer.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700207 int64_t nextReadPosition = mAudioEndpoint->getDataWriteCounter() - getBufferSize();
Phil Burk8d4f0062019-10-03 15:55:41 -0700208 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700209 }
210 break;
211 default:
212 break;
213 }
214 *wakeTimePtr = wakeTime;
215
216 }
Phil Burkfd34a932017-07-19 07:03:52 -0700217
218 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700219 return framesWritten;
220}
221
222
223aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
224 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700225 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800226 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700227 int32_t framesLeft = numFrames;
228
Phil Burk5edc4ea2020-04-17 08:15:42 -0700229 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700230
Phil Burkfd34a932017-07-19 07:03:52 -0700231 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700232 int partIndex = 0;
233 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
234 int32_t framesToWrite = framesLeft;
235 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
236 if (framesAvailable > 0) {
237 if (framesToWrite > framesAvailable) {
238 framesToWrite = framesAvailable;
239 }
Phil Burk41f19d82018-02-13 14:59:10 -0800240
Phil Burk87c9f642017-05-17 07:22:39 -0700241 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800242
Phil Burk0127c1b2018-03-29 13:48:06 -0700243 mFlowGraph.process((void *)byteBuffer,
244 wrappingBuffer.data[partIndex],
245 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800246
247 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700248 framesLeft -= framesToWrite;
249 } else {
250 break;
251 }
252 partIndex++;
253 }
254 int32_t framesWritten = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700255 mAudioEndpoint->advanceWriteIndex(framesWritten);
Phil Burk87c9f642017-05-17 07:22:39 -0700256
Phil Burk87c9f642017-05-17 07:22:39 -0700257 return framesWritten;
258}
259
Phil Burk377c1c22018-12-12 16:06:54 -0800260int64_t AudioStreamInternalPlay::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700261 if (mAudioEndpoint) {
262 const int64_t framesReadHardware = isClockModelInControl()
263 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
264 : mAudioEndpoint->getDataReadCounter();
265 // Add service offset and prevent retrograde motion.
266 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
267 }
Phil Burk377c1c22018-12-12 16:06:54 -0800268 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700269}
270
Phil Burk377c1c22018-12-12 16:06:54 -0800271int64_t AudioStreamInternalPlay::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700272 if (mAudioEndpoint) {
273 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
274 + mFramesOffsetFromService;
275 }
276 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700277}
278
279
280// Render audio in the application callback and then write the data to the stream.
281void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700282 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700283 aaudio_result_t result = AAUDIO_OK;
284 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
jiabind5bd06a2021-04-27 22:04:08 +0000285 if (!isDataCallbackSet()) return nullptr;
Phil Burkfd34a932017-07-19 07:03:52 -0700286 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700287
288 // result might be a frame count
289 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
290 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700291 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700292
293 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700294 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burkbf821e22020-04-17 11:51:43 -0700295 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700296 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700297 if (result >= 0) {
298 // Only wrote some of the frames requested. Must have timed out.
299 result = AAUDIO_ERROR_TIMEOUT;
300 }
Phil Burk134f1972017-12-08 13:06:11 -0800301 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700302 break;
303 }
304 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800305 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk5ff3b952021-04-02 17:29:11 +0000306 result = systemStopInternal();
Phil Burk87c9f642017-05-17 07:22:39 -0700307 break;
308 }
309 }
310
Phil Burk19e990e2018-03-22 13:59:34 -0700311 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
312 __func__, result, (int) isActive());
jiabind5bd06a2021-04-27 22:04:08 +0000313 return nullptr;
Phil Burk87c9f642017-05-17 07:22:39 -0700314}
Phil Burk965650e2017-09-07 21:00:09 -0700315
316//------------------------------------------------------------------------------
317// Implementation of PlayerBase
318status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700319 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
320 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
321 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700322 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700323 return android::NO_ERROR;
324}