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