blob: 12b77c55295c63c15488b5f7a3ba0e4e31acaafe [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
Robert Wud559ba52023-06-29 00:08:51 +000048#define AAUDIO_MAX_OPEN_ATTEMPTS 10
49
Phil Burk39f02dd2017-08-04 09:13:31 -070050using namespace android; // TODO just import names needed
51using namespace aaudio; // TODO just import names needed
52
Phil Burkbbd52862018-04-13 11:37:42 -070053AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
54 : mMmapStream(nullptr)
55 , mAAudioService(audioService) {}
Phil Burk39f02dd2017-08-04 09:13:31 -070056
Phil Burk39f02dd2017-08-04 09:13:31 -070057std::string AAudioServiceEndpointMMAP::dump() const {
58 std::stringstream result;
59
60 result << " MMAP: framesTransferred = " << mFramesTransferred.get();
61 result << ", HW nanos = " << mHardwareTimeOffsetNanos;
62 result << ", port handle = " << mPortHandle;
jiabinfc791ee2023-02-15 19:43:40 +000063 result << ", audio data FD = " << mAudioDataWrapper->getDataFileDescriptor();
Phil Burk39f02dd2017-08-04 09:13:31 -070064 result << "\n";
65
66 result << " HW Offset Micros: " <<
67 (getHardwareTimeOffsetNanos()
68 / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
69
70 result << AAudioServiceEndpoint::dump();
71 return result.str();
72}
73
jiabinf1c73972022-04-14 16:28:52 -070074namespace {
75
76const static std::map<audio_format_t, audio_format_t> NEXT_FORMAT_TO_TRY = {
77 {AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT},
78 {AUDIO_FORMAT_PCM_32_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED},
79 {AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT}
80};
81
Robert Wud559ba52023-06-29 00:08:51 +000082audio_format_t getNextFormatToTry(audio_format_t curFormat) {
jiabinf1c73972022-04-14 16:28:52 -070083 const auto it = NEXT_FORMAT_TO_TRY.find(curFormat);
Robert Wud559ba52023-06-29 00:08:51 +000084 return it != NEXT_FORMAT_TO_TRY.end() ? it->second : curFormat;
jiabinf1c73972022-04-14 16:28:52 -070085}
86
Robert Wud559ba52023-06-29 00:08:51 +000087struct configComp {
88 bool operator() (const audio_config_base_t& lhs, const audio_config_base_t& rhs) const {
89 if (lhs.sample_rate != rhs.sample_rate) {
90 return lhs.sample_rate < rhs.sample_rate;
91 } else if (lhs.channel_mask != rhs.channel_mask) {
92 return lhs.channel_mask < rhs.channel_mask;
93 } else {
94 return lhs.format < rhs.format;
95 }
96 }
97};
98
jiabin613e6ae2022-12-21 20:20:11 +000099} // namespace
jiabinf1c73972022-04-14 16:28:52 -0700100
Phil Burk39f02dd2017-08-04 09:13:31 -0700101aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
102 aaudio_result_t result = AAUDIO_OK;
jiabinfc791ee2023-02-15 19:43:40 +0000103 mAudioDataWrapper = std::make_unique<SharedMemoryWrapper>();
Phil Burk39f02dd2017-08-04 09:13:31 -0700104 copyFrom(request.getConstantConfiguration());
Phil Burk7bc710b2022-09-01 16:57:00 +0000105 mRequestedDeviceId = getDeviceId();
106
Svet Ganov33761132021-05-13 22:51:08 +0000107 mMmapClient.attributionSource = request.getAttributionSource();
108 // TODO b/182392769: use attribution source util
109 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700110 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000111 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700112 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Phil Burk39f02dd2017-08-04 09:13:31 -0700113
Phil Burk04e805b2018-03-27 09:13:53 -0700114 audio_format_t audioFormat = getFormat();
Robert Wud559ba52023-06-29 00:08:51 +0000115 int32_t sampleRate = getSampleRate();
116 if (sampleRate == AAUDIO_UNSPECIFIED) {
117 sampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
118 }
119
120 const aaudio_direction_t direction = getDirection();
121 audio_config_base_t config;
122 config.format = audioFormat;
123 config.sample_rate = sampleRate;
124 config.channel_mask = AAudio_getChannelMaskForOpen(
125 getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
126
127 std::set<audio_config_base_t, configComp> configsTried;
128 int32_t numberOfAttempts = 0;
129 while (numberOfAttempts < AAUDIO_MAX_OPEN_ATTEMPTS) {
130 if (configsTried.find(config) != configsTried.end()) {
jiabinf1c73972022-04-14 16:28:52 -0700131 // APM returning something that has already tried.
Robert Wud559ba52023-06-29 00:08:51 +0000132 ALOGW("Have already tried to open with format=%#x and sr=%d, but failed before",
133 config.format, config.sample_rate);
jiabinf1c73972022-04-14 16:28:52 -0700134 break;
135 }
Robert Wud559ba52023-06-29 00:08:51 +0000136 configsTried.insert(config);
Phil Burk04e805b2018-03-27 09:13:53 -0700137
Robert Wud559ba52023-06-29 00:08:51 +0000138 audio_config_base_t previousConfig = config;
139 result = openWithConfig(&config);
jiabin613e6ae2022-12-21 20:20:11 +0000140 if (result != AAUDIO_ERROR_UNAVAILABLE) {
jiabinf1c73972022-04-14 16:28:52 -0700141 // Return if it is successful or there is an error that is not
142 // AAUDIO_ERROR_UNAVAILABLE happens.
Robert Wud559ba52023-06-29 00:08:51 +0000143 ALOGI("Opened format=%#x sr=%d, with result=%d", previousConfig.format,
144 previousConfig.sample_rate, result);
jiabinf1c73972022-04-14 16:28:52 -0700145 break;
146 }
Phil Burk04e805b2018-03-27 09:13:53 -0700147
Robert Wud559ba52023-06-29 00:08:51 +0000148 // Try other formats if the config from APM is the same as our current config.
149 // Some HALs may report its format support incorrectly.
150 if ((previousConfig.format == config.format) &&
151 (previousConfig.sample_rate == config.sample_rate)) {
152 config.format = getNextFormatToTry(config.format);
jiabinf1c73972022-04-14 16:28:52 -0700153 }
Robert Wud559ba52023-06-29 00:08:51 +0000154
155 ALOGD("%s() %#x %d failed, perhaps due to format or sample rate. Try again with %#x %d",
156 __func__, previousConfig.format, previousConfig.sample_rate, config.format,
157 config.sample_rate);
158 numberOfAttempts++;
Phil Burk04e805b2018-03-27 09:13:53 -0700159 }
160 return result;
161}
162
Robert Wud559ba52023-06-29 00:08:51 +0000163aaudio_result_t AAudioServiceEndpointMMAP::openWithConfig(
164 audio_config_base_t* config) {
Phil Burk04e805b2018-03-27 09:13:53 -0700165 aaudio_result_t result = AAUDIO_OK;
Robert Wud559ba52023-06-29 00:08:51 +0000166 audio_config_base_t currentConfig = *config;
Phil Burk04e805b2018-03-27 09:13:53 -0700167 audio_port_handle_t deviceId;
168
169 const audio_attributes_t attributes = getAudioAttributesFrom(this);
170
Phil Burk7bc710b2022-09-01 16:57:00 +0000171 deviceId = mRequestedDeviceId;
Phil Burk39f02dd2017-08-04 09:13:31 -0700172
jiabind1f1cb62020-03-24 11:57:57 -0700173 const aaudio_direction_t direction = getDirection();
174
Phil Burk39f02dd2017-08-04 09:13:31 -0700175 if (direction == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700176 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
177
178 } else if (direction == AAUDIO_DIRECTION_INPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700179 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
180
181 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700182 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700183 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
184 }
185
jiabin613e6ae2022-12-21 20:20:11 +0000186 const MmapStreamInterface::stream_direction_t streamDirection =
Phil Burk39f02dd2017-08-04 09:13:31 -0700187 (direction == AAUDIO_DIRECTION_OUTPUT)
188 ? MmapStreamInterface::DIRECTION_OUTPUT
189 : MmapStreamInterface::DIRECTION_INPUT;
190
jiabin613e6ae2022-12-21 20:20:11 +0000191 const aaudio_session_id_t requestedSessionId = getSessionId();
Phil Burk4e1af9f2018-01-03 15:54:35 -0800192 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
193
Phil Burk39f02dd2017-08-04 09:13:31 -0700194 // Open HAL stream. Set mMmapStream
Phil Burk7bc710b2022-09-01 16:57:00 +0000195 ALOGD("%s trying to open MMAP stream with format=%#x, "
196 "sample_rate=%u, channel_mask=%#x, device=%d",
Robert Wud559ba52023-06-29 00:08:51 +0000197 __func__, config->format, config->sample_rate,
198 config->channel_mask, deviceId);
jiabin613e6ae2022-12-21 20:20:11 +0000199 const status_t status = MmapStreamInterface::openMmapStream(streamDirection,
200 &attributes,
Robert Wud559ba52023-06-29 00:08:51 +0000201 config,
jiabin613e6ae2022-12-21 20:20:11 +0000202 mMmapClient,
203 &deviceId,
204 &sessionId,
205 this, // callback
206 mMmapStream,
207 &mPortHandle);
Svet Ganov33761132021-05-13 22:51:08 +0000208 ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
209 __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700210 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700211 // This can happen if the resource is busy or the config does
212 // not match the hardware.
jiabinf1c73972022-04-14 16:28:52 -0700213 ALOGD("%s() - openMmapStream() returned status=%d, suggested format=%#x, sample_rate=%u, "
214 "channel_mask=%#x",
Robert Wud559ba52023-06-29 00:08:51 +0000215 __func__, status, config->format, config->sample_rate, config->channel_mask);
216 // Keep the channel mask of the current config
217 config->channel_mask = currentConfig.channel_mask;
Phil Burk39f02dd2017-08-04 09:13:31 -0700218 return AAUDIO_ERROR_UNAVAILABLE;
219 }
220
221 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700222 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700223 }
224 setDeviceId(deviceId);
225
Phil Burk4e1af9f2018-01-03 15:54:35 -0800226 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700227 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800228 }
229
jiabin613e6ae2022-12-21 20:20:11 +0000230 const aaudio_session_id_t actualSessionId =
Phil Burk4e1af9f2018-01-03 15:54:35 -0800231 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
232 ? AAUDIO_SESSION_ID_NONE
233 : (aaudio_session_id_t) sessionId;
234 setSessionId(actualSessionId);
Phil Burked782c82022-02-08 21:43:53 +0000235
236 ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
Robert Wud559ba52023-06-29 00:08:51 +0000237 __func__, config->format, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800238
Phil Burk39f02dd2017-08-04 09:13:31 -0700239 // Create MMAP/NOIRQ buffer.
jiabinfc791ee2023-02-15 19:43:40 +0000240 result = createMmapBuffer();
millerliang18d1e6c2022-02-08 15:43:40 +0800241 if (result != AAUDIO_OK) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700242 goto error;
Phil Burk39f02dd2017-08-04 09:13:31 -0700243 }
244
245 // Get information about the stream and pass it back to the caller.
jiabina9094092021-06-28 20:36:45 +0000246 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
Robert Wud559ba52023-06-29 00:08:51 +0000247 config->channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
248 AAudio_isChannelIndexMask(config->channel_mask)));
Phil Burk39f02dd2017-08-04 09:13:31 -0700249
Robert Wud559ba52023-06-29 00:08:51 +0000250 setFormat(config->format);
251 setSampleRate(config->sample_rate);
Robert Wu310037a2022-09-06 21:48:18 +0000252 setHardwareSampleRate(getSampleRate());
253 setHardwareFormat(getFormat());
254 setHardwareSamplesPerFrame(AAudioConvert_channelMaskToCount(getChannelMask()));
Phil Burk39f02dd2017-08-04 09:13:31 -0700255
jiabina5df87b2020-12-29 10:45:19 -0800256 // If the position is not updated while the timestamp is updated for more than a certain amount,
257 // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
258 // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
259 // that is too short.
260 static constexpr int kTimestampGraceBurstCount = 5;
261 mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
262 * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
263
jiabinfc791ee2023-02-15 19:43:40 +0000264 mDataReportOffsetNanos = ((int64_t)mTimestampGracePeriodMs) * AAUDIO_NANOS_PER_MILLISECOND;
265
Phil Burked782c82022-02-08 21:43:53 +0000266 ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
jiabina9094092021-06-28 20:36:45 +0000267 __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
268 deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700269
Phil Burked782c82022-02-08 21:43:53 +0000270 ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
271 __func__, getFormat(), audio_format_to_string(getFormat()),
272 calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700273
Phil Burk39f02dd2017-08-04 09:13:31 -0700274 return result;
275
276error:
277 close();
Phil Burk7bc710b2022-09-01 16:57:00 +0000278 // restore original requests
279 setDeviceId(mRequestedDeviceId);
280 setSessionId(requestedSessionId);
Phil Burk39f02dd2017-08-04 09:13:31 -0700281 return result;
282}
283
Phil Burk320910f2020-08-12 14:29:10 +0000284void AAudioServiceEndpointMMAP::close() {
Phil Burk6e463ce2020-04-13 10:20:20 -0700285 if (mMmapStream != nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700286 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
287 mMmapStream.clear();
Phil Burk39f02dd2017-08-04 09:13:31 -0700288 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
289 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700290}
291
292aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700293 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700294 // Start the client on behalf of the AAudio service.
295 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700296 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700297 audio_attributes_t attr = {};
298 if (stream != nullptr) {
299 attr = getAudioAttributesFrom(stream.get());
300 }
jiabin613e6ae2022-12-21 20:20:11 +0000301 const aaudio_result_t result = startClient(
jiabind1f1cb62020-03-24 11:57:57 -0700302 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700303 // When AudioFlinger is passed a valid port handle then it should not change it.
304 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
305 "%s() port handle not expected to change from %d to %d",
306 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700307 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700308 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700309}
310
jiabin613e6ae2022-12-21 20:20:11 +0000311aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> /*stream*/,
312 audio_port_handle_t /*clientHandle*/) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700313 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700314
315 // Round 64-bit counter up to a multiple of the buffer capacity.
316 // This is required because the 64-bit counter is used as an index
317 // into a circular buffer and the actual HW position is reset to zero
318 // when the stream is stopped.
319 mFramesTransferred.roundUp64(getBufferCapacity());
320
Phil Burkbbd52862018-04-13 11:37:42 -0700321 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700322 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700323 return stopClient(mPortHandle);
324}
325
326aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700327 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700328 audio_port_handle_t *clientHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000329 return mMmapStream == nullptr
330 ? AAUDIO_ERROR_NULL
331 : AAudioConvert_androidToAAudioResult(mMmapStream->start(client, attr, clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700332}
333
334aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000335 return mMmapStream == nullptr
336 ? AAUDIO_ERROR_NULL
337 : AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700338}
339
jiabinf7f06152021-11-22 18:10:14 +0000340aaudio_result_t AAudioServiceEndpointMMAP::standby() {
jiabin613e6ae2022-12-21 20:20:11 +0000341 return mMmapStream == nullptr
342 ? AAUDIO_ERROR_NULL
343 : AAudioConvert_androidToAAudioResult(mMmapStream->standby());
jiabinf7f06152021-11-22 18:10:14 +0000344}
345
346aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
347 if (mMmapStream == nullptr) {
348 return AAUDIO_ERROR_NULL;
349 }
jiabinfc791ee2023-02-15 19:43:40 +0000350 mAudioDataWrapper->reset();
351 const aaudio_result_t result = createMmapBuffer();
jiabinf7f06152021-11-22 18:10:14 +0000352 if (result == AAUDIO_OK) {
jiabinfc791ee2023-02-15 19:43:40 +0000353 getDownDataDescription(parcelable);
jiabinf7f06152021-11-22 18:10:14 +0000354 }
355 return result;
356}
357
Phil Burk39f02dd2017-08-04 09:13:31 -0700358// Get free-running DSP or DMA hardware position from the HAL.
359aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
360 int64_t *timeNanos) {
361 struct audio_mmap_position position;
362 if (mMmapStream == nullptr) {
363 return AAUDIO_ERROR_NULL;
364 }
jiabin613e6ae2022-12-21 20:20:11 +0000365 const status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700366 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
367 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
jiabin613e6ae2022-12-21 20:20:11 +0000368 const aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700369 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700370 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700371 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700372 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700373 } else {
374 // Convert 32-bit position to 64-bit position.
375 mFramesTransferred.update32(position.position_frames);
376 *positionFrames = mFramesTransferred.get();
377 *timeNanos = position.time_nanoseconds;
378 }
379 return result;
380}
381
jiabin613e6ae2022-12-21 20:20:11 +0000382aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t* /*positionFrames*/,
383 int64_t* /*timeNanos*/) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700384 return 0; // TODO
385}
386
Phil Burka77869d2020-05-07 10:39:47 -0700387// This is called by onTearDown() in a separate thread to avoid deadlocks.
388void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
Phil Burkbbd52862018-04-13 11:37:42 -0700389 // Are we tearing down the EXCLUSIVE MMAP stream?
390 if (isStreamRegistered(portHandle)) {
391 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
392 disconnectRegisteredStreams();
393 } else {
394 // Must be a SHARED stream?
395 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
jiabin613e6ae2022-12-21 20:20:11 +0000396 const aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700397 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
398 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700399};
400
Phil Burka77869d2020-05-07 10:39:47 -0700401// This is called by AudioFlinger when it wants to destroy a stream.
402void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
403 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
jiabin613e6ae2022-12-21 20:20:11 +0000404 const android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
Phil Burk3d201942021-04-08 23:27:04 +0000405 std::thread asyncTask([holdEndpoint, portHandle]() {
406 holdEndpoint->handleTearDownAsync(portHandle);
407 });
Phil Burka77869d2020-05-07 10:39:47 -0700408 asyncTask.detach();
409}
410
Robert Wu4389ae62022-02-17 18:39:41 +0000411void AAudioServiceEndpointMMAP::onVolumeChanged(float volume) {
412 ALOGD("%s() volume = %f", __func__, volume);
jiabin613e6ae2022-12-21 20:20:11 +0000413 const std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800414 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700415 stream->onVolumeChanged(volume);
416 }
417};
418
Phil Burka77869d2020-05-07 10:39:47 -0700419void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
jiabin613e6ae2022-12-21 20:20:11 +0000420 const auto deviceId = static_cast<int32_t>(portHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700421 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burka77869d2020-05-07 10:39:47 -0700422 if (getDeviceId() != deviceId) {
423 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
jiabind7ff88a2023-12-04 18:40:26 +0000424 // When there is a routing changed, mmap stream should be disconnected. Set `mConnected`
425 // as false here so that there won't be a new stream connect to this endpoint.
426 mConnected.store(false);
jiabin613e6ae2022-12-21 20:20:11 +0000427 const android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
Phil Burk3d201942021-04-08 23:27:04 +0000428 std::thread asyncTask([holdEndpoint, deviceId]() {
429 ALOGD("onRoutingChanged() asyncTask launched");
jiabind7ff88a2023-12-04 18:40:26 +0000430 // When routing changed, the stream is disconnected and cannot be used except for
431 // closing. In that case, it should be safe to release all registered streams.
432 // This can help release service side resource in case the client doesn't close
433 // the stream after receiving disconnect event.
434 holdEndpoint->releaseRegisteredStreams();
Phil Burk3d201942021-04-08 23:27:04 +0000435 holdEndpoint->setDeviceId(deviceId);
Phil Burka77869d2020-05-07 10:39:47 -0700436 });
437 asyncTask.detach();
438 } else {
439 setDeviceId(deviceId);
440 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700441 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700442};
443
444/**
445 * Get an immutable description of the data queue from the HAL.
446 */
jiabin2a594622021-10-14 00:32:25 +0000447aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
448 AudioEndpointParcelable* parcelable)
Phil Burk39f02dd2017-08-04 09:13:31 -0700449{
jiabinfc791ee2023-02-15 19:43:40 +0000450 if (mAudioDataWrapper->setupFifoBuffer(calculateBytesPerFrame(), getBufferCapacity())
451 != AAUDIO_OK) {
452 ALOGE("Failed to setup audio data wrapper, will not be able to "
453 "set data for sound dose computation");
454 // This will not affect the audio processing capability
455 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700456 // Gather information on the data queue based on HAL info.
jiabinfc791ee2023-02-15 19:43:40 +0000457 mAudioDataWrapper->fillParcelable(parcelable, parcelable->mDownDataQueueParcelable,
458 calculateBytesPerFrame(), mFramesPerBurst,
459 getBufferCapacity(),
460 getDirection() == AAUDIO_DIRECTION_OUTPUT
461 ? SharedMemoryWrapper::WRITE
462 : SharedMemoryWrapper::NONE);
Phil Burk39f02dd2017-08-04 09:13:31 -0700463 return AAUDIO_OK;
464}
jiabinb7d8c5a2020-08-26 17:24:52 -0700465
466aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
467 int64_t *timeNanos)
468{
jiabina5df87b2020-12-29 10:45:19 -0800469 if (mHalExternalPositionStatus != AAUDIO_OK) {
470 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700471 }
jiabina5df87b2020-12-29 10:45:19 -0800472 uint64_t tempPositionFrames;
473 int64_t tempTimeNanos;
jiabin613e6ae2022-12-21 20:20:11 +0000474 const status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
jiabina5df87b2020-12-29 10:45:19 -0800475 if (status != OK) {
476 // getExternalPosition reports error. The HAL may not support the API. Cache the result
jiabinb7d8c5a2020-08-26 17:24:52 -0700477 // so that the call will not go to the HAL next time.
jiabina5df87b2020-12-29 10:45:19 -0800478 mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
479 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700480 }
jiabina5df87b2020-12-29 10:45:19 -0800481
482 // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
483 // to report correct external position. In that case, we will not trust the values reported from
484 // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
485 // correct position within a period. But it may not be a good idea to get system time too often.
486 // In that case, a maximum number of frozen external position is defined so that if the
487 // count of the same timestamp or position is reported by the HAL continuously, the values from
488 // the HAL will no longer be trusted.
489 static constexpr int kMaxFrozenCount = 20;
490 // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
491 // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
492 // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
493 // position is a valid one. Do a simple validation, which is checking if the position is
494 // forward within half a second or not, here so that this function can return error if
495 // the validation fails. Note that we don't only apply this validation logic to HAL API
496 // less than 7.0. The reason is that there is a chance the HAL is not reporting the
497 // timestamp and position correctly.
498 if (mLastPositionFrames > tempPositionFrames) {
499 // If the position is going backwards, there must be something wrong with the HAL.
500 // In that case, we do not trust the values reported by the HAL.
501 ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
502 __func__, mLastPositionFrames, tempPositionFrames);
503 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
504 return mHalExternalPositionStatus;
505 } else if (mLastPositionFrames == tempPositionFrames) {
506 if (tempTimeNanos - mTimestampNanosForLastPosition >
507 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
508 ALOGW("%s, the reported position is not changed within %d msec. "
509 "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
510 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
511 return mHalExternalPositionStatus;
512 }
513 mFrozenPositionCount++;
514 } else {
515 mFrozenPositionCount = 0;
516 }
517
518 if (mTimestampNanosForLastPosition > tempTimeNanos) {
519 // If the timestamp is going backwards, there must be something wrong with the HAL.
520 // In that case, we do not trust the values reported by the HAL.
521 ALOGW("%s timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
522 __func__, mTimestampNanosForLastPosition, tempTimeNanos);
523 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
524 return mHalExternalPositionStatus;
525 } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
526 mFrozenTimestampCount++;
527 } else {
528 mFrozenTimestampCount = 0;
529 }
530
531 if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
532 ALOGW("%s too many frozen external position from HAL.", __func__);
533 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
534 return mHalExternalPositionStatus;
535 }
536
537 mLastPositionFrames = tempPositionFrames;
538 mTimestampNanosForLastPosition = tempTimeNanos;
539
540 // Only update the timestamp and position when they looks valid.
541 *positionFrames = tempPositionFrames;
542 *timeNanos = tempTimeNanos;
543 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700544}
jiabinf7f06152021-11-22 18:10:14 +0000545
jiabinfc791ee2023-02-15 19:43:40 +0000546aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer()
jiabinf7f06152021-11-22 18:10:14 +0000547{
548 memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
549 int32_t minSizeFrames = getBufferCapacity();
550 if (minSizeFrames <= 0) { // zero will get rejected
551 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
552 }
jiabin613e6ae2022-12-21 20:20:11 +0000553 const status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
554 const bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
jiabinf7f06152021-11-22 18:10:14 +0000555 if (status != OK) {
556 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
557 __func__, status, strerror(-status));
558 return AAUDIO_ERROR_UNAVAILABLE;
559 } else {
560 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
561 ", Sharable FD: %s",
562 __func__,
563 mMmapBufferinfo.buffer_size_frames,
564 mMmapBufferinfo.burst_size_frames,
565 isBufferShareable ? "Yes" : "No");
566 }
567
568 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
569 if (!isBufferShareable) {
570 // Exclusive mode can only be used by the service because the FD cannot be shared.
jiabin613e6ae2022-12-21 20:20:11 +0000571 const int32_t audioServiceUid =
jiabinf7f06152021-11-22 18:10:14 +0000572 VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
573 if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
574 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
575 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
576 return AAUDIO_ERROR_UNAVAILABLE;
577 }
578 }
579
580 // AAudio creates a copy of this FD and retains ownership of the copy.
581 // Assume that AudioFlinger will close the original shared_memory_fd.
jiabinfc791ee2023-02-15 19:43:40 +0000582
583 mAudioDataWrapper->getDataFileDescriptor().reset(dup(mMmapBufferinfo.shared_memory_fd));
584 if (mAudioDataWrapper->getDataFileDescriptor().get() == -1) {
jiabinf7f06152021-11-22 18:10:14 +0000585 ALOGE("%s() - could not dup shared_memory_fd", __func__);
586 return AAUDIO_ERROR_INTERNAL;
587 }
588
589 // Call to HAL to make sure the transport FD was able to be closed by binder.
590 // This is a tricky workaround for a problem in Binder.
591 // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
592 struct audio_mmap_position position;
593 mMmapStream->getMmapPosition(&position);
594
595 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
596
597 return AAUDIO_OK;
598}
jiabinfc791ee2023-02-15 19:43:40 +0000599
600int64_t AAudioServiceEndpointMMAP::nextDataReportTime() {
601 return getDirection() == AAUDIO_DIRECTION_OUTPUT
602 ? AudioClock::getNanoseconds() + mDataReportOffsetNanos
603 : std::numeric_limits<int64_t>::max();
604}
605
606void AAudioServiceEndpointMMAP::reportData() {
607 if (mMmapStream == nullptr) {
608 // This must not happen
609 ALOGE("%s() invalid state, mmap stream is not initialized", __func__);
610 return;
611 }
612 auto fifo = mAudioDataWrapper->getFifoBuffer();
613 if (fifo == nullptr) {
614 ALOGE("%s() fifo buffer is not initialized, cannot report data", __func__);
615 return;
616 }
617
618 WrappingBuffer wrappingBuffer;
619 fifo_frames_t framesAvailable = fifo->getFullDataAvailable(&wrappingBuffer);
620 for (size_t i = 0; i < WrappingBuffer::SIZE; ++i) {
621 if (wrappingBuffer.numFrames[i] > 0) {
622 mMmapStream->reportData(wrappingBuffer.data[i], wrappingBuffer.numFrames[i]);
623 }
624 }
625 fifo->advanceReadIndex(framesAvailable);
626}