blob: 71bde9068fc4574a8e0bc739131b640db1c3c270 [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
47AudioStreamInternalPlay::~AudioStreamInternalPlay() {}
48
Phil Burk02fec702018-02-16 18:25:55 -080049constexpr int kRampMSec = 10; // time to apply a change in volume
50
51aaudio_result_t AudioStreamInternalPlay::open(const AudioStreamBuilder &builder) {
52 aaudio_result_t result = AudioStreamInternal::open(builder);
53 if (result == AAUDIO_OK) {
Phil Burk0127c1b2018-03-29 13:48:06 -070054 result = mFlowGraph.configure(getFormat(),
55 getSamplesPerFrame(),
56 getDeviceFormat(),
57 getDeviceChannelCount());
58
59 if (result != AAUDIO_OK) {
Phil Burkdd582922020-10-15 20:29:51 +000060 safeReleaseClose();
Phil Burk0127c1b2018-03-29 13:48:06 -070061 }
Phil Burk02fec702018-02-16 18:25:55 -080062 // Sample rate is constrained to common values by now and should not overflow.
63 int32_t numFrames = kRampMSec * getSampleRate() / AAUDIO_MILLIS_PER_SECOND;
Phil Burk0127c1b2018-03-29 13:48:06 -070064 mFlowGraph.setRampLengthInFrames(numFrames);
Phil Burk02fec702018-02-16 18:25:55 -080065 }
66 return result;
67}
68
Phil Burk13d3d832019-06-10 14:36:48 -070069// This must be called under mStreamLock.
Phil Burkdd582922020-10-15 20:29:51 +000070aaudio_result_t AudioStreamInternalPlay::requestPause_l()
Phil Burkb336e892017-07-05 15:35:43 -070071{
Phil Burkdd582922020-10-15 20:29:51 +000072 aaudio_result_t result = stopCallback_l();
Phil Burk5cc83c32017-11-28 15:43:18 -080073 if (result != AAUDIO_OK) {
74 return result;
75 }
Phil Burkb336e892017-07-05 15:35:43 -070076 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070077 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070078 return AAUDIO_ERROR_INVALID_STATE;
79 }
80
81 mClockModel.stop(AudioClock::getNanoseconds());
82 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burka53ffa62018-10-10 16:21:37 -070083 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -070084 return mServiceInterface.pauseStream(mServiceStreamHandle);
Phil Burkb336e892017-07-05 15:35:43 -070085}
86
Phil Burkdd582922020-10-15 20:29:51 +000087aaudio_result_t AudioStreamInternalPlay::requestFlush_l() {
Phil Burkb336e892017-07-05 15:35:43 -070088 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk29ccc292019-04-15 08:58:08 -070089 ALOGW("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070090 return AAUDIO_ERROR_INVALID_STATE;
91 }
92
93 setState(AAUDIO_STREAM_STATE_FLUSHING);
94 return mServiceInterface.flushStream(mServiceStreamHandle);
95}
96
Phil Burkec8ca522020-05-19 10:05:58 -070097void AudioStreamInternalPlay::prepareBuffersForStart() {
98 // Prevent stale data from being played.
99 mAudioEndpoint->eraseDataMemory();
100}
101
102void AudioStreamInternalPlay::advanceClientToMatchServerPosition(int32_t serverMargin) {
103 int64_t readCounter = mAudioEndpoint->getDataReadCounter() + serverMargin;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700104 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter();
Phil Burkb336e892017-07-05 15:35:43 -0700105
106 // Bump offset so caller does not see the retrograde motion in getFramesRead().
Phil Burkbcc36742017-08-31 17:24:51 -0700107 int64_t offset = writeCounter - readCounter;
108 mFramesOffsetFromService += offset;
Phil Burk19e990e2018-03-22 13:59:34 -0700109 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
Phil Burkb336e892017-07-05 15:35:43 -0700110 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
111
Phil Burkbcc36742017-08-31 17:24:51 -0700112 // Force writeCounter to match readCounter.
113 // This is because we cannot change the read counter in the hardware.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700114 mAudioEndpoint->setDataWriteCounter(readCounter);
Phil Burkb336e892017-07-05 15:35:43 -0700115}
116
Phil Burkbcc36742017-08-31 17:24:51 -0700117void AudioStreamInternalPlay::onFlushFromServer() {
118 advanceClientToMatchServerPosition();
119}
120
Phil Burk87c9f642017-05-17 07:22:39 -0700121// Write the data, block if needed and timeoutMillis > 0
122aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
Phil Burk19e990e2018-03-22 13:59:34 -0700123 int64_t timeoutNanoseconds) {
Phil Burk87c9f642017-05-17 07:22:39 -0700124 return processData((void *)buffer, numFrames, timeoutNanoseconds);
125}
126
127// Write as much data as we can without blocking.
128aaudio_result_t AudioStreamInternalPlay::processDataNow(void *buffer, int32_t numFrames,
129 int64_t currentNanoTime, int64_t *wakeTimePtr) {
130 aaudio_result_t result = processCommands();
131 if (result != AAUDIO_OK) {
132 return result;
133 }
134
Phil Burkfd34a932017-07-19 07:03:52 -0700135 const char *traceName = "aaWrNow";
136 ATRACE_BEGIN(traceName);
137
Phil Burkbcc36742017-08-31 17:24:51 -0700138 if (mClockModel.isStarting()) {
139 // Still haven't got any timestamps from server.
140 // Keep waiting until we get some valid timestamps then start writing to the
141 // current buffer position.
Phil Burk55e5eab2018-04-10 15:16:38 -0700142 ALOGV("%s() wait for valid timestamps", __func__);
Phil Burkbcc36742017-08-31 17:24:51 -0700143 // Sleep very briefly and hope we get a timestamp soon.
144 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
145 ATRACE_END();
146 return 0;
147 }
148 // If we have gotten this far then we have at least one timestamp from server.
149
Phil Burkfd34a932017-07-19 07:03:52 -0700150 // 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 -0700151 if (mAudioEndpoint->isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700152 // Update data queue based on the timing model.
153 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
Phil Burkec89b2e2017-06-20 15:05:06 -0700154 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
Phil Burk5edc4ea2020-04-17 08:15:42 -0700155 mAudioEndpoint->setDataReadCounter(estimatedReadCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700156 }
Phil Burk87c9f642017-05-17 07:22:39 -0700157
Phil Burkbcc36742017-08-31 17:24:51 -0700158 if (mNeedCatchUp.isRequested()) {
159 // Catch an MMAP pointer that is already advancing.
160 // This will avoid initial underruns caused by a slow cold start.
Phil Burkec8ca522020-05-19 10:05:58 -0700161 // We add a one burst margin in case the DSP advances before we can write the data.
162 // This can help prevent the beginning of the stream from being skipped.
163 advanceClientToMatchServerPosition(getFramesPerBurst());
Phil Burkbcc36742017-08-31 17:24:51 -0700164 mNeedCatchUp.acknowledge();
165 }
166
Phil Burk87c9f642017-05-17 07:22:39 -0700167 // If the read index passed the write index then consider it an underrun.
Phil Burk23296382017-11-20 15:45:11 -0800168 // For shared streams, the xRunCount is passed up from the service.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700169 if (mAudioEndpoint->isFreeRunning() && mAudioEndpoint->getFullFramesAvailable() < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700170 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700171 if (ATRACE_ENABLED()) {
172 ATRACE_INT("aaUnderRuns", mXRunCount);
173 }
Phil Burk87c9f642017-05-17 07:22:39 -0700174 }
175
176 // Write some data to the buffer.
177 //ALOGD("AudioStreamInternal::processDataNow() - writeNowWithConversion(%d)", numFrames);
178 int32_t framesWritten = writeNowWithConversion(buffer, numFrames);
179 //ALOGD("AudioStreamInternal::processDataNow() - tried to write %d frames, wrote %d",
180 // numFrames, framesWritten);
Phil Burkfd34a932017-07-19 07:03:52 -0700181 if (ATRACE_ENABLED()) {
182 ATRACE_INT("aaWrote", framesWritten);
183 }
Phil Burk87c9f642017-05-17 07:22:39 -0700184
Phil Burk8d4f0062019-10-03 15:55:41 -0700185 // Sleep if there is too much data in the buffer.
Phil Burk87c9f642017-05-17 07:22:39 -0700186 // Calculate an ideal time to wake up.
Phil Burk8d4f0062019-10-03 15:55:41 -0700187 if (wakeTimePtr != nullptr
Phil Burk5edc4ea2020-04-17 08:15:42 -0700188 && (mAudioEndpoint->getFullFramesAvailable() >= getBufferSize())) {
Phil Burk87c9f642017-05-17 07:22:39 -0700189 // By default wake up a few milliseconds from now. // TODO review
190 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
191 aaudio_stream_state_t state = getState();
192 //ALOGD("AudioStreamInternal::processDataNow() - wakeTime based on %s",
193 // AAudio_convertStreamStateToText(state));
194 switch (state) {
195 case AAUDIO_STREAM_STATE_OPEN:
196 case AAUDIO_STREAM_STATE_STARTING:
197 if (framesWritten != 0) {
198 // Don't wait to write more data. Just prime the buffer.
199 wakeTime = currentNanoTime;
200 }
201 break;
Phil Burkfd34a932017-07-19 07:03:52 -0700202 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700203 {
Phil Burk8d4f0062019-10-03 15:55:41 -0700204 // Sleep until the readCounter catches up and we only have
205 // the getBufferSize() frames of data sitting in the buffer.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700206 int64_t nextReadPosition = mAudioEndpoint->getDataWriteCounter() - getBufferSize();
Phil Burk8d4f0062019-10-03 15:55:41 -0700207 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700208 }
209 break;
210 default:
211 break;
212 }
213 *wakeTimePtr = wakeTime;
214
215 }
Phil Burkfd34a932017-07-19 07:03:52 -0700216
217 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700218 return framesWritten;
219}
220
221
222aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
223 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700224 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800225 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700226 int32_t framesLeft = numFrames;
227
Phil Burk5edc4ea2020-04-17 08:15:42 -0700228 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700229
Phil Burkfd34a932017-07-19 07:03:52 -0700230 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700231 int partIndex = 0;
232 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
233 int32_t framesToWrite = framesLeft;
234 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
235 if (framesAvailable > 0) {
236 if (framesToWrite > framesAvailable) {
237 framesToWrite = framesAvailable;
238 }
Phil Burk41f19d82018-02-13 14:59:10 -0800239
Phil Burk87c9f642017-05-17 07:22:39 -0700240 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800241
Phil Burk0127c1b2018-03-29 13:48:06 -0700242 mFlowGraph.process((void *)byteBuffer,
243 wrappingBuffer.data[partIndex],
244 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800245
246 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700247 framesLeft -= framesToWrite;
248 } else {
249 break;
250 }
251 partIndex++;
252 }
253 int32_t framesWritten = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700254 mAudioEndpoint->advanceWriteIndex(framesWritten);
Phil Burk87c9f642017-05-17 07:22:39 -0700255
Phil Burk87c9f642017-05-17 07:22:39 -0700256 return framesWritten;
257}
258
Phil Burk377c1c22018-12-12 16:06:54 -0800259int64_t AudioStreamInternalPlay::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700260 if (mAudioEndpoint) {
261 const int64_t framesReadHardware = isClockModelInControl()
262 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
263 : mAudioEndpoint->getDataReadCounter();
264 // Add service offset and prevent retrograde motion.
265 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
266 }
Phil Burk377c1c22018-12-12 16:06:54 -0800267 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700268}
269
Phil Burk377c1c22018-12-12 16:06:54 -0800270int64_t AudioStreamInternalPlay::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700271 if (mAudioEndpoint) {
272 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
273 + mFramesOffsetFromService;
274 }
275 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700276}
277
278
279// Render audio in the application callback and then write the data to the stream.
280void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700281 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700282 aaudio_result_t result = AAUDIO_OK;
283 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
Phil Burk134f1972017-12-08 13:06:11 -0800284 if (!isDataCallbackSet()) return NULL;
Phil Burkfd34a932017-07-19 07:03:52 -0700285 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700286
287 // result might be a frame count
288 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
289 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700290 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700291
292 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700293 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burkbf821e22020-04-17 11:51:43 -0700294 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700295 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700296 if (result >= 0) {
297 // Only wrote some of the frames requested. Must have timed out.
298 result = AAUDIO_ERROR_TIMEOUT;
299 }
Phil Burk134f1972017-12-08 13:06:11 -0800300 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700301 break;
302 }
303 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800304 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk5ff3b952021-04-02 17:29:11 +0000305 result = systemStopInternal();
Phil Burk87c9f642017-05-17 07:22:39 -0700306 break;
307 }
308 }
309
Phil Burk19e990e2018-03-22 13:59:34 -0700310 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
311 __func__, result, (int) isActive());
Phil Burk87c9f642017-05-17 07:22:39 -0700312 return NULL;
313}
Phil Burk965650e2017-09-07 21:00:09 -0700314
315//------------------------------------------------------------------------------
316// Implementation of PlayerBase
317status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700318 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
319 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
320 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700321 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700322 return android::NO_ERROR;
323}