blob: 89dd8ffd33b5617af53ce40e8e157eecadaf249c [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 }
jiabin5f787812023-03-02 20:42:43 +000077 if (getServiceHandle() == 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();
jiabin5f787812023-03-02 20:42:43 +000085 return mServiceInterface.pauseStream(mServiceStreamHandleInfo);
Phil Burkb336e892017-07-05 15:35:43 -070086}
87
Phil Burkdd582922020-10-15 20:29:51 +000088aaudio_result_t AudioStreamInternalPlay::requestFlush_l() {
jiabin5f787812023-03-02 20:42:43 +000089 if (getServiceHandle() == 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);
jiabin5f787812023-03-02 20:42:43 +000095 return mServiceInterface.flushStream(mServiceStreamHandleInfo);
Phil Burkb336e892017-07-05 15:35:43 -070096}
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 Burkec21f2b2022-04-19 18:52:03 +0000205 // Calculate when there will be room available to write to the buffer.
206 // If the appBufferSize is smaller than the endpointBufferSize then
207 // we will have room to write data beyond the appBufferSize.
208 // That is a technique used to reduce glitches without adding latency.
209 const int32_t appBufferSize = getBufferSize();
210 // The endpoint buffer size is set to the maximum that can be written.
211 // If we use it then we must carve out some room to write data when we wake up.
212 const int32_t endBufferSize = mAudioEndpoint->getBufferSizeInFrames()
213 - getFramesPerBurst();
214 const int32_t bestBufferSize = std::min(appBufferSize, endBufferSize);
215 int64_t targetReadPosition = mAudioEndpoint->getDataWriteCounter() - bestBufferSize;
216 wakeTime = mClockModel.convertPositionToTime(targetReadPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700217 }
218 break;
219 default:
220 break;
221 }
222 *wakeTimePtr = wakeTime;
223
224 }
Phil Burkfd34a932017-07-19 07:03:52 -0700225
226 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700227 return framesWritten;
228}
229
230
231aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
232 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700233 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800234 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700235 int32_t framesLeft = numFrames;
236
Phil Burk5edc4ea2020-04-17 08:15:42 -0700237 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700238
Phil Burkfd34a932017-07-19 07:03:52 -0700239 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700240 int partIndex = 0;
241 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
242 int32_t framesToWrite = framesLeft;
243 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
244 if (framesAvailable > 0) {
245 if (framesToWrite > framesAvailable) {
246 framesToWrite = framesAvailable;
247 }
Phil Burk41f19d82018-02-13 14:59:10 -0800248
Phil Burk87c9f642017-05-17 07:22:39 -0700249 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800250
Phil Burk0127c1b2018-03-29 13:48:06 -0700251 mFlowGraph.process((void *)byteBuffer,
252 wrappingBuffer.data[partIndex],
253 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800254
255 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700256 framesLeft -= framesToWrite;
257 } else {
258 break;
259 }
260 partIndex++;
261 }
262 int32_t framesWritten = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700263 mAudioEndpoint->advanceWriteIndex(framesWritten);
Phil Burk87c9f642017-05-17 07:22:39 -0700264
Phil Burk87c9f642017-05-17 07:22:39 -0700265 return framesWritten;
266}
267
Phil Burk377c1c22018-12-12 16:06:54 -0800268int64_t AudioStreamInternalPlay::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700269 if (mAudioEndpoint) {
270 const int64_t framesReadHardware = isClockModelInControl()
271 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
272 : mAudioEndpoint->getDataReadCounter();
273 // Add service offset and prevent retrograde motion.
274 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
275 }
Phil Burk377c1c22018-12-12 16:06:54 -0800276 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700277}
278
Phil Burk377c1c22018-12-12 16:06:54 -0800279int64_t AudioStreamInternalPlay::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700280 if (mAudioEndpoint) {
281 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
282 + mFramesOffsetFromService;
283 }
284 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700285}
286
287
288// Render audio in the application callback and then write the data to the stream.
289void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700290 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700291 aaudio_result_t result = AAUDIO_OK;
292 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
jiabind5bd06a2021-04-27 22:04:08 +0000293 if (!isDataCallbackSet()) return nullptr;
Phil Burkfd34a932017-07-19 07:03:52 -0700294 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700295
296 // result might be a frame count
297 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
298 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700299 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700300
301 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700302 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burkbf821e22020-04-17 11:51:43 -0700303 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700304 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700305 if (result >= 0) {
306 // Only wrote some of the frames requested. Must have timed out.
307 result = AAUDIO_ERROR_TIMEOUT;
308 }
Phil Burk134f1972017-12-08 13:06:11 -0800309 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700310 break;
311 }
312 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800313 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk5ff3b952021-04-02 17:29:11 +0000314 result = systemStopInternal();
Phil Burk87c9f642017-05-17 07:22:39 -0700315 break;
316 }
317 }
318
Phil Burk19e990e2018-03-22 13:59:34 -0700319 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
320 __func__, result, (int) isActive());
jiabind5bd06a2021-04-27 22:04:08 +0000321 return nullptr;
Phil Burk87c9f642017-05-17 07:22:39 -0700322}
Phil Burk965650e2017-09-07 21:00:09 -0700323
324//------------------------------------------------------------------------------
325// Implementation of PlayerBase
326status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700327 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
328 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
329 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700330 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700331 return android::NO_ERROR;
332}