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 #include <algorithm>
21 #include <audio_utils/format.h>
22 #include <aaudio/AAudio.h>
23 #include <media/MediaMetricsItem.h>
24
25 #include "client/AudioStreamInternalCapture.h"
26 #include "utility/AudioClock.h"
27
28 #define ATRACE_TAG ATRACE_TAG_AUDIO
29 #include <utils/Trace.h>
30
31 // We do this after the #includes because if a header uses ALOG.
32 // it would fail on the reference to mInService.
33 #undef LOG_TAG
34 // This file is used in both client and server processes.
35 // This is needed to make sense of the logs more easily.
36 #define LOG_TAG (mInService ? "AudioStreamInternalCapture_Service" \
37 : "AudioStreamInternalCapture_Client")
38
39 using android::WrappingBuffer;
40
41 using namespace aaudio;
42
AudioStreamInternalCapture(AAudioServiceInterface & serviceInterface,bool inService)43 AudioStreamInternalCapture::AudioStreamInternalCapture(AAudioServiceInterface &serviceInterface,
44 bool inService)
45 : AudioStreamInternal(serviceInterface, inService) {
46
47 }
48
advanceClientToMatchServerPosition(int32_t serverMargin)49 void AudioStreamInternalCapture::advanceClientToMatchServerPosition(int32_t serverMargin) {
50 int64_t readCounter = mAudioEndpoint->getDataReadCounter();
51 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter() + serverMargin;
52
53 // Bump offset so caller does not see the retrograde motion in getFramesRead().
54 int64_t offset = readCounter - writeCounter;
55 mFramesOffsetFromService += offset;
56 ALOGD("advanceClientToMatchServerPosition() readN = %lld, writeN = %lld, offset = %lld",
57 (long long)readCounter, (long long)writeCounter, (long long)mFramesOffsetFromService);
58
59 // Force readCounter to match writeCounter.
60 // This is because we cannot change the write counter in the hardware.
61 mAudioEndpoint->setDataReadCounter(writeCounter);
62 }
63
64 // Write the data, block if needed and timeoutMillis > 0
read(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)65 aaudio_result_t AudioStreamInternalCapture::read(void *buffer, int32_t numFrames,
66 int64_t timeoutNanoseconds)
67 {
68 return processData(buffer, numFrames, timeoutNanoseconds);
69 }
70
71 // Read as much data as we can without blocking.
processDataNow(void * buffer,int32_t numFrames,int64_t currentNanoTime,int64_t * wakeTimePtr)72 aaudio_result_t AudioStreamInternalCapture::processDataNow(void *buffer, int32_t numFrames,
73 int64_t currentNanoTime, int64_t *wakeTimePtr) {
74 aaudio_result_t result = processCommands();
75 if (result != AAUDIO_OK) {
76 return result;
77 }
78
79 const char *traceName = "aaRdNow";
80 ATRACE_BEGIN(traceName);
81
82 if (mClockModel.isStarting()) {
83 // Still haven't got any timestamps from server.
84 // Keep waiting until we get some valid timestamps then start writing to the
85 // current buffer position.
86 ALOGD("processDataNow() wait for valid timestamps");
87 // Sleep very briefly and hope we get a timestamp soon.
88 *wakeTimePtr = currentNanoTime + (2000 * AAUDIO_NANOS_PER_MICROSECOND);
89 ATRACE_END();
90 return 0;
91 }
92 // If we have gotten this far then we have at least one timestamp from server.
93
94 if (mAudioEndpoint->isFreeRunning()) {
95 //ALOGD("AudioStreamInternalCapture::processDataNow() - update remote counter");
96 // Update data queue based on the timing model.
97 // Jitter in the DSP can cause late writes to the FIFO.
98 // This might be caused by resampling.
99 // We want to read the FIFO after the latest possible time
100 // that the DSP could have written the data.
101 int64_t estimatedRemoteCounter = mClockModel.convertLatestTimeToPosition(currentNanoTime);
102 // TODO refactor, maybe use setRemoteCounter()
103 mAudioEndpoint->setDataWriteCounter(estimatedRemoteCounter);
104 }
105
106 // This code assumes that we have already received valid timestamps.
107 if (mNeedCatchUp.isRequested()) {
108 // Catch an MMAP pointer that is already advancing.
109 // This will avoid initial underruns caused by a slow cold start.
110 advanceClientToMatchServerPosition(0 /*serverMargin*/);
111 mNeedCatchUp.acknowledge();
112 }
113
114 // If the capture buffer is full beyond capacity then consider it an overrun.
115 // For shared streams, the xRunCount is passed up from the service.
116 if (mAudioEndpoint->isFreeRunning()
117 && mAudioEndpoint->getFullFramesAvailable() > mAudioEndpoint->getBufferCapacityInFrames()) {
118 mXRunCount++;
119 if (ATRACE_ENABLED()) {
120 ATRACE_INT("aaOverRuns", mXRunCount);
121 }
122 }
123
124 // Read some data from the buffer.
125 //ALOGD("AudioStreamInternalCapture::processDataNow() - readNowWithConversion(%d)", numFrames);
126 int32_t framesProcessed = readNowWithConversion(buffer, numFrames);
127 //ALOGD("AudioStreamInternalCapture::processDataNow() - tried to read %d frames, read %d",
128 // numFrames, framesProcessed);
129 if (ATRACE_ENABLED()) {
130 ATRACE_INT("aaRead", framesProcessed);
131 }
132
133 // Calculate an ideal time to wake up.
134 if (wakeTimePtr != nullptr && framesProcessed >= 0) {
135 // By default wake up a few milliseconds from now. // TODO review
136 int64_t wakeTime = currentNanoTime + (1 * AAUDIO_NANOS_PER_MILLISECOND);
137 aaudio_stream_state_t state = getState();
138 //ALOGD("AudioStreamInternalCapture::processDataNow() - wakeTime based on %s",
139 // AAudio_convertStreamStateToText(state));
140 switch (state) {
141 case AAUDIO_STREAM_STATE_OPEN:
142 case AAUDIO_STREAM_STATE_STARTING:
143 break;
144 case AAUDIO_STREAM_STATE_STARTED:
145 {
146 // When do we expect the next write burst to occur?
147
148 // Calculate frame position based off of the readCounter because
149 // the writeCounter might have just advanced in the background,
150 // causing us to sleep until a later burst.
151 int64_t nextPosition = mAudioEndpoint->getDataReadCounter() + getFramesPerBurst();
152 wakeTime = mClockModel.convertPositionToLatestTime(nextPosition);
153 }
154 break;
155 default:
156 break;
157 }
158 *wakeTimePtr = wakeTime;
159
160 }
161
162 ATRACE_END();
163 return framesProcessed;
164 }
165
readNowWithConversion(void * buffer,int32_t numFrames)166 aaudio_result_t AudioStreamInternalCapture::readNowWithConversion(void *buffer,
167 int32_t numFrames) {
168 // ALOGD("readNowWithConversion(%p, %d)",
169 // buffer, numFrames);
170 WrappingBuffer wrappingBuffer;
171 uint8_t *destination = (uint8_t *) buffer;
172 int32_t framesLeft = numFrames;
173
174 mAudioEndpoint->getFullFramesAvailable(&wrappingBuffer);
175
176 // Read data in one or two parts.
177 for (int partIndex = 0; framesLeft > 0 && partIndex < WrappingBuffer::SIZE; partIndex++) {
178 int32_t framesToProcess = framesLeft;
179 const int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
180 if (framesAvailable <= 0) break;
181
182 if (framesToProcess > framesAvailable) {
183 framesToProcess = framesAvailable;
184 }
185
186 const int32_t numBytes = getBytesPerFrame() * framesToProcess;
187 const int32_t numSamples = framesToProcess * getSamplesPerFrame();
188
189 const audio_format_t sourceFormat = getDeviceFormat();
190 const audio_format_t destinationFormat = getFormat();
191
192 memcpy_by_audio_format(destination, destinationFormat,
193 wrappingBuffer.data[partIndex], sourceFormat, numSamples);
194
195 destination += numBytes;
196 framesLeft -= framesToProcess;
197 }
198
199 int32_t framesProcessed = numFrames - framesLeft;
200 mAudioEndpoint->advanceReadIndex(framesProcessed);
201
202 //ALOGD("readNowWithConversion() returns %d", framesProcessed);
203 return framesProcessed;
204 }
205
getFramesWritten()206 int64_t AudioStreamInternalCapture::getFramesWritten() {
207 if (mAudioEndpoint) {
208 const int64_t framesWrittenHardware = isClockModelInControl()
209 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
210 : mAudioEndpoint->getDataWriteCounter();
211 // Add service offset and prevent retrograde motion.
212 mLastFramesWritten = std::max(mLastFramesWritten,
213 framesWrittenHardware + mFramesOffsetFromService);
214 }
215 return mLastFramesWritten;
216 }
217
getFramesRead()218 int64_t AudioStreamInternalCapture::getFramesRead() {
219 if (mAudioEndpoint) {
220 mLastFramesRead = mAudioEndpoint->getDataReadCounter() + mFramesOffsetFromService;
221 }
222 return mLastFramesRead;
223 }
224
225 // Read data from the stream and pass it to the callback for processing.
callbackLoop()226 void *AudioStreamInternalCapture::callbackLoop() {
227 aaudio_result_t result = AAUDIO_OK;
228 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
229 if (!isDataCallbackSet()) return nullptr;
230
231 // result might be a frame count
232 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
233
234 // Read audio data from stream.
235 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
236
237 // This is a BLOCKING READ!
238 result = read(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
239 if ((result != mCallbackFrames)) {
240 ALOGE("callbackLoop: read() returned %d", result);
241 if (result >= 0) {
242 // Only read some of the frames requested. Must have timed out.
243 result = AAUDIO_ERROR_TIMEOUT;
244 }
245 maybeCallErrorCallback(result);
246 break;
247 }
248
249 // Call application using the AAudio callback interface.
250 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
251
252 if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
253 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
254 result = systemStopInternal();
255 break;
256 }
257 }
258
259 ALOGD("callbackLoop() exiting, result = %d, isActive() = %d",
260 result, (int) isActive());
261 return nullptr;
262 }
263