blob: 5c8bdfcc12d7e2e27bf6e76f644531019a2a09a2 [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 Burkec89b2e2017-06-20 15:05:06 -070020#include <algorithm>
Phil Burk0127c1b2018-03-29 13:48:06 -070021#include <audio_utils/primitives.h>
Phil Burk87c9f642017-05-17 07:22:39 -070022#include <aaudio/AAudio.h>
jiabin97247ea2021-04-07 00:33:38 +000023#include <media/MediaMetricsItem.h>
Phil Burk87c9f642017-05-17 07:22:39 -070024
25#include "client/AudioStreamInternalCapture.h"
26#include "utility/AudioClock.h"
27
Phil Burkfd34a932017-07-19 07:03:52 -070028#define ATRACE_TAG ATRACE_TAG_AUDIO
29#include <utils/Trace.h>
30
Phil Burk58f5ce12020-08-12 14:29:10 +000031// 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
Phil Burk87c9f642017-05-17 07:22:39 -070039using android::WrappingBuffer;
40
41using namespace aaudio;
42
43AudioStreamInternalCapture::AudioStreamInternalCapture(AAudioServiceInterface &serviceInterface,
44 bool inService)
45 : AudioStreamInternal(serviceInterface, inService) {
46
47}
48
Phil Burkec8ca522020-05-19 10:05:58 -070049void AudioStreamInternalCapture::advanceClientToMatchServerPosition(int32_t serverMargin) {
Phil Burk5edc4ea2020-04-17 08:15:42 -070050 int64_t readCounter = mAudioEndpoint->getDataReadCounter();
Phil Burkec8ca522020-05-19 10:05:58 -070051 int64_t writeCounter = mAudioEndpoint->getDataWriteCounter() + serverMargin;
Phil Burkbcc36742017-08-31 17:24:51 -070052
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.
Phil Burk5edc4ea2020-04-17 08:15:42 -070061 mAudioEndpoint->setDataReadCounter(writeCounter);
Phil Burkbcc36742017-08-31 17:24:51 -070062}
63
Phil Burk87c9f642017-05-17 07:22:39 -070064// Write the data, block if needed and timeoutMillis > 0
65aaudio_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.
72aaudio_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
Phil Burkfd34a932017-07-19 07:03:52 -070079 const char *traceName = "aaRdNow";
80 ATRACE_BEGIN(traceName);
81
Phil Burkbcc36742017-08-31 17:24:51 -070082 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
Phil Burk5edc4ea2020-04-17 08:15:42 -070094 if (mAudioEndpoint->isFreeRunning()) {
Phil Burk87c9f642017-05-17 07:22:39 -070095 //ALOGD("AudioStreamInternalCapture::processDataNow() - update remote counter");
96 // Update data queue based on the timing model.
Phil Burkfceeee72019-06-14 11:18:45 -070097 // 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);
Phil Burk87c9f642017-05-17 07:22:39 -0700102 // TODO refactor, maybe use setRemoteCounter()
Phil Burk5edc4ea2020-04-17 08:15:42 -0700103 mAudioEndpoint->setDataWriteCounter(estimatedRemoteCounter);
Phil Burk87c9f642017-05-17 07:22:39 -0700104 }
105
Phil Burkbcc36742017-08-31 17:24:51 -0700106 // 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.
jiabind5bd06a2021-04-27 22:04:08 +0000110 advanceClientToMatchServerPosition(0 /*serverMargin*/);
Phil Burkbcc36742017-08-31 17:24:51 -0700111 mNeedCatchUp.acknowledge();
112 }
113
Phil Burka10bd512019-09-27 11:49:17 -0700114 // If the capture buffer is full beyond capacity then consider it an overrun.
Phil Burk23296382017-11-20 15:45:11 -0800115 // For shared streams, the xRunCount is passed up from the service.
Phil Burk5edc4ea2020-04-17 08:15:42 -0700116 if (mAudioEndpoint->isFreeRunning()
117 && mAudioEndpoint->getFullFramesAvailable() > mAudioEndpoint->getBufferCapacityInFrames()) {
Phil Burk87c9f642017-05-17 07:22:39 -0700118 mXRunCount++;
Phil Burkfd34a932017-07-19 07:03:52 -0700119 if (ATRACE_ENABLED()) {
120 ATRACE_INT("aaOverRuns", mXRunCount);
121 }
Phil Burk87c9f642017-05-17 07:22:39 -0700122 }
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);
Phil Burkfd34a932017-07-19 07:03:52 -0700129 if (ATRACE_ENABLED()) {
130 ATRACE_INT("aaRead", framesProcessed);
131 }
Phil Burk87c9f642017-05-17 07:22:39 -0700132
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;
Phil Burkfd34a932017-07-19 07:03:52 -0700144 case AAUDIO_STREAM_STATE_STARTED:
Phil Burk87c9f642017-05-17 07:22:39 -0700145 {
Phil Burkfd34a932017-07-19 07:03:52 -0700146 // When do we expect the next write burst to occur?
Phil Burk87c9f642017-05-17 07:22:39 -0700147
Phil Burkfd34a932017-07-19 07:03:52 -0700148 // 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.
Phil Burk8d97b8e2020-09-25 23:18:14 +0000151 int64_t nextPosition = mAudioEndpoint->getDataReadCounter() + getFramesPerBurst();
Phil Burkfceeee72019-06-14 11:18:45 -0700152 wakeTime = mClockModel.convertPositionToLatestTime(nextPosition);
Phil Burk87c9f642017-05-17 07:22:39 -0700153 }
154 break;
155 default:
156 break;
157 }
158 *wakeTimePtr = wakeTime;
159
160 }
Phil Burkfd34a932017-07-19 07:03:52 -0700161
162 ATRACE_END();
Phil Burk87c9f642017-05-17 07:22:39 -0700163 return framesProcessed;
164}
165
166aaudio_result_t AudioStreamInternalCapture::readNowWithConversion(void *buffer,
167 int32_t numFrames) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700168 // ALOGD("readNowWithConversion(%p, %d)",
Phil Burk87c9f642017-05-17 07:22:39 -0700169 // buffer, numFrames);
170 WrappingBuffer wrappingBuffer;
171 uint8_t *destination = (uint8_t *) buffer;
172 int32_t framesLeft = numFrames;
173
Phil Burk5edc4ea2020-04-17 08:15:42 -0700174 mAudioEndpoint->getFullFramesAvailable(&wrappingBuffer);
Phil Burk87c9f642017-05-17 07:22:39 -0700175
176 // Read data in one or two parts.
177 for (int partIndex = 0; framesLeft > 0 && partIndex < WrappingBuffer::SIZE; partIndex++) {
178 int32_t framesToProcess = framesLeft;
Phil Burk0127c1b2018-03-29 13:48:06 -0700179 const int32_t framesAvailable = wrappingBuffer.numFrames[partIndex];
Phil Burk87c9f642017-05-17 07:22:39 -0700180 if (framesAvailable <= 0) break;
181
182 if (framesToProcess > framesAvailable) {
183 framesToProcess = framesAvailable;
184 }
185
Phil Burk0127c1b2018-03-29 13:48:06 -0700186 const int32_t numBytes = getBytesPerFrame() * framesToProcess;
187 const int32_t numSamples = framesToProcess * getSamplesPerFrame();
Phil Burk87c9f642017-05-17 07:22:39 -0700188
Phil Burk0127c1b2018-03-29 13:48:06 -0700189 const audio_format_t sourceFormat = getDeviceFormat();
190 const audio_format_t destinationFormat = getFormat();
Phil Burk87c9f642017-05-17 07:22:39 -0700191 // TODO factor this out into a utility function
Phil Burk0127c1b2018-03-29 13:48:06 -0700192 if (sourceFormat == destinationFormat) {
Phil Burk87c9f642017-05-17 07:22:39 -0700193 memcpy(destination, wrappingBuffer.data[partIndex], numBytes);
Phil Burk0127c1b2018-03-29 13:48:06 -0700194 } else if (sourceFormat == AUDIO_FORMAT_PCM_16_BIT
195 && destinationFormat == AUDIO_FORMAT_PCM_FLOAT) {
196 memcpy_to_float_from_i16(
Phil Burk87c9f642017-05-17 07:22:39 -0700197 (float *) destination,
Phil Burk0127c1b2018-03-29 13:48:06 -0700198 (const int16_t *) wrappingBuffer.data[partIndex],
199 numSamples);
200 } else if (sourceFormat == AUDIO_FORMAT_PCM_FLOAT
201 && destinationFormat == AUDIO_FORMAT_PCM_16_BIT) {
202 memcpy_to_i16_from_float(
Phil Burk87c9f642017-05-17 07:22:39 -0700203 (int16_t *) destination,
Phil Burk0127c1b2018-03-29 13:48:06 -0700204 (const float *) wrappingBuffer.data[partIndex],
205 numSamples);
Phil Burk87c9f642017-05-17 07:22:39 -0700206 } else {
Phil Burk0127c1b2018-03-29 13:48:06 -0700207 ALOGE("%s() - Format conversion not supported! audio_format_t source = %u, dest = %u",
208 __func__, sourceFormat, destinationFormat);
Phil Burk87c9f642017-05-17 07:22:39 -0700209 return AAUDIO_ERROR_INVALID_FORMAT;
210 }
211 destination += numBytes;
212 framesLeft -= framesToProcess;
213 }
214
215 int32_t framesProcessed = numFrames - framesLeft;
Phil Burk5edc4ea2020-04-17 08:15:42 -0700216 mAudioEndpoint->advanceReadIndex(framesProcessed);
Phil Burk87c9f642017-05-17 07:22:39 -0700217
Phil Burkfbf031e2017-10-12 15:58:31 -0700218 //ALOGD("readNowWithConversion() returns %d", framesProcessed);
Phil Burk87c9f642017-05-17 07:22:39 -0700219 return framesProcessed;
220}
221
Phil Burkec89b2e2017-06-20 15:05:06 -0700222int64_t AudioStreamInternalCapture::getFramesWritten() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700223 if (mAudioEndpoint) {
224 const int64_t framesWrittenHardware = isClockModelInControl()
225 ? mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
226 : mAudioEndpoint->getDataWriteCounter();
227 // Add service offset and prevent retrograde motion.
228 mLastFramesWritten = std::max(mLastFramesWritten,
229 framesWrittenHardware + mFramesOffsetFromService);
230 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700231 return mLastFramesWritten;
Phil Burk87c9f642017-05-17 07:22:39 -0700232}
233
Phil Burkec89b2e2017-06-20 15:05:06 -0700234int64_t AudioStreamInternalCapture::getFramesRead() {
Phil Burk5edc4ea2020-04-17 08:15:42 -0700235 if (mAudioEndpoint) {
236 mLastFramesRead = mAudioEndpoint->getDataReadCounter() + mFramesOffsetFromService;
237 }
238 return mLastFramesRead;
Phil Burk87c9f642017-05-17 07:22:39 -0700239}
240
241// Read data from the stream and pass it to the callback for processing.
242void *AudioStreamInternalCapture::callbackLoop() {
243 aaudio_result_t result = AAUDIO_OK;
244 aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE;
jiabind5bd06a2021-04-27 22:04:08 +0000245 if (!isDataCallbackSet()) return nullptr;
Phil Burk87c9f642017-05-17 07:22:39 -0700246
247 // result might be a frame count
248 while (mCallbackEnabled.load() && isActive() && (result >= 0)) {
249
250 // Read audio data from stream.
251 int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames);
252
253 // This is a BLOCKING READ!
Phil Burkbf821e22020-04-17 11:51:43 -0700254 result = read(mCallbackBuffer.get(), mCallbackFrames, timeoutNanos);
Phil Burk87c9f642017-05-17 07:22:39 -0700255 if ((result != mCallbackFrames)) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700256 ALOGE("callbackLoop: read() returned %d", result);
Phil Burk87c9f642017-05-17 07:22:39 -0700257 if (result >= 0) {
258 // Only read some of the frames requested. Must have timed out.
259 result = AAUDIO_ERROR_TIMEOUT;
260 }
Phil Burk134f1972017-12-08 13:06:11 -0800261 maybeCallErrorCallback(result);
Phil Burk87c9f642017-05-17 07:22:39 -0700262 break;
263 }
264
265 // Call application using the AAudio callback interface.
Phil Burkbf821e22020-04-17 11:51:43 -0700266 callbackResult = maybeCallDataCallback(mCallbackBuffer.get(), mCallbackFrames);
Phil Burk87c9f642017-05-17 07:22:39 -0700267
268 if (callbackResult == AAUDIO_CALLBACK_RESULT_STOP) {
Phil Burk762365c2018-12-10 16:02:16 -0800269 ALOGD("%s(): callback returned AAUDIO_CALLBACK_RESULT_STOP", __func__);
Phil Burk5ff3b952021-04-02 17:29:11 +0000270 result = systemStopInternal();
Phil Burk87c9f642017-05-17 07:22:39 -0700271 break;
272 }
273 }
274
Phil Burkfbf031e2017-10-12 15:58:31 -0700275 ALOGD("callbackLoop() exiting, result = %d, isActive() = %d",
Phil Burk87c9f642017-05-17 07:22:39 -0700276 result, (int) isActive());
jiabind5bd06a2021-04-27 22:04:08 +0000277 return nullptr;
Phil Burk87c9f642017-05-17 07:22:39 -0700278}