blob: e1443d913f1b16ff20c82bdf34dad1152453a153 [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) {
52 close();
53 }
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 Burk5cc83c32017-11-28 15:43:18 -080061aaudio_result_t AudioStreamInternalPlay::requestPause()
Phil Burkb336e892017-07-05 15:35:43 -070062{
Phil Burk5cc83c32017-11-28 15:43:18 -080063 aaudio_result_t result = stopCallback();
64 if (result != AAUDIO_OK) {
65 return result;
66 }
Phil Burkb336e892017-07-05 15:35:43 -070067 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk19e990e2018-03-22 13:59:34 -070068 ALOGE("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070069 return AAUDIO_ERROR_INVALID_STATE;
70 }
71
72 mClockModel.stop(AudioClock::getNanoseconds());
73 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burka53ffa62018-10-10 16:21:37 -070074 mAtomicInternalTimestamp.clear();
Phil Burk965650e2017-09-07 21:00:09 -070075 return mServiceInterface.pauseStream(mServiceStreamHandle);
Phil Burkb336e892017-07-05 15:35:43 -070076}
77
Phil Burkb336e892017-07-05 15:35:43 -070078aaudio_result_t AudioStreamInternalPlay::requestFlush() {
79 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
Phil Burk19e990e2018-03-22 13:59:34 -070080 ALOGE("%s() mServiceStreamHandle invalid", __func__);
Phil Burkb336e892017-07-05 15:35:43 -070081 return AAUDIO_ERROR_INVALID_STATE;
82 }
83
84 setState(AAUDIO_STREAM_STATE_FLUSHING);
85 return mServiceInterface.flushStream(mServiceStreamHandle);
86}
87
Phil Burkbcc36742017-08-31 17:24:51 -070088void AudioStreamInternalPlay::advanceClientToMatchServerPosition() {
Phil Burkb336e892017-07-05 15:35:43 -070089 int64_t readCounter = mAudioEndpoint.getDataReadCounter();
90 int64_t writeCounter = mAudioEndpoint.getDataWriteCounter();
91
92 // Bump offset so caller does not see the retrograde motion in getFramesRead().
Phil Burkbcc36742017-08-31 17:24:51 -070093 int64_t offset = writeCounter - readCounter;
94 mFramesOffsetFromService += offset;
Phil Burk19e990e2018-03-22 13:59:34 -070095 ALOGV("%s() readN = %lld, writeN = %lld, offset = %lld", __func__,
Phil Burkb336e892017-07-05 15:35:43 -070096 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
97
Phil Burkbcc36742017-08-31 17:24:51 -070098 // Force writeCounter to match readCounter.
99 // This is because we cannot change the read counter in the hardware.
Phil Burkb336e892017-07-05 15:35:43 -0700100 mAudioEndpoint.setDataWriteCounter(readCounter);
101}
102
Phil Burkbcc36742017-08-31 17:24:51 -0700103void AudioStreamInternalPlay::onFlushFromServer() {
104 advanceClientToMatchServerPosition();
105}
106
Phil Burk87c9f642017-05-17 07:22:39 -0700107// Write the data, block if needed and timeoutMillis > 0
108aaudio_result_t AudioStreamInternalPlay::write(const void *buffer, int32_t numFrames,
Phil Burk19e990e2018-03-22 13:59:34 -0700109 int64_t timeoutNanoseconds) {
Phil Burk87c9f642017-05-17 07:22:39 -0700110 return processData((void *)buffer, numFrames, timeoutNanoseconds);
111}
112
113// Write as much data as we can without blocking.
114aaudio_result_t AudioStreamInternalPlay::processDataNow(void *buffer, int32_t numFrames,
115 int64_t currentNanoTime, int64_t *wakeTimePtr) {
116 aaudio_result_t result = processCommands();
117 if (result != AAUDIO_OK) {
118 return result;
119 }
120
Phil Burkfd34a932017-07-19 07:03:52 -0700121 const char *traceName = "aaWrNow";
122 ATRACE_BEGIN(traceName);
123
Phil Burkbcc36742017-08-31 17:24:51 -0700124 if (mClockModel.isStarting()) {
125 // Still haven't got any timestamps from server.
126 // Keep waiting until we get some valid timestamps then start writing to the
127 // current buffer position.
Phil Burk55e5eab2018-04-10 15:16:38 -0700128 ALOGV("%s() wait for valid timestamps", __func__);
Phil Burkbcc36742017-08-31 17:24:51 -0700129 // Sleep very briefly and hope we get a timestamp soon.
130 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
131 ATRACE_END();
132 return 0;
133 }
134 // If we have gotten this far then we have at least one timestamp from server.
135
Phil Burkfd34a932017-07-19 07:03:52 -0700136 // If a DMA channel or DSP is reading the other end then we have to update the readCounter.
Phil Burk87c9f642017-05-17 07:22:39 -0700137 if (mAudioEndpoint.isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700138 // Update data queue based on the timing model.
139 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
Phil Burkec89b2e2017-06-20 15:05:06 -0700140 // ALOGD("AudioStreamInternal::processDataNow() - estimatedReadCounter = %d", (int)estimatedReadCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700141 mAudioEndpoint.setDataReadCounter(estimatedReadCounter);
142 }
Phil Burk87c9f642017-05-17 07:22:39 -0700143
Phil Burkbcc36742017-08-31 17:24:51 -0700144 if (mNeedCatchUp.isRequested()) {
145 // Catch an MMAP pointer that is already advancing.
146 // This will avoid initial underruns caused by a slow cold start.
147 advanceClientToMatchServerPosition();
148 mNeedCatchUp.acknowledge();
149 }
150
Phil Burk87c9f642017-05-17 07:22:39 -0700151 // If the read index passed the write index then consider it an underrun.
Phil Burk23296382017-11-20 15:45:11 -0800152 // For shared streams, the xRunCount is passed up from the service.
153 if (mAudioEndpoint.isFreeRunning() && mAudioEndpoint.getFullFramesAvailable() < 0) {
Phil Burk87c9f642017-05-17 07:22:39 -0700154 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700155 if (ATRACE_ENABLED()) {
156 ATRACE_INT("aaUnderRuns", mXRunCount);
157 }
Phil Burk87c9f642017-05-17 07:22:39 -0700158 }
159
160 // Write some data to the buffer.
161 //ALOGD("AudioStreamInternal::processDataNow() - writeNowWithConversion(%d)", numFrames);
162 int32_t framesWritten = writeNowWithConversion(buffer, numFrames);
163 //ALOGD("AudioStreamInternal::processDataNow() - tried to write %d frames, wrote %d",
164 // numFrames, framesWritten);
Phil Burkfd34a932017-07-19 07:03:52 -0700165 if (ATRACE_ENABLED()) {
166 ATRACE_INT("aaWrote", framesWritten);
167 }
Phil Burk87c9f642017-05-17 07:22:39 -0700168
169 // Calculate an ideal time to wake up.
170 if (wakeTimePtr != nullptr && framesWritten >= 0) {
171 // By default wake up a few milliseconds from now. // TODO review
172 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
173 aaudio_stream_state_t state = getState();
174 //ALOGD("AudioStreamInternal::processDataNow() - wakeTime based on %s",
175 // AAudio_convertStreamStateToText(state));
176 switch (state) {
177 case AAUDIO_STREAM_STATE_OPEN:
178 case AAUDIO_STREAM_STATE_STARTING:
179 if (framesWritten != 0) {
180 // Don't wait to write more data. Just prime the buffer.
181 wakeTime = currentNanoTime;
182 }
183 break;
Phil Burkfd34a932017-07-19 07:03:52 -0700184 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700185 {
Phil Burkfd34a932017-07-19 07:03:52 -0700186 // When do we expect the next read burst to occur?
Phil Burk87c9f642017-05-17 07:22:39 -0700187
Phil Burkfd34a932017-07-19 07:03:52 -0700188 // Calculate frame position based off of the writeCounter because
189 // the readCounter might have just advanced in the background,
190 // causing us to sleep until a later burst.
Phil Burkbcc36742017-08-31 17:24:51 -0700191 int64_t nextPosition = mAudioEndpoint.getDataWriteCounter() + mFramesPerBurst
Phil Burkfd34a932017-07-19 07:03:52 -0700192 - mAudioEndpoint.getBufferSizeInFrames();
Phil Burkbcc36742017-08-31 17:24:51 -0700193 wakeTime = mClockModel.convertPositionToTime(nextPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700194 }
195 break;
196 default:
197 break;
198 }
199 *wakeTimePtr = wakeTime;
200
201 }
Phil Burkfd34a932017-07-19 07:03:52 -0700202
203 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700204 return framesWritten;
205}
206
207
208aaudio_result_t AudioStreamInternalPlay::writeNowWithConversion(const void *buffer,
209 int32_t numFrames) {
Phil Burk87c9f642017-05-17 07:22:39 -0700210 WrappingBuffer wrappingBuffer;
Phil Burk41f19d82018-02-13 14:59:10 -0800211 uint8_t *byteBuffer = (uint8_t *) buffer;
Phil Burk87c9f642017-05-17 07:22:39 -0700212 int32_t framesLeft = numFrames;
213
214 mAudioEndpoint.getEmptyFramesAvailable(&wrappingBuffer);
215
Phil Burkfd34a932017-07-19 07:03:52 -0700216 // Write data in one or two parts.
Phil Burk87c9f642017-05-17 07:22:39 -0700217 int partIndex = 0;
218 while (framesLeft > 0 && partIndex < WrappingBuffer::SIZE) {
219 int32_t framesToWrite = framesLeft;
220 int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
221 if (framesAvailable > 0) {
222 if (framesToWrite > framesAvailable) {
223 framesToWrite = framesAvailable;
224 }
Phil Burk41f19d82018-02-13 14:59:10 -0800225
Phil Burk87c9f642017-05-17 07:22:39 -0700226 int32_t numBytes = getBytesPerFrame() * framesToWrite;
Phil Burk41f19d82018-02-13 14:59:10 -0800227
Phil Burk0127c1b2018-03-29 13:48:06 -0700228 mFlowGraph.process((void *)byteBuffer,
229 wrappingBuffer.data[partIndex],
230 framesToWrite);
Phil Burk41f19d82018-02-13 14:59:10 -0800231
232 byteBuffer += numBytes;
Phil Burk87c9f642017-05-17 07:22:39 -0700233 framesLeft -= framesToWrite;
234 } else {
235 break;
236 }
237 partIndex++;
238 }
239 int32_t framesWritten = numFrames - framesLeft;
240 mAudioEndpoint.advanceWriteIndex(framesWritten);
241
Phil Burk87c9f642017-05-17 07:22:39 -0700242 return framesWritten;
243}
244
Phil Burk377c1c22018-12-12 16:06:54 -0800245int64_t AudioStreamInternalPlay::getFramesRead() {
246 const int64_t framesReadHardware = isClockModelInControl()
247 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
248 : mAudioEndpoint.getDataReadCounter();
249 // Add service offset and prevent retrograde motion.
250 mLastFramesRead = std::max(mLastFramesRead, framesReadHardware + mFramesOffsetFromService);
251 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700252}
253
Phil Burk377c1c22018-12-12 16:06:54 -0800254int64_t AudioStreamInternalPlay::getFramesWritten() {
255 const int64_t framesWritten = mAudioEndpoint.getDataWriteCounter()
Phil Burk87c9f642017-05-17 07:22:39 -0700256 + mFramesOffsetFromService;
Phil Burkec89b2e2017-06-20 15:05:06 -0700257 return framesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700258}
259
260
261// Render audio in the application callback and then write the data to the stream.
262void *AudioStreamInternalPlay::callbackLoop() {
Phil Burk19e990e2018-03-22 13:59:34 -0700263 ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__);
Phil Burk87c9f642017-05-17 07:22:39 -0700264 aaudio_result_t result = AAUDIO_OK;
265 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
Phil Burk134f1972017-12-08 13:06:11 -0800266 if (!isDataCallbackSet()) return NULL;
Phil Burkfd34a932017-07-19 07:03:52 -0700267 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700268
269 // result might be a frame count
270 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
271 // Call application using the AAudio callback interface.
Phil Burk134f1972017-12-08 13:06:11 -0800272 callbackResult = maybeCallDataCallback(mCallbackBuffer, mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700273
274 if (callbackResult == AAUDIO_CALLBACK_RESULT_CONTINUE) {
Phil Burkfd34a932017-07-19 07:03:52 -0700275 // Write audio data to stream. This is a BLOCKING WRITE!
Phil Burk87c9f642017-05-17 07:22:39 -0700276 result = write(mCallbackBuffer, mCallbackFrames, timeoutNanos);
277 if ((result != mCallbackFrames)) {
Phil Burk87c9f642017-05-17 07:22:39 -0700278 if (result >= 0) {
279 // Only wrote some of the frames requested. Must have timed out.
280 result = AAUDIO_ERROR_TIMEOUT;
281 }
Phil Burk134f1972017-12-08 13:06:11 -0800282 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700283 break;
284 }
285 } else if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800286 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk1e83bee2018-12-17 14:15:20 -0800287 result = systemStopFromCallback();
Phil Burk87c9f642017-05-17 07:22:39 -0700288 break;
289 }
290 }
291
Phil Burk19e990e2018-03-22 13:59:34 -0700292 ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<",
293 __func__, result, (int) isActive());
Phil Burk87c9f642017-05-17 07:22:39 -0700294 return NULL;
295}
Phil Burk965650e2017-09-07 21:00:09 -0700296
297//------------------------------------------------------------------------------
298// Implementation of PlayerBase
299status_t AudioStreamInternalPlay::doSetVolume() {
Phil Burk55e5eab2018-04-10 15:16:38 -0700300 float combinedVolume = mStreamVolume * getDuckAndMuteVolume();
301 ALOGD("%s() mStreamVolume * duckAndMuteVolume = %f * %f = %f",
302 __func__, mStreamVolume, getDuckAndMuteVolume(), combinedVolume);
Phil Burk0127c1b2018-03-29 13:48:06 -0700303 mFlowGraph.setTargetVolume(combinedVolume);
Phil Burk965650e2017-09-07 21:00:09 -0700304 return android::NO_ERROR;
305}