blob: 133b9b460a1edb24c8e59d30ab0ad2941e47c2a9 [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 Burk39f02dd2017-08-04 09:13:31 -070040#define AAUDIO_BUFFER_CAPACITY_MIN 4 * 512
41#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;
61 result << ", audio data FD = " << mAudioDataFileDescriptor;
62 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
88}
89
Phil Burk39f02dd2017-08-04 09:13:31 -070090aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
91 aaudio_result_t result = AAUDIO_OK;
Phil Burk39f02dd2017-08-04 09:13:31 -070092 copyFrom(request.getConstantConfiguration());
Svet Ganov33761132021-05-13 22:51:08 +000093 mMmapClient.attributionSource = request.getAttributionSource();
94 // TODO b/182392769: use attribution source util
95 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070096 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +000097 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070098 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Phil Burk39f02dd2017-08-04 09:13:31 -070099
Phil Burk04e805b2018-03-27 09:13:53 -0700100 audio_format_t audioFormat = getFormat();
jiabinf1c73972022-04-14 16:28:52 -0700101 std::set<audio_format_t> formatsTried;
102 while (true) {
103 if (formatsTried.find(audioFormat) != formatsTried.end()) {
104 // APM returning something that has already tried.
105 ALOGW("Have already tried to open #x, but failed before");
106 break;
107 }
108 formatsTried.insert(audioFormat);
Phil Burk04e805b2018-03-27 09:13:53 -0700109
jiabinf1c73972022-04-14 16:28:52 -0700110 audio_format_t nextFormatToTry = AUDIO_FORMAT_DEFAULT;
111 result = openWithFormat(audioFormat, &nextFormatToTry);
112 if (result == AAUDIO_OK || result != AAUDIO_ERROR_UNAVAILABLE) {
113 // Return if it is successful or there is an error that is not
114 // AAUDIO_ERROR_UNAVAILABLE happens.
115 ALOGI("Opened format=%#x with result=%d", audioFormat, result);
116 break;
117 }
Phil Burk04e805b2018-03-27 09:13:53 -0700118
jiabinf1c73972022-04-14 16:28:52 -0700119 nextFormatToTry = getNextFormatToTry(audioFormat, nextFormatToTry);
120 ALOGD("%s() %#x failed, perhaps due to format. Try again with %#x",
121 __func__, audioFormat, nextFormatToTry);
122 audioFormat = nextFormatToTry;
123 if (audioFormat == AUDIO_FORMAT_DEFAULT) {
124 // Nothing else to try
125 break;
126 }
Phil Burk04e805b2018-03-27 09:13:53 -0700127 }
128 return result;
129}
130
jiabinf1c73972022-04-14 16:28:52 -0700131aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(
132 audio_format_t audioFormat, audio_format_t* nextFormatToTry) {
Phil Burk04e805b2018-03-27 09:13:53 -0700133 aaudio_result_t result = AAUDIO_OK;
134 audio_config_base_t config;
135 audio_port_handle_t deviceId;
136
137 const audio_attributes_t attributes = getAudioAttributesFrom(this);
138
Phil Burk39f02dd2017-08-04 09:13:31 -0700139 mRequestedDeviceId = deviceId = getDeviceId();
140
141 // Fill in config
Phil Burk0127c1b2018-03-29 13:48:06 -0700142 config.format = audioFormat;
Phil Burk39f02dd2017-08-04 09:13:31 -0700143
144 int32_t aaudioSampleRate = getSampleRate();
145 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
146 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
147 }
148 config.sample_rate = aaudioSampleRate;
149
jiabind1f1cb62020-03-24 11:57:57 -0700150 const aaudio_direction_t direction = getDirection();
151
jiabina9094092021-06-28 20:36:45 +0000152 config.channel_mask = AAudio_getChannelMaskForOpen(
153 getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
154
Phil Burk39f02dd2017-08-04 09:13:31 -0700155 if (direction == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700156 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
157
158 } else if (direction == AAUDIO_DIRECTION_INPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700159 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
160
161 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700162 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700163 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
164 }
165
166 MmapStreamInterface::stream_direction_t streamDirection =
167 (direction == AAUDIO_DIRECTION_OUTPUT)
168 ? MmapStreamInterface::DIRECTION_OUTPUT
169 : MmapStreamInterface::DIRECTION_INPUT;
170
Phil Burk4e1af9f2018-01-03 15:54:35 -0800171 aaudio_session_id_t requestedSessionId = getSessionId();
172 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
173
Phil Burk39f02dd2017-08-04 09:13:31 -0700174 // Open HAL stream. Set mMmapStream
jiabinf1c73972022-04-14 16:28:52 -0700175 ALOGD("%s trying to open MMAP stream with format=%#x, sample_rate=%u, channel_mask=%#x",
176 __func__, config.format, config.sample_rate, config.channel_mask);
Phil Burk39f02dd2017-08-04 09:13:31 -0700177 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
178 &attributes,
179 &config,
180 mMmapClient,
181 &deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800182 &sessionId,
Phil Burk39f02dd2017-08-04 09:13:31 -0700183 this, // callback
184 mMmapStream,
185 &mPortHandle);
Svet Ganov33761132021-05-13 22:51:08 +0000186 ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
187 __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700188 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700189 // This can happen if the resource is busy or the config does
190 // not match the hardware.
jiabinf1c73972022-04-14 16:28:52 -0700191 ALOGD("%s() - openMmapStream() returned status=%d, suggested format=%#x, sample_rate=%u, "
192 "channel_mask=%#x",
193 __func__, status, config.format, config.sample_rate, config.format);
194 *nextFormatToTry = config.format != audioFormat ? config.format
195 : *nextFormatToTry;
Phil Burk39f02dd2017-08-04 09:13:31 -0700196 return AAUDIO_ERROR_UNAVAILABLE;
197 }
198
199 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700200 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700201 }
202 setDeviceId(deviceId);
203
Phil Burk4e1af9f2018-01-03 15:54:35 -0800204 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700205 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800206 }
207
208 aaudio_session_id_t actualSessionId =
209 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
210 ? AAUDIO_SESSION_ID_NONE
211 : (aaudio_session_id_t) sessionId;
212 setSessionId(actualSessionId);
Phil Burked782c82022-02-08 21:43:53 +0000213
214 ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
215 __func__, audioFormat, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800216
Phil Burk39f02dd2017-08-04 09:13:31 -0700217 // Create MMAP/NOIRQ buffer.
millerliang18d1e6c2022-02-08 15:43:40 +0800218 result = createMmapBuffer(&mAudioDataFileDescriptor);
219 if (result != AAUDIO_OK) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700220 goto error;
Phil Burk39f02dd2017-08-04 09:13:31 -0700221 }
222
223 // Get information about the stream and pass it back to the caller.
jiabina9094092021-06-28 20:36:45 +0000224 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
225 config.channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
226 AAudio_isChannelIndexMask(config.channel_mask)));
Phil Burk39f02dd2017-08-04 09:13:31 -0700227
Phil Burk0127c1b2018-03-29 13:48:06 -0700228 setFormat(config.format);
Phil Burk39f02dd2017-08-04 09:13:31 -0700229 setSampleRate(config.sample_rate);
230
jiabina5df87b2020-12-29 10:45:19 -0800231 // If the position is not updated while the timestamp is updated for more than a certain amount,
232 // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
233 // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
234 // that is too short.
235 static constexpr int kTimestampGraceBurstCount = 5;
236 mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
237 * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
238
Phil Burked782c82022-02-08 21:43:53 +0000239 ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
jiabina9094092021-06-28 20:36:45 +0000240 __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
241 deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700242
Phil Burked782c82022-02-08 21:43:53 +0000243 ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
244 __func__, getFormat(), audio_format_to_string(getFormat()),
245 calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700246
Phil Burk39f02dd2017-08-04 09:13:31 -0700247 return result;
248
249error:
250 close();
251 return result;
252}
253
Phil Burk320910f2020-08-12 14:29:10 +0000254void AAudioServiceEndpointMMAP::close() {
Phil Burk6e463ce2020-04-13 10:20:20 -0700255 if (mMmapStream != nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700256 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
257 mMmapStream.clear();
Phil Burk39f02dd2017-08-04 09:13:31 -0700258 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
259 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700260}
261
262aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700263 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700264 // Start the client on behalf of the AAudio service.
265 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700266 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700267 audio_attributes_t attr = {};
268 if (stream != nullptr) {
269 attr = getAudioAttributesFrom(stream.get());
270 }
271 aaudio_result_t result = startClient(
272 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700273 // When AudioFlinger is passed a valid port handle then it should not change it.
274 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
275 "%s() port handle not expected to change from %d to %d",
276 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700277 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700278 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700279}
280
281aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700282 audio_port_handle_t clientHandle __unused) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700283 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700284
285 // Round 64-bit counter up to a multiple of the buffer capacity.
286 // This is required because the 64-bit counter is used as an index
287 // into a circular buffer and the actual HW position is reset to zero
288 // when the stream is stopped.
289 mFramesTransferred.roundUp64(getBufferCapacity());
290
Phil Burkbbd52862018-04-13 11:37:42 -0700291 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700292 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700293 return stopClient(mPortHandle);
294}
295
296aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700297 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700298 audio_port_handle_t *clientHandle) {
299 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
jiabind1f1cb62020-03-24 11:57:57 -0700300 status_t status = mMmapStream->start(client, attr, clientHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700301 return AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700302}
303
304aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
305 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
306 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700307 return result;
308}
309
jiabinf7f06152021-11-22 18:10:14 +0000310aaudio_result_t AAudioServiceEndpointMMAP::standby() {
311 if (mMmapStream == nullptr) {
312 return AAUDIO_ERROR_NULL;
313 }
314 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->standby());
315 return result;
316}
317
318aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
319 if (mMmapStream == nullptr) {
320 return AAUDIO_ERROR_NULL;
321 }
322 mAudioDataFileDescriptor.reset();
323 aaudio_result_t result = createMmapBuffer(&mAudioDataFileDescriptor);
324 if (result == AAUDIO_OK) {
325 int32_t bytesPerFrame = calculateBytesPerFrame();
326 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
327 int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
328 parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
329 parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
330 parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
331 parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
332 }
333 return result;
334}
335
Phil Burk39f02dd2017-08-04 09:13:31 -0700336// Get free-running DSP or DMA hardware position from the HAL.
337aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
338 int64_t *timeNanos) {
339 struct audio_mmap_position position;
340 if (mMmapStream == nullptr) {
341 return AAUDIO_ERROR_NULL;
342 }
343 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700344 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
345 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
Phil Burk39f02dd2017-08-04 09:13:31 -0700346 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
347 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700348 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700349 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700350 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700351 } else {
352 // Convert 32-bit position to 64-bit position.
353 mFramesTransferred.update32(position.position_frames);
354 *positionFrames = mFramesTransferred.get();
355 *timeNanos = position.time_nanoseconds;
356 }
357 return result;
358}
359
360aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
361 int64_t *timeNanos) {
362 return 0; // TODO
363}
364
Phil Burka77869d2020-05-07 10:39:47 -0700365// This is called by onTearDown() in a separate thread to avoid deadlocks.
366void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
Phil Burkbbd52862018-04-13 11:37:42 -0700367 // Are we tearing down the EXCLUSIVE MMAP stream?
368 if (isStreamRegistered(portHandle)) {
369 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
370 disconnectRegisteredStreams();
371 } else {
372 // Must be a SHARED stream?
373 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
374 aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
375 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
376 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700377};
378
Phil Burka77869d2020-05-07 10:39:47 -0700379// This is called by AudioFlinger when it wants to destroy a stream.
380void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
381 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
Phil Burk3d201942021-04-08 23:27:04 +0000382 android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
383 std::thread asyncTask([holdEndpoint, portHandle]() {
384 holdEndpoint->handleTearDownAsync(portHandle);
385 });
Phil Burka77869d2020-05-07 10:39:47 -0700386 asyncTask.detach();
387}
388
Robert Wu4389ae62022-02-17 18:39:41 +0000389void AAudioServiceEndpointMMAP::onVolumeChanged(float volume) {
390 ALOGD("%s() volume = %f", __func__, volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700391 std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800392 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700393 stream->onVolumeChanged(volume);
394 }
395};
396
Phil Burka77869d2020-05-07 10:39:47 -0700397void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
398 const int32_t deviceId = static_cast<int32_t>(portHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700399 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burka77869d2020-05-07 10:39:47 -0700400 if (getDeviceId() != deviceId) {
401 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
Phil Burk3d201942021-04-08 23:27:04 +0000402 android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
403 std::thread asyncTask([holdEndpoint, deviceId]() {
404 ALOGD("onRoutingChanged() asyncTask launched");
405 holdEndpoint->disconnectRegisteredStreams();
406 holdEndpoint->setDeviceId(deviceId);
Phil Burka77869d2020-05-07 10:39:47 -0700407 });
408 asyncTask.detach();
409 } else {
410 setDeviceId(deviceId);
411 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700412 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700413};
414
415/**
416 * Get an immutable description of the data queue from the HAL.
417 */
jiabin2a594622021-10-14 00:32:25 +0000418aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
419 AudioEndpointParcelable* parcelable)
Phil Burk39f02dd2017-08-04 09:13:31 -0700420{
421 // Gather information on the data queue based on HAL info.
422 int32_t bytesPerFrame = calculateBytesPerFrame();
423 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
jiabin2a594622021-10-14 00:32:25 +0000424 int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
425 parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
426 parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
427 parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
428 parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700429 return AAUDIO_OK;
430}
jiabinb7d8c5a2020-08-26 17:24:52 -0700431
432aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
433 int64_t *timeNanos)
434{
jiabina5df87b2020-12-29 10:45:19 -0800435 if (mHalExternalPositionStatus != AAUDIO_OK) {
436 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700437 }
jiabina5df87b2020-12-29 10:45:19 -0800438 uint64_t tempPositionFrames;
439 int64_t tempTimeNanos;
440 status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
441 if (status != OK) {
442 // getExternalPosition reports error. The HAL may not support the API. Cache the result
jiabinb7d8c5a2020-08-26 17:24:52 -0700443 // so that the call will not go to the HAL next time.
jiabina5df87b2020-12-29 10:45:19 -0800444 mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
445 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700446 }
jiabina5df87b2020-12-29 10:45:19 -0800447
448 // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
449 // to report correct external position. In that case, we will not trust the values reported from
450 // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
451 // correct position within a period. But it may not be a good idea to get system time too often.
452 // In that case, a maximum number of frozen external position is defined so that if the
453 // count of the same timestamp or position is reported by the HAL continuously, the values from
454 // the HAL will no longer be trusted.
455 static constexpr int kMaxFrozenCount = 20;
456 // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
457 // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
458 // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
459 // position is a valid one. Do a simple validation, which is checking if the position is
460 // forward within half a second or not, here so that this function can return error if
461 // the validation fails. Note that we don't only apply this validation logic to HAL API
462 // less than 7.0. The reason is that there is a chance the HAL is not reporting the
463 // timestamp and position correctly.
464 if (mLastPositionFrames > tempPositionFrames) {
465 // If the position is going backwards, there must be something wrong with the HAL.
466 // In that case, we do not trust the values reported by the HAL.
467 ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
468 __func__, mLastPositionFrames, tempPositionFrames);
469 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
470 return mHalExternalPositionStatus;
471 } else if (mLastPositionFrames == tempPositionFrames) {
472 if (tempTimeNanos - mTimestampNanosForLastPosition >
473 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
474 ALOGW("%s, the reported position is not changed within %d msec. "
475 "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
476 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
477 return mHalExternalPositionStatus;
478 }
479 mFrozenPositionCount++;
480 } else {
481 mFrozenPositionCount = 0;
482 }
483
484 if (mTimestampNanosForLastPosition > tempTimeNanos) {
485 // If the timestamp is going backwards, there must be something wrong with the HAL.
486 // In that case, we do not trust the values reported by the HAL.
487 ALOGW("%s timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
488 __func__, mTimestampNanosForLastPosition, tempTimeNanos);
489 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
490 return mHalExternalPositionStatus;
491 } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
492 mFrozenTimestampCount++;
493 } else {
494 mFrozenTimestampCount = 0;
495 }
496
497 if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
498 ALOGW("%s too many frozen external position from HAL.", __func__);
499 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
500 return mHalExternalPositionStatus;
501 }
502
503 mLastPositionFrames = tempPositionFrames;
504 mTimestampNanosForLastPosition = tempTimeNanos;
505
506 // Only update the timestamp and position when they looks valid.
507 *positionFrames = tempPositionFrames;
508 *timeNanos = tempTimeNanos;
509 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700510}
jiabinf7f06152021-11-22 18:10:14 +0000511
512aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer(
513 android::base::unique_fd* fileDescriptor)
514{
515 memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
516 int32_t minSizeFrames = getBufferCapacity();
517 if (minSizeFrames <= 0) { // zero will get rejected
518 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
519 }
520 status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
521 bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
522 if (status != OK) {
523 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
524 __func__, status, strerror(-status));
525 return AAUDIO_ERROR_UNAVAILABLE;
526 } else {
527 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
528 ", Sharable FD: %s",
529 __func__,
530 mMmapBufferinfo.buffer_size_frames,
531 mMmapBufferinfo.burst_size_frames,
532 isBufferShareable ? "Yes" : "No");
533 }
534
535 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
536 if (!isBufferShareable) {
537 // Exclusive mode can only be used by the service because the FD cannot be shared.
538 int32_t audioServiceUid =
539 VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
540 if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
541 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
542 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
543 return AAUDIO_ERROR_UNAVAILABLE;
544 }
545 }
546
547 // AAudio creates a copy of this FD and retains ownership of the copy.
548 // Assume that AudioFlinger will close the original shared_memory_fd.
549 fileDescriptor->reset(dup(mMmapBufferinfo.shared_memory_fd));
550 if (fileDescriptor->get() == -1) {
551 ALOGE("%s() - could not dup shared_memory_fd", __func__);
552 return AAUDIO_ERROR_INTERNAL;
553 }
554
555 // Call to HAL to make sure the transport FD was able to be closed by binder.
556 // This is a tricky workaround for a problem in Binder.
557 // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
558 struct audio_mmap_position position;
559 mMmapStream->getMmapPosition(&position);
560
561 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
562
563 return AAUDIO_OK;
564}