blob: 78e52704a5abf9e01b0ad7a4fc45c7f0ae419d60 [file] [log] [blame]
Phil Burk39f02dd2017-08-04 09:13:31 -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
17#define LOG_TAG "AAudioServiceEndpointMMAP"
18//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <algorithm>
22#include <assert.h>
23#include <map>
24#include <mutex>
jiabinf1c73972022-04-14 16:28:52 -070025#include <set>
Phil Burk39f02dd2017-08-04 09:13:31 -070026#include <sstream>
Phil Burka77869d2020-05-07 10:39:47 -070027#include <thread>
Phil Burk39f02dd2017-08-04 09:13:31 -070028#include <utils/Singleton.h>
29#include <vector>
30
Phil Burk39f02dd2017-08-04 09:13:31 -070031#include "AAudioEndpointManager.h"
32#include "AAudioServiceEndpoint.h"
33
34#include "core/AudioStreamBuilder.h"
35#include "AAudioServiceEndpoint.h"
36#include "AAudioServiceStreamShared.h"
37#include "AAudioServiceEndpointPlay.h"
38#include "AAudioServiceEndpointMMAP.h"
39
jiabin613e6ae2022-12-21 20:20:11 +000040#define AAUDIO_BUFFER_CAPACITY_MIN (4 * 512)
Phil Burk39f02dd2017-08-04 09:13:31 -070041#define AAUDIO_SAMPLE_RATE_DEFAULT 48000
42
43// This is an estimate of the time difference between the HW and the MMAP time.
44// TODO Get presentation timestamps from the HAL instead of using these estimates.
45#define OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (3 * AAUDIO_NANOS_PER_MILLISECOND)
46#define INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (-1 * AAUDIO_NANOS_PER_MILLISECOND)
47
48using namespace android; // TODO just import names needed
49using namespace aaudio; // TODO just import names needed
50
Phil Burkbbd52862018-04-13 11:37:42 -070051AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
52 : mMmapStream(nullptr)
53 , mAAudioService(audioService) {}
Phil Burk39f02dd2017-08-04 09:13:31 -070054
Phil Burk39f02dd2017-08-04 09:13:31 -070055std::string AAudioServiceEndpointMMAP::dump() const {
56 std::stringstream result;
57
58 result << " MMAP: framesTransferred = " << mFramesTransferred.get();
59 result << ", HW nanos = " << mHardwareTimeOffsetNanos;
60 result << ", port handle = " << mPortHandle;
jiabinfc791ee2023-02-15 19:43:40 +000061 result << ", audio data FD = " << mAudioDataWrapper->getDataFileDescriptor();
Phil Burk39f02dd2017-08-04 09:13:31 -070062 result << "\n";
63
64 result << " HW Offset Micros: " <<
65 (getHardwareTimeOffsetNanos()
66 / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
67
68 result << AAudioServiceEndpoint::dump();
69 return result.str();
70}
71
jiabinf1c73972022-04-14 16:28:52 -070072namespace {
73
74const static std::map<audio_format_t, audio_format_t> NEXT_FORMAT_TO_TRY = {
75 {AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT},
76 {AUDIO_FORMAT_PCM_32_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED},
77 {AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT}
78};
79
80audio_format_t getNextFormatToTry(audio_format_t curFormat, audio_format_t returnedFromAPM) {
81 if (returnedFromAPM != AUDIO_FORMAT_DEFAULT) {
82 return returnedFromAPM;
83 }
84 const auto it = NEXT_FORMAT_TO_TRY.find(curFormat);
85 return it != NEXT_FORMAT_TO_TRY.end() ? it->second : AUDIO_FORMAT_DEFAULT;
86}
87
jiabin613e6ae2022-12-21 20:20:11 +000088} // namespace
jiabinf1c73972022-04-14 16:28:52 -070089
Phil Burk39f02dd2017-08-04 09:13:31 -070090aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
91 aaudio_result_t result = AAUDIO_OK;
jiabinfc791ee2023-02-15 19:43:40 +000092 mAudioDataWrapper = std::make_unique<SharedMemoryWrapper>();
Phil Burk39f02dd2017-08-04 09:13:31 -070093 copyFrom(request.getConstantConfiguration());
Phil Burk7bc710b2022-09-01 16:57:00 +000094 mRequestedDeviceId = getDeviceId();
95
Svet Ganov33761132021-05-13 22:51:08 +000096 mMmapClient.attributionSource = request.getAttributionSource();
97 // TODO b/182392769: use attribution source util
98 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070099 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000100 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700101 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Phil Burk39f02dd2017-08-04 09:13:31 -0700102
Phil Burk04e805b2018-03-27 09:13:53 -0700103 audio_format_t audioFormat = getFormat();
jiabinf1c73972022-04-14 16:28:52 -0700104 std::set<audio_format_t> formatsTried;
105 while (true) {
106 if (formatsTried.find(audioFormat) != formatsTried.end()) {
107 // APM returning something that has already tried.
108 ALOGW("Have already tried to open #x, but failed before");
109 break;
110 }
111 formatsTried.insert(audioFormat);
Phil Burk04e805b2018-03-27 09:13:53 -0700112
jiabinf1c73972022-04-14 16:28:52 -0700113 audio_format_t nextFormatToTry = AUDIO_FORMAT_DEFAULT;
114 result = openWithFormat(audioFormat, &nextFormatToTry);
jiabin613e6ae2022-12-21 20:20:11 +0000115 if (result != AAUDIO_ERROR_UNAVAILABLE) {
jiabinf1c73972022-04-14 16:28:52 -0700116 // Return if it is successful or there is an error that is not
117 // AAUDIO_ERROR_UNAVAILABLE happens.
118 ALOGI("Opened format=%#x with result=%d", audioFormat, result);
119 break;
120 }
Phil Burk04e805b2018-03-27 09:13:53 -0700121
jiabinf1c73972022-04-14 16:28:52 -0700122 nextFormatToTry = getNextFormatToTry(audioFormat, nextFormatToTry);
123 ALOGD("%s() %#x failed, perhaps due to format. Try again with %#x",
124 __func__, audioFormat, nextFormatToTry);
125 audioFormat = nextFormatToTry;
126 if (audioFormat == AUDIO_FORMAT_DEFAULT) {
127 // Nothing else to try
128 break;
129 }
Phil Burk04e805b2018-03-27 09:13:53 -0700130 }
131 return result;
132}
133
jiabinf1c73972022-04-14 16:28:52 -0700134aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(
135 audio_format_t audioFormat, audio_format_t* nextFormatToTry) {
Phil Burk04e805b2018-03-27 09:13:53 -0700136 aaudio_result_t result = AAUDIO_OK;
137 audio_config_base_t config;
138 audio_port_handle_t deviceId;
139
140 const audio_attributes_t attributes = getAudioAttributesFrom(this);
141
Phil Burk7bc710b2022-09-01 16:57:00 +0000142 deviceId = mRequestedDeviceId;
Phil Burk39f02dd2017-08-04 09:13:31 -0700143
144 // Fill in config
Phil Burk0127c1b2018-03-29 13:48:06 -0700145 config.format = audioFormat;
Phil Burk39f02dd2017-08-04 09:13:31 -0700146
147 int32_t aaudioSampleRate = getSampleRate();
148 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
149 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
150 }
151 config.sample_rate = aaudioSampleRate;
152
jiabind1f1cb62020-03-24 11:57:57 -0700153 const aaudio_direction_t direction = getDirection();
154
jiabina9094092021-06-28 20:36:45 +0000155 config.channel_mask = AAudio_getChannelMaskForOpen(
156 getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
157
Phil Burk39f02dd2017-08-04 09:13:31 -0700158 if (direction == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700159 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
160
161 } else if (direction == AAUDIO_DIRECTION_INPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700162 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
163
164 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700165 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700166 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
167 }
168
jiabin613e6ae2022-12-21 20:20:11 +0000169 const MmapStreamInterface::stream_direction_t streamDirection =
Phil Burk39f02dd2017-08-04 09:13:31 -0700170 (direction == AAUDIO_DIRECTION_OUTPUT)
171 ? MmapStreamInterface::DIRECTION_OUTPUT
172 : MmapStreamInterface::DIRECTION_INPUT;
173
jiabin613e6ae2022-12-21 20:20:11 +0000174 const aaudio_session_id_t requestedSessionId = getSessionId();
Phil Burk4e1af9f2018-01-03 15:54:35 -0800175 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
176
Phil Burk39f02dd2017-08-04 09:13:31 -0700177 // Open HAL stream. Set mMmapStream
Phil Burk7bc710b2022-09-01 16:57:00 +0000178 ALOGD("%s trying to open MMAP stream with format=%#x, "
179 "sample_rate=%u, channel_mask=%#x, device=%d",
180 __func__, config.format, config.sample_rate,
181 config.channel_mask, deviceId);
jiabin613e6ae2022-12-21 20:20:11 +0000182 const status_t status = MmapStreamInterface::openMmapStream(streamDirection,
183 &attributes,
184 &config,
185 mMmapClient,
186 &deviceId,
187 &sessionId,
188 this, // callback
189 mMmapStream,
190 &mPortHandle);
Svet Ganov33761132021-05-13 22:51:08 +0000191 ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
192 __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700193 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700194 // This can happen if the resource is busy or the config does
195 // not match the hardware.
jiabinf1c73972022-04-14 16:28:52 -0700196 ALOGD("%s() - openMmapStream() returned status=%d, suggested format=%#x, sample_rate=%u, "
197 "channel_mask=%#x",
198 __func__, status, config.format, config.sample_rate, config.format);
199 *nextFormatToTry = config.format != audioFormat ? config.format
200 : *nextFormatToTry;
Phil Burk39f02dd2017-08-04 09:13:31 -0700201 return AAUDIO_ERROR_UNAVAILABLE;
202 }
203
204 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700205 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700206 }
207 setDeviceId(deviceId);
208
Phil Burk4e1af9f2018-01-03 15:54:35 -0800209 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700210 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800211 }
212
jiabin613e6ae2022-12-21 20:20:11 +0000213 const aaudio_session_id_t actualSessionId =
Phil Burk4e1af9f2018-01-03 15:54:35 -0800214 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
215 ? AAUDIO_SESSION_ID_NONE
216 : (aaudio_session_id_t) sessionId;
217 setSessionId(actualSessionId);
Phil Burked782c82022-02-08 21:43:53 +0000218
219 ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
220 __func__, audioFormat, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800221
Phil Burk39f02dd2017-08-04 09:13:31 -0700222 // Create MMAP/NOIRQ buffer.
jiabinfc791ee2023-02-15 19:43:40 +0000223 result = createMmapBuffer();
millerliang18d1e6c2022-02-08 15:43:40 +0800224 if (result != AAUDIO_OK) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700225 goto error;
Phil Burk39f02dd2017-08-04 09:13:31 -0700226 }
227
228 // Get information about the stream and pass it back to the caller.
jiabina9094092021-06-28 20:36:45 +0000229 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
230 config.channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
231 AAudio_isChannelIndexMask(config.channel_mask)));
Phil Burk39f02dd2017-08-04 09:13:31 -0700232
Phil Burk0127c1b2018-03-29 13:48:06 -0700233 setFormat(config.format);
Phil Burk39f02dd2017-08-04 09:13:31 -0700234 setSampleRate(config.sample_rate);
Robert Wu310037a2022-09-06 21:48:18 +0000235 setHardwareSampleRate(getSampleRate());
236 setHardwareFormat(getFormat());
237 setHardwareSamplesPerFrame(AAudioConvert_channelMaskToCount(getChannelMask()));
Phil Burk39f02dd2017-08-04 09:13:31 -0700238
jiabina5df87b2020-12-29 10:45:19 -0800239 // If the position is not updated while the timestamp is updated for more than a certain amount,
240 // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
241 // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
242 // that is too short.
243 static constexpr int kTimestampGraceBurstCount = 5;
244 mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
245 * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
246
jiabinfc791ee2023-02-15 19:43:40 +0000247 mDataReportOffsetNanos = ((int64_t)mTimestampGracePeriodMs) * AAUDIO_NANOS_PER_MILLISECOND;
248
Phil Burked782c82022-02-08 21:43:53 +0000249 ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
jiabina9094092021-06-28 20:36:45 +0000250 __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
251 deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700252
Phil Burked782c82022-02-08 21:43:53 +0000253 ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
254 __func__, getFormat(), audio_format_to_string(getFormat()),
255 calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700256
Phil Burk39f02dd2017-08-04 09:13:31 -0700257 return result;
258
259error:
260 close();
Phil Burk7bc710b2022-09-01 16:57:00 +0000261 // restore original requests
262 setDeviceId(mRequestedDeviceId);
263 setSessionId(requestedSessionId);
Phil Burk39f02dd2017-08-04 09:13:31 -0700264 return result;
265}
266
Phil Burk320910f2020-08-12 14:29:10 +0000267void AAudioServiceEndpointMMAP::close() {
Phil Burk6e463ce2020-04-13 10:20:20 -0700268 if (mMmapStream != nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700269 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
270 mMmapStream.clear();
Phil Burk39f02dd2017-08-04 09:13:31 -0700271 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
272 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700273}
274
275aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700276 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700277 // Start the client on behalf of the AAudio service.
278 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700279 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700280 audio_attributes_t attr = {};
281 if (stream != nullptr) {
282 attr = getAudioAttributesFrom(stream.get());
283 }
jiabin613e6ae2022-12-21 20:20:11 +0000284 const aaudio_result_t result = startClient(
jiabind1f1cb62020-03-24 11:57:57 -0700285 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700286 // When AudioFlinger is passed a valid port handle then it should not change it.
287 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
288 "%s() port handle not expected to change from %d to %d",
289 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700290 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700291 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700292}
293
jiabin613e6ae2022-12-21 20:20:11 +0000294aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> /*stream*/,
295 audio_port_handle_t /*clientHandle*/) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700296 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700297
298 // Round 64-bit counter up to a multiple of the buffer capacity.
299 // This is required because the 64-bit counter is used as an index
300 // into a circular buffer and the actual HW position is reset to zero
301 // when the stream is stopped.
302 mFramesTransferred.roundUp64(getBufferCapacity());
303
Phil Burkbbd52862018-04-13 11:37:42 -0700304 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700305 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700306 return stopClient(mPortHandle);
307}
308
309aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700310 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700311 audio_port_handle_t *clientHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000312 return mMmapStream == nullptr
313 ? AAUDIO_ERROR_NULL
314 : AAudioConvert_androidToAAudioResult(mMmapStream->start(client, attr, clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700315}
316
317aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000318 return mMmapStream == nullptr
319 ? AAUDIO_ERROR_NULL
320 : AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700321}
322
jiabinf7f06152021-11-22 18:10:14 +0000323aaudio_result_t AAudioServiceEndpointMMAP::standby() {
jiabin613e6ae2022-12-21 20:20:11 +0000324 return mMmapStream == nullptr
325 ? AAUDIO_ERROR_NULL
326 : AAudioConvert_androidToAAudioResult(mMmapStream->standby());
jiabinf7f06152021-11-22 18:10:14 +0000327}
328
329aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
330 if (mMmapStream == nullptr) {
331 return AAUDIO_ERROR_NULL;
332 }
jiabinfc791ee2023-02-15 19:43:40 +0000333 mAudioDataWrapper->reset();
334 const aaudio_result_t result = createMmapBuffer();
jiabinf7f06152021-11-22 18:10:14 +0000335 if (result == AAUDIO_OK) {
jiabinfc791ee2023-02-15 19:43:40 +0000336 getDownDataDescription(parcelable);
jiabinf7f06152021-11-22 18:10:14 +0000337 }
338 return result;
339}
340
Phil Burk39f02dd2017-08-04 09:13:31 -0700341// Get free-running DSP or DMA hardware position from the HAL.
342aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
343 int64_t *timeNanos) {
344 struct audio_mmap_position position;
345 if (mMmapStream == nullptr) {
346 return AAUDIO_ERROR_NULL;
347 }
jiabin613e6ae2022-12-21 20:20:11 +0000348 const status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700349 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
350 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
jiabin613e6ae2022-12-21 20:20:11 +0000351 const aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700352 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700353 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700354 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700355 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700356 } else {
357 // Convert 32-bit position to 64-bit position.
358 mFramesTransferred.update32(position.position_frames);
359 *positionFrames = mFramesTransferred.get();
360 *timeNanos = position.time_nanoseconds;
361 }
362 return result;
363}
364
jiabin613e6ae2022-12-21 20:20:11 +0000365aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t* /*positionFrames*/,
366 int64_t* /*timeNanos*/) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700367 return 0; // TODO
368}
369
Phil Burka77869d2020-05-07 10:39:47 -0700370// This is called by onTearDown() in a separate thread to avoid deadlocks.
371void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
Phil Burkbbd52862018-04-13 11:37:42 -0700372 // Are we tearing down the EXCLUSIVE MMAP stream?
373 if (isStreamRegistered(portHandle)) {
374 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
375 disconnectRegisteredStreams();
376 } else {
377 // Must be a SHARED stream?
378 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
jiabin613e6ae2022-12-21 20:20:11 +0000379 const aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700380 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
381 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700382};
383
Phil Burka77869d2020-05-07 10:39:47 -0700384// This is called by AudioFlinger when it wants to destroy a stream.
385void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
386 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
jiabin613e6ae2022-12-21 20:20:11 +0000387 const android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
Phil Burk3d201942021-04-08 23:27:04 +0000388 std::thread asyncTask([holdEndpoint, portHandle]() {
389 holdEndpoint->handleTearDownAsync(portHandle);
390 });
Phil Burka77869d2020-05-07 10:39:47 -0700391 asyncTask.detach();
392}
393
Robert Wu4389ae62022-02-17 18:39:41 +0000394void AAudioServiceEndpointMMAP::onVolumeChanged(float volume) {
395 ALOGD("%s() volume = %f", __func__, volume);
jiabin613e6ae2022-12-21 20:20:11 +0000396 const std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800397 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700398 stream->onVolumeChanged(volume);
399 }
400};
401
Phil Burka77869d2020-05-07 10:39:47 -0700402void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000403 const auto deviceId = static_cast<int32_t>(portHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700404 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burka77869d2020-05-07 10:39:47 -0700405 if (getDeviceId() != deviceId) {
406 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
jiabin613e6ae2022-12-21 20:20:11 +0000407 const android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
Phil Burk3d201942021-04-08 23:27:04 +0000408 std::thread asyncTask([holdEndpoint, deviceId]() {
409 ALOGD("onRoutingChanged() asyncTask launched");
410 holdEndpoint->disconnectRegisteredStreams();
411 holdEndpoint->setDeviceId(deviceId);
Phil Burka77869d2020-05-07 10:39:47 -0700412 });
413 asyncTask.detach();
414 } else {
415 setDeviceId(deviceId);
416 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700417 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700418};
419
420/**
421 * Get an immutable description of the data queue from the HAL.
422 */
jiabin2a594622021-10-14 00:32:25 +0000423aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
424 AudioEndpointParcelable* parcelable)
Phil Burk39f02dd2017-08-04 09:13:31 -0700425{
jiabinfc791ee2023-02-15 19:43:40 +0000426 if (mAudioDataWrapper->setupFifoBuffer(calculateBytesPerFrame(), getBufferCapacity())
427 != AAUDIO_OK) {
428 ALOGE("Failed to setup audio data wrapper, will not be able to "
429 "set data for sound dose computation");
430 // This will not affect the audio processing capability
431 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700432 // Gather information on the data queue based on HAL info.
jiabinfc791ee2023-02-15 19:43:40 +0000433 mAudioDataWrapper->fillParcelable(parcelable, parcelable->mDownDataQueueParcelable,
434 calculateBytesPerFrame(), mFramesPerBurst,
435 getBufferCapacity(),
436 getDirection() == AAUDIO_DIRECTION_OUTPUT
437 ? SharedMemoryWrapper::WRITE
438 : SharedMemoryWrapper::NONE);
Phil Burk39f02dd2017-08-04 09:13:31 -0700439 return AAUDIO_OK;
440}
jiabinb7d8c5a2020-08-26 17:24:52 -0700441
442aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
443 int64_t *timeNanos)
444{
jiabina5df87b2020-12-29 10:45:19 -0800445 if (mHalExternalPositionStatus != AAUDIO_OK) {
446 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700447 }
jiabina5df87b2020-12-29 10:45:19 -0800448 uint64_t tempPositionFrames;
449 int64_t tempTimeNanos;
jiabin613e6ae2022-12-21 20:20:11 +0000450 const status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
jiabina5df87b2020-12-29 10:45:19 -0800451 if (status != OK) {
452 // getExternalPosition reports error. The HAL may not support the API. Cache the result
jiabinb7d8c5a2020-08-26 17:24:52 -0700453 // so that the call will not go to the HAL next time.
jiabina5df87b2020-12-29 10:45:19 -0800454 mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
455 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700456 }
jiabina5df87b2020-12-29 10:45:19 -0800457
458 // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
459 // to report correct external position. In that case, we will not trust the values reported from
460 // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
461 // correct position within a period. But it may not be a good idea to get system time too often.
462 // In that case, a maximum number of frozen external position is defined so that if the
463 // count of the same timestamp or position is reported by the HAL continuously, the values from
464 // the HAL will no longer be trusted.
465 static constexpr int kMaxFrozenCount = 20;
466 // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
467 // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
468 // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
469 // position is a valid one. Do a simple validation, which is checking if the position is
470 // forward within half a second or not, here so that this function can return error if
471 // the validation fails. Note that we don't only apply this validation logic to HAL API
472 // less than 7.0. The reason is that there is a chance the HAL is not reporting the
473 // timestamp and position correctly.
474 if (mLastPositionFrames > tempPositionFrames) {
475 // If the position is going backwards, there must be something wrong with the HAL.
476 // In that case, we do not trust the values reported by the HAL.
477 ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
478 __func__, mLastPositionFrames, tempPositionFrames);
479 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
480 return mHalExternalPositionStatus;
481 } else if (mLastPositionFrames == tempPositionFrames) {
482 if (tempTimeNanos - mTimestampNanosForLastPosition >
483 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
484 ALOGW("%s, the reported position is not changed within %d msec. "
485 "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
486 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
487 return mHalExternalPositionStatus;
488 }
489 mFrozenPositionCount++;
490 } else {
491 mFrozenPositionCount = 0;
492 }
493
494 if (mTimestampNanosForLastPosition > tempTimeNanos) {
495 // If the timestamp is going backwards, there must be something wrong with the HAL.
496 // In that case, we do not trust the values reported by the HAL.
497 ALOGW("%s timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
498 __func__, mTimestampNanosForLastPosition, tempTimeNanos);
499 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
500 return mHalExternalPositionStatus;
501 } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
502 mFrozenTimestampCount++;
503 } else {
504 mFrozenTimestampCount = 0;
505 }
506
507 if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
508 ALOGW("%s too many frozen external position from HAL.", __func__);
509 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
510 return mHalExternalPositionStatus;
511 }
512
513 mLastPositionFrames = tempPositionFrames;
514 mTimestampNanosForLastPosition = tempTimeNanos;
515
516 // Only update the timestamp and position when they looks valid.
517 *positionFrames = tempPositionFrames;
518 *timeNanos = tempTimeNanos;
519 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700520}
jiabinf7f06152021-11-22 18:10:14 +0000521
jiabinfc791ee2023-02-15 19:43:40 +0000522aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer()
jiabinf7f06152021-11-22 18:10:14 +0000523{
524 memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
525 int32_t minSizeFrames = getBufferCapacity();
526 if (minSizeFrames <= 0) { // zero will get rejected
527 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
528 }
jiabin613e6ae2022-12-21 20:20:11 +0000529 const status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
530 const bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
jiabinf7f06152021-11-22 18:10:14 +0000531 if (status != OK) {
532 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
533 __func__, status, strerror(-status));
534 return AAUDIO_ERROR_UNAVAILABLE;
535 } else {
536 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
537 ", Sharable FD: %s",
538 __func__,
539 mMmapBufferinfo.buffer_size_frames,
540 mMmapBufferinfo.burst_size_frames,
541 isBufferShareable ? "Yes" : "No");
542 }
543
544 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
545 if (!isBufferShareable) {
546 // Exclusive mode can only be used by the service because the FD cannot be shared.
jiabin613e6ae2022-12-21 20:20:11 +0000547 const int32_t audioServiceUid =
jiabinf7f06152021-11-22 18:10:14 +0000548 VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
549 if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
550 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
551 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
552 return AAUDIO_ERROR_UNAVAILABLE;
553 }
554 }
555
556 // AAudio creates a copy of this FD and retains ownership of the copy.
557 // Assume that AudioFlinger will close the original shared_memory_fd.
jiabinfc791ee2023-02-15 19:43:40 +0000558
559 mAudioDataWrapper->getDataFileDescriptor().reset(dup(mMmapBufferinfo.shared_memory_fd));
560 if (mAudioDataWrapper->getDataFileDescriptor().get() == -1) {
jiabinf7f06152021-11-22 18:10:14 +0000561 ALOGE("%s() - could not dup shared_memory_fd", __func__);
562 return AAUDIO_ERROR_INTERNAL;
563 }
564
565 // Call to HAL to make sure the transport FD was able to be closed by binder.
566 // This is a tricky workaround for a problem in Binder.
567 // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
568 struct audio_mmap_position position;
569 mMmapStream->getMmapPosition(&position);
570
571 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
572
573 return AAUDIO_OK;
574}
jiabinfc791ee2023-02-15 19:43:40 +0000575
576int64_t AAudioServiceEndpointMMAP::nextDataReportTime() {
577 return getDirection() == AAUDIO_DIRECTION_OUTPUT
578 ? AudioClock::getNanoseconds() + mDataReportOffsetNanos
579 : std::numeric_limits<int64_t>::max();
580}
581
582void AAudioServiceEndpointMMAP::reportData() {
583 if (mMmapStream == nullptr) {
584 // This must not happen
585 ALOGE("%s() invalid state, mmap stream is not initialized", __func__);
586 return;
587 }
588 auto fifo = mAudioDataWrapper->getFifoBuffer();
589 if (fifo == nullptr) {
590 ALOGE("%s() fifo buffer is not initialized, cannot report data", __func__);
591 return;
592 }
593
594 WrappingBuffer wrappingBuffer;
595 fifo_frames_t framesAvailable = fifo->getFullDataAvailable(&wrappingBuffer);
596 for (size_t i = 0; i < WrappingBuffer::SIZE; ++i) {
597 if (wrappingBuffer.numFrames[i] > 0) {
598 mMmapStream->reportData(wrappingBuffer.data[i], wrappingBuffer.numFrames[i]);
599 }
600 }
601 fifo->advanceReadIndex(framesAvailable);
602}