1 /*
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
17 //#define LOG_NDEBUG 0
18 #include <utils/Log.h>
19
20 #define ATRACE_TAG ATRACE_TAG_AUDIO
21
22 #include <media/MediaMetricsItem.h>
23 #include <utils/Trace.h>
24
25 #include "client/AudioStreamInternalPlay.h"
26 #include "utility/AudioClock.h"
27
28 // 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
36 using android::status_t;
37 using android::WrappingBuffer;
38
39 using namespace aaudio;
40
AudioStreamInternalPlay(AAudioServiceInterface & serviceInterface,bool inService)41 AudioStreamInternalPlay::AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface,
42 bool inService)
43 : AudioStreamInternal(serviceInterface, inService) {
44
45 }
46
~AudioStreamInternalPlay()47 AudioStreamInternalPlay::~AudioStreamInternalPlay() {}
48
49 constexpr int kRampMSec = 10; // time to apply a change in volume
50
open(const AudioStreamBuilder & builder)51 aaudio_result_t AudioStreamInternalPlay::open(const AudioStreamBuilder &builder) {
52 aaudio_result_t result = AudioStreamInternal::open(builder);
53 if (result == AAUDIO_OK) {
54 result = mFlowGraph.configure(getFormat(),
55 getSamplesPerFrame(),
56 getDeviceFormat(),
57 getDeviceChannelCount());
58
59 if (result != AAUDIO_OK) {
60 safeReleaseClose();
61 }
62 // Sample rate is constrained to common values by now and should not overflow.
63 int32_t numFrames = kRampMSec * getSampleRate() / AAUDIO_MILLIS_PER_SECOND;
64 mFlowGraph.setRampLengthInFrames(numFrames);
65 }
66 return result;
67 }
68
69 // This must be called under mStreamLock.
requestPause_l()70 aaudio_result_t AudioStreamInternalPlay::requestPause_l()
71 {
72 aaudio_result_t result = stopCallback_l();
73 if (result != AAUDIO_OK) {
74 return result;
75 }
76 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
77 ALOGW("%s() mServiceStreamHandle invalid", __func__);
78 return AAUDIO_ERROR_INVALID_STATE;
79 }
80
81 mClockModel.stop(AudioClock::getNanoseconds());
82 setState(AAUDIO_STREAM_STATE_PAUSING);
83 mAtomicInternalTimestamp.clear();
84 return mServiceInterface.pauseStream(mServiceStreamHandle);
85 }
86
requestFlush_l()87 aaudio_result_t AudioStreamInternalPlay::requestFlush_l() {
88 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
89 ALOGW("%s() mServiceStreamHandle invalid", __func__);
90 return AAUDIO_ERROR_INVALID_STATE;
91 }
92
93 setState(AAUDIO_STREAM_STATE_FLUSHING);
94 return mServiceInterface.flushStream(mServiceStreamHandle);
95 }
96
prepareBuffersForStart()97 void AudioStreamInternalPlay::prepareBuffersForStart() {
98 // Prevent stale data from being played.
99 mAudioEndpoint->eraseDataMemory();
100 }
101
advanceClientToMatchServerPosition(int32_t serverMargin)102 void AudioStreamInternalPlay::advanceClientToMatchServerPosition(int32_t serverMargin) {
103 int64_t readCounter = mAudioEndpoint->getDataReadCounter() + serverMargin;
104 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter();
105
106 // Bump offset so caller does not see the retrograde motion in getFramesRead().
107 int64_t offset = writeCounter - readCounter;
108 mFramesOffsetFromService += offset;
109 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
110 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
111
112 // Force writeCounter to match readCounter.
113 // This is because we cannot change the read counter in the hardware.
114 mAudioEndpoint->setDataWriteCounter(readCounter);
115 }
116
onFlushFromServer()117 void AudioStreamInternalPlay::onFlushFromServer() {
118 advanceClientToMatchServerPosition();
119 }
120
121 // Write the data, block if needed and timeoutMillis > 0
write(const void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)122 aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
123 int64_t timeoutNanoseconds) {
124 return processData((void *)buffer, numFrames, timeoutNanoseconds);
125 }
126
127 // Write as much data as we can without blocking.
processDataNow(void * buffer,int32_t numFrames,int64_t currentNanoTime,int64_t * wakeTimePtr)128 aaudio_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
135 const char *traceName = "aaWrNow";
136 ATRACE_BEGIN(traceName);
137
138 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.
142 ALOGV("%s() wait for valid timestamps", __func__);
143 // 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
150 // If a DMA channel or DSP is reading the other end then we have to update the readCounter.
151 if (mAudioEndpoint->isFreeRunning()) {
152 // Update data queue based on the timing model.
153 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
154 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
155 mAudioEndpoint->setDataReadCounter(estimatedReadCounter);
156 }
157
158 if (mNeedCatchUp.isRequested()) {
159 // Catch an MMAP pointer that is already advancing.
160 // This will avoid initial underruns caused by a slow cold start.
161 // 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());
164 mNeedCatchUp.acknowledge();
165 }
166
167 // If the read index passed the write index then consider it an underrun.
168 // For shared streams, the xRunCount is passed up from the service.
169 if (mAudioEndpoint->isFreeRunning() && mAudioEndpoint->getFullFramesAvailable() < 0) {
170 mXRunCount++;
171 if (ATRACE_ENABLED()) {
172 ATRACE_INT("aaUnderRuns", mXRunCount);
173 }
174 }
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);
181 if (ATRACE_ENABLED()) {
182 ATRACE_INT("aaWrote", framesWritten);
183 }
184
185 // Sleep if there is too much data in the buffer.
186 // Calculate an ideal time to wake up.
187 if (wakeTimePtr != nullptr
188 && (mAudioEndpoint->getFullFramesAvailable() >= getBufferSize())) {
189 // 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;
202 case AAUDIO_STREAM_STATE_STARTED:
203 {
204 // Sleep until the readCounter catches up and we only have
205 // the getBufferSize() frames of data sitting in the buffer.
206 int64_t nextReadPosition = mAudioEndpoint->getDataWriteCounter() - getBufferSize();
207 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
208 }
209 break;
210 default:
211 break;
212 }
213 *wakeTimePtr = wakeTime;
214
215 }
216
217 ATRACE_END();
218 return framesWritten;
219 }
220
221
writeNowWithConversion(const void * buffer,int32_t numFrames)222 aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
223 int32_t numFrames) {
224 WrappingBuffer wrappingBuffer;
225 uint8_t *byteBuffer = (uint8_t *) buffer;
226 int32_t framesLeft = numFrames;
227
228 mAudioEndpoint->getEmptyFramesAvailable(&wrappingBuffer);
229
230 // Write data in one or two parts.
231 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 }
239
240 int32_t numBytes = getBytesPerFrame() * framesToWrite;
241
242 mFlowGraph.process((void *)byteBuffer,
243 wrappingBuffer.data[partIndex],
244 framesToWrite);
245
246 byteBuffer += numBytes;
247 framesLeft -= framesToWrite;
248 } else {
249 break;
250 }
251 partIndex++;
252 }
253 int32_t framesWritten = numFrames - framesLeft;
254 mAudioEndpoint->advanceWriteIndex(framesWritten);
255
256 return framesWritten;
257 }
258
getFramesRead()259 int64_t AudioStreamInternalPlay::getFramesRead() {
260 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 }
267 return mLastFramesRead;
268 }
269
getFramesWritten()270 int64_t AudioStreamInternalPlay::getFramesWritten() {
271 if (mAudioEndpoint) {
272 mLastFramesWritten = mAudioEndpoint->getDataWriteCounter()
273 + mFramesOffsetFromService;
274 }
275 return mLastFramesWritten;
276 }
277
278
279 // Render audio in the application callback and then write the data to the stream.
callbackLoop()280 void *AudioStreamInternalPlay::callbackLoop() {
281 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
282 aaudio_result_t result = AAUDIO_OK;
283 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
284 if (!isDataCallbackSet()) return NULL;
285 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
286
287 // result might be a frame count
288 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
289 // Call application using the AAudio callback interface.
290 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
291
292 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
293 // Write audio data to stream. This is a BLOCKING WRITE!
294 result = write(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
295 if ((result != mCallbackFrames)) {
296 if (result >= 0) {
297 // Only wrote some of the frames requested. Must have timed out.
298 result = AAUDIO_ERROR_TIMEOUT;
299 }
300 maybeCallErrorCallback(result);
301 break;
302 }
303 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
304 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
305 result = systemStopInternal();
306 break;
307 }
308 }
309
310 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
311 __func__, result, (int) isActive());
312 return NULL;
313 }
314
315 //------------------------------------------------------------------------------
316 // Implementation of PlayerBase
doSetVolume()317 status_t AudioStreamInternalPlay::doSetVolume() {
318 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
319 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
320 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
321 mFlowGraph.setTargetVolume(combinedVolume);
322 return android::NO_ERROR;
323 }
324