blob: 5b4fca98ec6647926a691dc2c38ba17da4e232ff [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
Phil Burkbf05e942023-12-21 00:03:09 +000040#include <com_android_media_aaudio.h>
41
jiabin613e6ae2022-12-21 20:20:11 +000042#define AAUDIO_BUFFER_CAPACITY_MIN (4 * 512)
Phil Burk39f02dd2017-08-04 09:13:31 -070043#define AAUDIO_SAMPLE_RATE_DEFAULT 48000
44
45// This is an estimate of the time difference between the HW and the MMAP time.
46// TODO Get presentation timestamps from the HAL instead of using these estimates.
47#define OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (3 * AAUDIO_NANOS_PER_MILLISECOND)
48#define INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (-1 * AAUDIO_NANOS_PER_MILLISECOND)
49
Robert Wud559ba52023-06-29 00:08:51 +000050#define AAUDIO_MAX_OPEN_ATTEMPTS 10
51
Phil Burk39f02dd2017-08-04 09:13:31 -070052using namespace android; // TODO just import names needed
53using namespace aaudio; // TODO just import names needed
54
Phil Burkbbd52862018-04-13 11:37:42 -070055AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
56 : mMmapStream(nullptr)
57 , mAAudioService(audioService) {}
Phil Burk39f02dd2017-08-04 09:13:31 -070058
Phil Burk39f02dd2017-08-04 09:13:31 -070059std::string AAudioServiceEndpointMMAP::dump() const {
60 std::stringstream result;
61
62 result << " MMAP: framesTransferred = " << mFramesTransferred.get();
63 result << ", HW nanos = " << mHardwareTimeOffsetNanos;
64 result << ", port handle = " << mPortHandle;
jiabinfc791ee2023-02-15 19:43:40 +000065 result << ", audio data FD = " << mAudioDataWrapper->getDataFileDescriptor();
Phil Burk39f02dd2017-08-04 09:13:31 -070066 result << "\n";
67
68 result << " HW Offset Micros: " <<
69 (getHardwareTimeOffsetNanos()
70 / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
71
72 result << AAudioServiceEndpoint::dump();
73 return result.str();
74}
75
jiabinf1c73972022-04-14 16:28:52 -070076namespace {
77
78const static std::map<audio_format_t, audio_format_t> NEXT_FORMAT_TO_TRY = {
79 {AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT},
80 {AUDIO_FORMAT_PCM_32_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED},
Robert Wuc59b4c92023-11-30 02:10:29 +000081 {AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_8_24_BIT},
82 {AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_16_BIT}
jiabinf1c73972022-04-14 16:28:52 -070083};
84
Robert Wud559ba52023-06-29 00:08:51 +000085audio_format_t getNextFormatToTry(audio_format_t curFormat) {
jiabinf1c73972022-04-14 16:28:52 -070086 const auto it = NEXT_FORMAT_TO_TRY.find(curFormat);
Robert Wud559ba52023-06-29 00:08:51 +000087 return it != NEXT_FORMAT_TO_TRY.end() ? it->second : curFormat;
jiabinf1c73972022-04-14 16:28:52 -070088}
89
Robert Wud559ba52023-06-29 00:08:51 +000090struct configComp {
91 bool operator() (const audio_config_base_t& lhs, const audio_config_base_t& rhs) const {
92 if (lhs.sample_rate != rhs.sample_rate) {
93 return lhs.sample_rate < rhs.sample_rate;
94 } else if (lhs.channel_mask != rhs.channel_mask) {
95 return lhs.channel_mask < rhs.channel_mask;
96 } else {
97 return lhs.format < rhs.format;
98 }
99 }
100};
101
jiabin613e6ae2022-12-21 20:20:11 +0000102} // namespace
jiabinf1c73972022-04-14 16:28:52 -0700103
Phil Burk39f02dd2017-08-04 09:13:31 -0700104aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
105 aaudio_result_t result = AAUDIO_OK;
jiabinfc791ee2023-02-15 19:43:40 +0000106 mAudioDataWrapper = std::make_unique<SharedMemoryWrapper>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700107 copyFrom(request.getConstantConfiguration());
Phil Burk7bc710b2022-09-01 16:57:00 +0000108 mRequestedDeviceId = getDeviceId();
109
Svet Ganov33761132021-05-13 22:51:08 +0000110 mMmapClient.attributionSource = request.getAttributionSource();
111 // TODO b/182392769: use attribution source util
112 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700113 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000114 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Phil Burk39f02dd2017-08-04 09:13:31 -0700116
Phil Burk04e805b2018-03-27 09:13:53 -0700117 audio_format_t audioFormat = getFormat();
Robert Wud559ba52023-06-29 00:08:51 +0000118 int32_t sampleRate = getSampleRate();
119 if (sampleRate == AAUDIO_UNSPECIFIED) {
120 sampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
121 }
122
123 const aaudio_direction_t direction = getDirection();
124 audio_config_base_t config;
125 config.format = audioFormat;
126 config.sample_rate = sampleRate;
127 config.channel_mask = AAudio_getChannelMaskForOpen(
128 getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
129
130 std::set<audio_config_base_t, configComp> configsTried;
131 int32_t numberOfAttempts = 0;
132 while (numberOfAttempts < AAUDIO_MAX_OPEN_ATTEMPTS) {
133 if (configsTried.find(config) != configsTried.end()) {
jiabinf1c73972022-04-14 16:28:52 -0700134 // APM returning something that has already tried.
Robert Wud559ba52023-06-29 00:08:51 +0000135 ALOGW("Have already tried to open with format=%#x and sr=%d, but failed before",
136 config.format, config.sample_rate);
jiabinf1c73972022-04-14 16:28:52 -0700137 break;
138 }
Robert Wud559ba52023-06-29 00:08:51 +0000139 configsTried.insert(config);
Phil Burk04e805b2018-03-27 09:13:53 -0700140
Robert Wud559ba52023-06-29 00:08:51 +0000141 audio_config_base_t previousConfig = config;
142 result = openWithConfig(&config);
jiabin613e6ae2022-12-21 20:20:11 +0000143 if (result != AAUDIO_ERROR_UNAVAILABLE) {
jiabinf1c73972022-04-14 16:28:52 -0700144 // Return if it is successful or there is an error that is not
145 // AAUDIO_ERROR_UNAVAILABLE happens.
Robert Wud559ba52023-06-29 00:08:51 +0000146 ALOGI("Opened format=%#x sr=%d, with result=%d", previousConfig.format,
147 previousConfig.sample_rate, result);
jiabinf1c73972022-04-14 16:28:52 -0700148 break;
149 }
Phil Burk04e805b2018-03-27 09:13:53 -0700150
Robert Wud559ba52023-06-29 00:08:51 +0000151 // Try other formats if the config from APM is the same as our current config.
152 // Some HALs may report its format support incorrectly.
Phil Burkbf05e942023-12-21 00:03:09 +0000153 if (previousConfig.format == config.format) {
154 if (previousConfig.sample_rate == config.sample_rate) {
155 config.format = getNextFormatToTry(config.format);
156 } else if (!com::android::media::aaudio::sample_rate_conversion()) {
157 ALOGI("%s() - AAudio SRC feature not enabled, different rates! %d != %d",
158 __func__, previousConfig.sample_rate, config.sample_rate);
159 result = AAUDIO_ERROR_INVALID_RATE;
160 break;
161 }
jiabinf1c73972022-04-14 16:28:52 -0700162 }
Robert Wud559ba52023-06-29 00:08:51 +0000163
164 ALOGD("%s() %#x %d failed, perhaps due to format or sample rate. Try again with %#x %d",
165 __func__, previousConfig.format, previousConfig.sample_rate, config.format,
166 config.sample_rate);
167 numberOfAttempts++;
Phil Burk04e805b2018-03-27 09:13:53 -0700168 }
169 return result;
170}
171
Robert Wud559ba52023-06-29 00:08:51 +0000172aaudio_result_t AAudioServiceEndpointMMAP::openWithConfig(
173 audio_config_base_t* config) {
Phil Burk04e805b2018-03-27 09:13:53 -0700174 aaudio_result_t result = AAUDIO_OK;
Robert Wud559ba52023-06-29 00:08:51 +0000175 audio_config_base_t currentConfig = *config;
Phil Burk04e805b2018-03-27 09:13:53 -0700176 audio_port_handle_t deviceId;
177
178 const audio_attributes_t attributes = getAudioAttributesFrom(this);
179
Phil Burk7bc710b2022-09-01 16:57:00 +0000180 deviceId = mRequestedDeviceId;
Phil Burk39f02dd2017-08-04 09:13:31 -0700181
jiabind1f1cb62020-03-24 11:57:57 -0700182 const aaudio_direction_t direction = getDirection();
183
Phil Burk39f02dd2017-08-04 09:13:31 -0700184 if (direction == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700185 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
186
187 } else if (direction == AAUDIO_DIRECTION_INPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700188 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
189
190 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700191 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700192 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
193 }
194
jiabin613e6ae2022-12-21 20:20:11 +0000195 const MmapStreamInterface::stream_direction_t streamDirection =
Phil Burk39f02dd2017-08-04 09:13:31 -0700196 (direction == AAUDIO_DIRECTION_OUTPUT)
197 ? MmapStreamInterface::DIRECTION_OUTPUT
198 : MmapStreamInterface::DIRECTION_INPUT;
199
jiabin613e6ae2022-12-21 20:20:11 +0000200 const aaudio_session_id_t requestedSessionId = getSessionId();
Phil Burk4e1af9f2018-01-03 15:54:35 -0800201 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
202
Phil Burk39f02dd2017-08-04 09:13:31 -0700203 // Open HAL stream. Set mMmapStream
Phil Burk7bc710b2022-09-01 16:57:00 +0000204 ALOGD("%s trying to open MMAP stream with format=%#x, "
205 "sample_rate=%u, channel_mask=%#x, device=%d",
Robert Wud559ba52023-06-29 00:08:51 +0000206 __func__, config->format, config->sample_rate,
207 config->channel_mask, deviceId);
jiabin613e6ae2022-12-21 20:20:11 +0000208 const status_t status = MmapStreamInterface::openMmapStream(streamDirection,
209 &attributes,
Robert Wud559ba52023-06-29 00:08:51 +0000210 config,
jiabin613e6ae2022-12-21 20:20:11 +0000211 mMmapClient,
212 &deviceId,
213 &sessionId,
214 this, // callback
215 mMmapStream,
216 &mPortHandle);
Svet Ganov33761132021-05-13 22:51:08 +0000217 ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
218 __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700219 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700220 // This can happen if the resource is busy or the config does
221 // not match the hardware.
jiabinf1c73972022-04-14 16:28:52 -0700222 ALOGD("%s() - openMmapStream() returned status=%d, suggested format=%#x, sample_rate=%u, "
223 "channel_mask=%#x",
Robert Wud559ba52023-06-29 00:08:51 +0000224 __func__, status, config->format, config->sample_rate, config->channel_mask);
225 // Keep the channel mask of the current config
226 config->channel_mask = currentConfig.channel_mask;
Phil Burk39f02dd2017-08-04 09:13:31 -0700227 return AAUDIO_ERROR_UNAVAILABLE;
228 }
229
230 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700231 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700232 }
233 setDeviceId(deviceId);
234
Phil Burk4e1af9f2018-01-03 15:54:35 -0800235 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700236 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800237 }
238
jiabin613e6ae2022-12-21 20:20:11 +0000239 const aaudio_session_id_t actualSessionId =
Phil Burk4e1af9f2018-01-03 15:54:35 -0800240 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
241 ? AAUDIO_SESSION_ID_NONE
242 : (aaudio_session_id_t) sessionId;
243 setSessionId(actualSessionId);
Phil Burked782c82022-02-08 21:43:53 +0000244
245 ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
Robert Wud559ba52023-06-29 00:08:51 +0000246 __func__, config->format, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800247
Phil Burk39f02dd2017-08-04 09:13:31 -0700248 // Create MMAP/NOIRQ buffer.
jiabinfc791ee2023-02-15 19:43:40 +0000249 result = createMmapBuffer();
millerliang18d1e6c2022-02-08 15:43:40 +0800250 if (result != AAUDIO_OK) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700251 goto error;
Phil Burk39f02dd2017-08-04 09:13:31 -0700252 }
253
254 // Get information about the stream and pass it back to the caller.
jiabina9094092021-06-28 20:36:45 +0000255 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
Robert Wud559ba52023-06-29 00:08:51 +0000256 config->channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
257 AAudio_isChannelIndexMask(config->channel_mask)));
Phil Burk39f02dd2017-08-04 09:13:31 -0700258
Robert Wud559ba52023-06-29 00:08:51 +0000259 setFormat(config->format);
260 setSampleRate(config->sample_rate);
Robert Wu310037a2022-09-06 21:48:18 +0000261 setHardwareSampleRate(getSampleRate());
262 setHardwareFormat(getFormat());
263 setHardwareSamplesPerFrame(AAudioConvert_channelMaskToCount(getChannelMask()));
Phil Burk39f02dd2017-08-04 09:13:31 -0700264
jiabina5df87b2020-12-29 10:45:19 -0800265 // If the position is not updated while the timestamp is updated for more than a certain amount,
266 // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
267 // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
268 // that is too short.
269 static constexpr int kTimestampGraceBurstCount = 5;
270 mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
271 * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
272
jiabinfc791ee2023-02-15 19:43:40 +0000273 mDataReportOffsetNanos = ((int64_t)mTimestampGracePeriodMs) * AAUDIO_NANOS_PER_MILLISECOND;
274
Phil Burked782c82022-02-08 21:43:53 +0000275 ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
jiabina9094092021-06-28 20:36:45 +0000276 __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
277 deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700278
Phil Burked782c82022-02-08 21:43:53 +0000279 ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
280 __func__, getFormat(), audio_format_to_string(getFormat()),
281 calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700282
Phil Burk39f02dd2017-08-04 09:13:31 -0700283 return result;
284
285error:
286 close();
Phil Burk7bc710b2022-09-01 16:57:00 +0000287 // restore original requests
288 setDeviceId(mRequestedDeviceId);
289 setSessionId(requestedSessionId);
Phil Burk39f02dd2017-08-04 09:13:31 -0700290 return result;
291}
292
Phil Burk320910f2020-08-12 14:29:10 +0000293void AAudioServiceEndpointMMAP::close() {
Phil Burk6e463ce2020-04-13 10:20:20 -0700294 if (mMmapStream != nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700295 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
296 mMmapStream.clear();
Phil Burk39f02dd2017-08-04 09:13:31 -0700297 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
298 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700299}
300
301aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700302 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700303 // Start the client on behalf of the AAudio service.
304 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700305 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700306 audio_attributes_t attr = {};
307 if (stream != nullptr) {
308 attr = getAudioAttributesFrom(stream.get());
309 }
jiabin613e6ae2022-12-21 20:20:11 +0000310 const aaudio_result_t result = startClient(
jiabind1f1cb62020-03-24 11:57:57 -0700311 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700312 // When AudioFlinger is passed a valid port handle then it should not change it.
313 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
314 "%s() port handle not expected to change from %d to %d",
315 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700316 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700317 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700318}
319
jiabin613e6ae2022-12-21 20:20:11 +0000320aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> /*stream*/,
321 audio_port_handle_t /*clientHandle*/) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700322 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700323
324 // Round 64-bit counter up to a multiple of the buffer capacity.
325 // This is required because the 64-bit counter is used as an index
326 // into a circular buffer and the actual HW position is reset to zero
327 // when the stream is stopped.
328 mFramesTransferred.roundUp64(getBufferCapacity());
329
Phil Burkbbd52862018-04-13 11:37:42 -0700330 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700331 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700332 return stopClient(mPortHandle);
333}
334
335aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700336 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700337 audio_port_handle_t *clientHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000338 return mMmapStream == nullptr
339 ? AAUDIO_ERROR_NULL
340 : AAudioConvert_androidToAAudioResult(mMmapStream->start(client, attr, clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700341}
342
343aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000344 return mMmapStream == nullptr
345 ? AAUDIO_ERROR_NULL
346 : AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700347}
348
jiabinf7f06152021-11-22 18:10:14 +0000349aaudio_result_t AAudioServiceEndpointMMAP::standby() {
jiabin613e6ae2022-12-21 20:20:11 +0000350 return mMmapStream == nullptr
351 ? AAUDIO_ERROR_NULL
352 : AAudioConvert_androidToAAudioResult(mMmapStream->standby());
jiabinf7f06152021-11-22 18:10:14 +0000353}
354
355aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
356 if (mMmapStream == nullptr) {
357 return AAUDIO_ERROR_NULL;
358 }
jiabinfc791ee2023-02-15 19:43:40 +0000359 mAudioDataWrapper->reset();
360 const aaudio_result_t result = createMmapBuffer();
jiabinf7f06152021-11-22 18:10:14 +0000361 if (result == AAUDIO_OK) {
jiabinfc791ee2023-02-15 19:43:40 +0000362 getDownDataDescription(parcelable);
jiabinf7f06152021-11-22 18:10:14 +0000363 }
364 return result;
365}
366
Phil Burk39f02dd2017-08-04 09:13:31 -0700367// Get free-running DSP or DMA hardware position from the HAL.
368aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
369 int64_t *timeNanos) {
370 struct audio_mmap_position position;
371 if (mMmapStream == nullptr) {
372 return AAUDIO_ERROR_NULL;
373 }
jiabin613e6ae2022-12-21 20:20:11 +0000374 const status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700375 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
376 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
jiabin613e6ae2022-12-21 20:20:11 +0000377 const aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700378 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700379 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700380 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700381 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700382 } else {
383 // Convert 32-bit position to 64-bit position.
384 mFramesTransferred.update32(position.position_frames);
385 *positionFrames = mFramesTransferred.get();
386 *timeNanos = position.time_nanoseconds;
387 }
388 return result;
389}
390
jiabin613e6ae2022-12-21 20:20:11 +0000391aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t* /*positionFrames*/,
392 int64_t* /*timeNanos*/) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700393 return 0; // TODO
394}
395
Phil Burka77869d2020-05-07 10:39:47 -0700396// This is called by onTearDown() in a separate thread to avoid deadlocks.
397void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
Phil Burkbbd52862018-04-13 11:37:42 -0700398 // Are we tearing down the EXCLUSIVE MMAP stream?
399 if (isStreamRegistered(portHandle)) {
400 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
401 disconnectRegisteredStreams();
402 } else {
403 // Must be a SHARED stream?
404 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
jiabin613e6ae2022-12-21 20:20:11 +0000405 const aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700406 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
407 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700408};
409
Phil Burka77869d2020-05-07 10:39:47 -0700410// This is called by AudioFlinger when it wants to destroy a stream.
411void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
412 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
jiabin613e6ae2022-12-21 20:20:11 +0000413 const android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
Phil Burk3d201942021-04-08 23:27:04 +0000414 std::thread asyncTask([holdEndpoint, portHandle]() {
415 holdEndpoint->handleTearDownAsync(portHandle);
416 });
Phil Burka77869d2020-05-07 10:39:47 -0700417 asyncTask.detach();
418}
419
Robert Wu4389ae62022-02-17 18:39:41 +0000420void AAudioServiceEndpointMMAP::onVolumeChanged(float volume) {
421 ALOGD("%s() volume = %f", __func__, volume);
jiabin613e6ae2022-12-21 20:20:11 +0000422 const std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800423 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700424 stream->onVolumeChanged(volume);
425 }
426};
427
Phil Burka77869d2020-05-07 10:39:47 -0700428void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000429 const auto deviceId = static_cast<int32_t>(portHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700430 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burka77869d2020-05-07 10:39:47 -0700431 if (getDeviceId() != deviceId) {
432 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
jiabind7ff88a2023-12-04 18:40:26 +0000433 // When there is a routing changed, mmap stream should be disconnected. Set `mConnected`
434 // as false here so that there won't be a new stream connect to this endpoint.
435 mConnected.store(false);
jiabin613e6ae2022-12-21 20:20:11 +0000436 const android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
Phil Burk3d201942021-04-08 23:27:04 +0000437 std::thread asyncTask([holdEndpoint, deviceId]() {
438 ALOGD("onRoutingChanged() asyncTask launched");
jiabind7ff88a2023-12-04 18:40:26 +0000439 // When routing changed, the stream is disconnected and cannot be used except for
440 // closing. In that case, it should be safe to release all registered streams.
441 // This can help release service side resource in case the client doesn't close
442 // the stream after receiving disconnect event.
443 holdEndpoint->releaseRegisteredStreams();
Phil Burk3d201942021-04-08 23:27:04 +0000444 holdEndpoint->setDeviceId(deviceId);
Phil Burka77869d2020-05-07 10:39:47 -0700445 });
446 asyncTask.detach();
447 } else {
448 setDeviceId(deviceId);
449 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700450 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700451};
452
453/**
454 * Get an immutable description of the data queue from the HAL.
455 */
jiabin2a594622021-10-14 00:32:25 +0000456aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
457 AudioEndpointParcelable* parcelable)
Phil Burk39f02dd2017-08-04 09:13:31 -0700458{
jiabinfc791ee2023-02-15 19:43:40 +0000459 if (mAudioDataWrapper->setupFifoBuffer(calculateBytesPerFrame(), getBufferCapacity())
460 != AAUDIO_OK) {
461 ALOGE("Failed to setup audio data wrapper, will not be able to "
462 "set data for sound dose computation");
463 // This will not affect the audio processing capability
464 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700465 // Gather information on the data queue based on HAL info.
jiabinfc791ee2023-02-15 19:43:40 +0000466 mAudioDataWrapper->fillParcelable(parcelable, parcelable->mDownDataQueueParcelable,
467 calculateBytesPerFrame(), mFramesPerBurst,
468 getBufferCapacity(),
469 getDirection() == AAUDIO_DIRECTION_OUTPUT
470 ? SharedMemoryWrapper::WRITE
471 : SharedMemoryWrapper::NONE);
Phil Burk39f02dd2017-08-04 09:13:31 -0700472 return AAUDIO_OK;
473}
jiabinb7d8c5a2020-08-26 17:24:52 -0700474
475aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
476 int64_t *timeNanos)
477{
jiabina5df87b2020-12-29 10:45:19 -0800478 if (mHalExternalPositionStatus != AAUDIO_OK) {
479 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700480 }
jiabina5df87b2020-12-29 10:45:19 -0800481 uint64_t tempPositionFrames;
482 int64_t tempTimeNanos;
jiabin613e6ae2022-12-21 20:20:11 +0000483 const status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
jiabina5df87b2020-12-29 10:45:19 -0800484 if (status != OK) {
485 // getExternalPosition reports error. The HAL may not support the API. Cache the result
jiabinb7d8c5a2020-08-26 17:24:52 -0700486 // so that the call will not go to the HAL next time.
jiabina5df87b2020-12-29 10:45:19 -0800487 mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
488 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700489 }
jiabina5df87b2020-12-29 10:45:19 -0800490
491 // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
492 // to report correct external position. In that case, we will not trust the values reported from
493 // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
494 // correct position within a period. But it may not be a good idea to get system time too often.
495 // In that case, a maximum number of frozen external position is defined so that if the
496 // count of the same timestamp or position is reported by the HAL continuously, the values from
497 // the HAL will no longer be trusted.
498 static constexpr int kMaxFrozenCount = 20;
499 // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
500 // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
501 // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
502 // position is a valid one. Do a simple validation, which is checking if the position is
503 // forward within half a second or not, here so that this function can return error if
504 // the validation fails. Note that we don't only apply this validation logic to HAL API
505 // less than 7.0. The reason is that there is a chance the HAL is not reporting the
506 // timestamp and position correctly.
507 if (mLastPositionFrames > tempPositionFrames) {
508 // If the position is going backwards, there must be something wrong with the HAL.
509 // In that case, we do not trust the values reported by the HAL.
510 ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
511 __func__, mLastPositionFrames, tempPositionFrames);
512 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
513 return mHalExternalPositionStatus;
514 } else if (mLastPositionFrames == tempPositionFrames) {
515 if (tempTimeNanos - mTimestampNanosForLastPosition >
516 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
517 ALOGW("%s, the reported position is not changed within %d msec. "
518 "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
519 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
520 return mHalExternalPositionStatus;
521 }
522 mFrozenPositionCount++;
523 } else {
524 mFrozenPositionCount = 0;
525 }
526
527 if (mTimestampNanosForLastPosition > tempTimeNanos) {
528 // If the timestamp is going backwards, there must be something wrong with the HAL.
529 // In that case, we do not trust the values reported by the HAL.
530 ALOGW("%s timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
531 __func__, mTimestampNanosForLastPosition, tempTimeNanos);
532 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
533 return mHalExternalPositionStatus;
534 } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
535 mFrozenTimestampCount++;
536 } else {
537 mFrozenTimestampCount = 0;
538 }
539
540 if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
541 ALOGW("%s too many frozen external position from HAL.", __func__);
542 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
543 return mHalExternalPositionStatus;
544 }
545
546 mLastPositionFrames = tempPositionFrames;
547 mTimestampNanosForLastPosition = tempTimeNanos;
548
549 // Only update the timestamp and position when they looks valid.
550 *positionFrames = tempPositionFrames;
551 *timeNanos = tempTimeNanos;
552 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700553}
jiabinf7f06152021-11-22 18:10:14 +0000554
jiabinfc791ee2023-02-15 19:43:40 +0000555aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer()
jiabinf7f06152021-11-22 18:10:14 +0000556{
557 memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
558 int32_t minSizeFrames = getBufferCapacity();
559 if (minSizeFrames <= 0) { // zero will get rejected
560 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
561 }
jiabin613e6ae2022-12-21 20:20:11 +0000562 const status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
563 const bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
jiabinf7f06152021-11-22 18:10:14 +0000564 if (status != OK) {
565 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
566 __func__, status, strerror(-status));
567 return AAUDIO_ERROR_UNAVAILABLE;
568 } else {
569 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
570 ", Sharable FD: %s",
571 __func__,
572 mMmapBufferinfo.buffer_size_frames,
573 mMmapBufferinfo.burst_size_frames,
574 isBufferShareable ? "Yes" : "No");
575 }
576
577 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
578 if (!isBufferShareable) {
579 // Exclusive mode can only be used by the service because the FD cannot be shared.
jiabin613e6ae2022-12-21 20:20:11 +0000580 const int32_t audioServiceUid =
jiabinf7f06152021-11-22 18:10:14 +0000581 VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
582 if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
583 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
584 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
585 return AAUDIO_ERROR_UNAVAILABLE;
586 }
587 }
588
589 // AAudio creates a copy of this FD and retains ownership of the copy.
590 // Assume that AudioFlinger will close the original shared_memory_fd.
jiabinfc791ee2023-02-15 19:43:40 +0000591
592 mAudioDataWrapper->getDataFileDescriptor().reset(dup(mMmapBufferinfo.shared_memory_fd));
593 if (mAudioDataWrapper->getDataFileDescriptor().get() == -1) {
jiabinf7f06152021-11-22 18:10:14 +0000594 ALOGE("%s() - could not dup shared_memory_fd", __func__);
595 return AAUDIO_ERROR_INTERNAL;
596 }
597
598 // Call to HAL to make sure the transport FD was able to be closed by binder.
599 // This is a tricky workaround for a problem in Binder.
600 // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
601 struct audio_mmap_position position;
602 mMmapStream->getMmapPosition(&position);
603
604 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
605
606 return AAUDIO_OK;
607}
jiabinfc791ee2023-02-15 19:43:40 +0000608
609int64_t AAudioServiceEndpointMMAP::nextDataReportTime() {
610 return getDirection() == AAUDIO_DIRECTION_OUTPUT
611 ? AudioClock::getNanoseconds() + mDataReportOffsetNanos
612 : std::numeric_limits<int64_t>::max();
613}
614
615void AAudioServiceEndpointMMAP::reportData() {
616 if (mMmapStream == nullptr) {
617 // This must not happen
618 ALOGE("%s() invalid state, mmap stream is not initialized", __func__);
619 return;
620 }
621 auto fifo = mAudioDataWrapper->getFifoBuffer();
622 if (fifo == nullptr) {
623 ALOGE("%s() fifo buffer is not initialized, cannot report data", __func__);
624 return;
625 }
626
627 WrappingBuffer wrappingBuffer;
628 fifo_frames_t framesAvailable = fifo->getFullDataAvailable(&wrappingBuffer);
629 for (size_t i = 0; i < WrappingBuffer::SIZE; ++i) {
630 if (wrappingBuffer.numFrames[i] > 0) {
631 mMmapStream->reportData(wrappingBuffer.data[i], wrappingBuffer.numFrames[i]);
632 }
633 }
634 fifo->advanceReadIndex(framesAvailable);
635}