blob: 3f18b958a4d1592a501fea59b5501a669c177858 [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>
25#include <sstream>
Phil Burka77869d2020-05-07 10:39:47 -070026#include <thread>
Phil Burk39f02dd2017-08-04 09:13:31 -070027#include <utils/Singleton.h>
28#include <vector>
29
Phil Burk39f02dd2017-08-04 09:13:31 -070030#include "AAudioEndpointManager.h"
31#include "AAudioServiceEndpoint.h"
32
33#include "core/AudioStreamBuilder.h"
34#include "AAudioServiceEndpoint.h"
35#include "AAudioServiceStreamShared.h"
36#include "AAudioServiceEndpointPlay.h"
37#include "AAudioServiceEndpointMMAP.h"
38
Phil Burk39f02dd2017-08-04 09:13:31 -070039#define AAUDIO_BUFFER_CAPACITY_MIN 4 * 512
40#define AAUDIO_SAMPLE_RATE_DEFAULT 48000
41
42// This is an estimate of the time difference between the HW and the MMAP time.
43// TODO Get presentation timestamps from the HAL instead of using these estimates.
44#define OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (3 * AAUDIO_NANOS_PER_MILLISECOND)
45#define INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (-1 * AAUDIO_NANOS_PER_MILLISECOND)
46
47using namespace android; // TODO just import names needed
48using namespace aaudio; // TODO just import names needed
49
Phil Burkbbd52862018-04-13 11:37:42 -070050AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
51 : mMmapStream(nullptr)
52 , mAAudioService(audioService) {}
Phil Burk39f02dd2017-08-04 09:13:31 -070053
Phil Burk39f02dd2017-08-04 09:13:31 -070054std::string AAudioServiceEndpointMMAP::dump() const {
55 std::stringstream result;
56
57 result << " MMAP: framesTransferred = " << mFramesTransferred.get();
58 result << ", HW nanos = " << mHardwareTimeOffsetNanos;
59 result << ", port handle = " << mPortHandle;
60 result << ", audio data FD = " << mAudioDataFileDescriptor;
61 result << "\n";
62
63 result << " HW Offset Micros: " <<
64 (getHardwareTimeOffsetNanos()
65 / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
66
67 result << AAudioServiceEndpoint::dump();
68 return result.str();
69}
70
71aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
72 aaudio_result_t result = AAUDIO_OK;
Phil Burk39f02dd2017-08-04 09:13:31 -070073 copyFrom(request.getConstantConfiguration());
Svet Ganov33761132021-05-13 22:51:08 +000074 mMmapClient.attributionSource = request.getAttributionSource();
75 // TODO b/182392769: use attribution source util
76 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070077 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +000078 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070079 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Phil Burk39f02dd2017-08-04 09:13:31 -070080
Phil Burk04e805b2018-03-27 09:13:53 -070081 audio_format_t audioFormat = getFormat();
82
Phil Burk04e805b2018-03-27 09:13:53 -070083 result = openWithFormat(audioFormat);
84 if (result == AAUDIO_OK) return result;
85
millerliang8eebeba2021-11-03 21:45:58 +080086 if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_FLOAT) {
87 ALOGD("%s() FLOAT failed, perhaps due to format. Try again with 32_BIT", __func__);
88 audioFormat = AUDIO_FORMAT_PCM_32_BIT;
89 result = openWithFormat(audioFormat);
90 }
91 if (result == AAUDIO_OK) return result;
92
millerlianga75a83f2021-04-30 17:43:00 +080093 if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_32_BIT) {
94 ALOGD("%s() 32_BIT failed, perhaps due to format. Try again with 24_BIT_PACKED", __func__);
95 audioFormat = AUDIO_FORMAT_PCM_24_BIT_PACKED;
96 result = openWithFormat(audioFormat);
97 }
98 if (result == AAUDIO_OK) return result;
99
Phil Burk04e805b2018-03-27 09:13:53 -0700100 // TODO The HAL and AudioFlinger should be recommending a format if the open fails.
101 // But that recommendation is not propagating back from the HAL.
102 // So for now just try something very likely to work.
103 if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
104 ALOGD("%s() 24_BIT failed, perhaps due to format. Try again with 16_BIT", __func__);
105 audioFormat = AUDIO_FORMAT_PCM_16_BIT;
106 result = openWithFormat(audioFormat);
107 }
108 return result;
109}
110
111aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(audio_format_t audioFormat) {
112 aaudio_result_t result = AAUDIO_OK;
113 audio_config_base_t config;
114 audio_port_handle_t deviceId;
115
116 const audio_attributes_t attributes = getAudioAttributesFrom(this);
117
Phil Burk39f02dd2017-08-04 09:13:31 -0700118 mRequestedDeviceId = deviceId = getDeviceId();
119
120 // Fill in config
Phil Burk0127c1b2018-03-29 13:48:06 -0700121 config.format = audioFormat;
Phil Burk39f02dd2017-08-04 09:13:31 -0700122
123 int32_t aaudioSampleRate = getSampleRate();
124 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
125 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
126 }
127 config.sample_rate = aaudioSampleRate;
128
jiabind1f1cb62020-03-24 11:57:57 -0700129 const aaudio_direction_t direction = getDirection();
130
jiabina9094092021-06-28 20:36:45 +0000131 config.channel_mask = AAudio_getChannelMaskForOpen(
132 getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
133
Phil Burk39f02dd2017-08-04 09:13:31 -0700134 if (direction == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700135 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
136
137 } else if (direction == AAUDIO_DIRECTION_INPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700138 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
139
140 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700141 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700142 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
143 }
144
145 MmapStreamInterface::stream_direction_t streamDirection =
146 (direction == AAUDIO_DIRECTION_OUTPUT)
147 ? MmapStreamInterface::DIRECTION_OUTPUT
148 : MmapStreamInterface::DIRECTION_INPUT;
149
Phil Burk4e1af9f2018-01-03 15:54:35 -0800150 aaudio_session_id_t requestedSessionId = getSessionId();
151 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
152
Phil Burk39f02dd2017-08-04 09:13:31 -0700153 // Open HAL stream. Set mMmapStream
154 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
155 &attributes,
156 &config,
157 mMmapClient,
158 &deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800159 &sessionId,
Phil Burk39f02dd2017-08-04 09:13:31 -0700160 this, // callback
161 mMmapStream,
162 &mPortHandle);
Svet Ganov33761132021-05-13 22:51:08 +0000163 ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
164 __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700165 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700166 // This can happen if the resource is busy or the config does
167 // not match the hardware.
168 ALOGD("%s() - openMmapStream() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700169 return AAUDIO_ERROR_UNAVAILABLE;
170 }
171
172 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700173 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700174 }
175 setDeviceId(deviceId);
176
Phil Burk4e1af9f2018-01-03 15:54:35 -0800177 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700178 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800179 }
180
181 aaudio_session_id_t actualSessionId =
182 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
183 ? AAUDIO_SESSION_ID_NONE
184 : (aaudio_session_id_t) sessionId;
185 setSessionId(actualSessionId);
Phil Burked782c82022-02-08 21:43:53 +0000186
187 ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
188 __func__, audioFormat, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800189
Phil Burk39f02dd2017-08-04 09:13:31 -0700190 // Create MMAP/NOIRQ buffer.
millerliang18d1e6c2022-02-08 15:43:40 +0800191 result = createMmapBuffer(&mAudioDataFileDescriptor);
192 if (result != AAUDIO_OK) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700193 goto error;
Phil Burk39f02dd2017-08-04 09:13:31 -0700194 }
195
196 // Get information about the stream and pass it back to the caller.
jiabina9094092021-06-28 20:36:45 +0000197 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
198 config.channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
199 AAudio_isChannelIndexMask(config.channel_mask)));
Phil Burk39f02dd2017-08-04 09:13:31 -0700200
Phil Burk0127c1b2018-03-29 13:48:06 -0700201 setFormat(config.format);
Phil Burk39f02dd2017-08-04 09:13:31 -0700202 setSampleRate(config.sample_rate);
203
jiabina5df87b2020-12-29 10:45:19 -0800204 // If the position is not updated while the timestamp is updated for more than a certain amount,
205 // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
206 // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
207 // that is too short.
208 static constexpr int kTimestampGraceBurstCount = 5;
209 mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
210 * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
211
Phil Burked782c82022-02-08 21:43:53 +0000212 ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
jiabina9094092021-06-28 20:36:45 +0000213 __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
214 deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700215
Phil Burked782c82022-02-08 21:43:53 +0000216 ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
217 __func__, getFormat(), audio_format_to_string(getFormat()),
218 calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700219
Phil Burk39f02dd2017-08-04 09:13:31 -0700220 return result;
221
222error:
223 close();
224 return result;
225}
226
Phil Burk320910f2020-08-12 14:29:10 +0000227void AAudioServiceEndpointMMAP::close() {
Phil Burk6e463ce2020-04-13 10:20:20 -0700228 if (mMmapStream != nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700229 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
230 mMmapStream.clear();
231 // Apparently the above close is asynchronous. An attempt to open a new device
232 // right after a close can fail. Also some callbacks may still be in flight!
233 // FIXME Make closing synchronous.
234 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
235 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700236}
237
238aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700239 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700240 // Start the client on behalf of the AAudio service.
241 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700242 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700243 audio_attributes_t attr = {};
244 if (stream != nullptr) {
245 attr = getAudioAttributesFrom(stream.get());
246 }
247 aaudio_result_t result = startClient(
248 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700249 // When AudioFlinger is passed a valid port handle then it should not change it.
250 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
251 "%s() port handle not expected to change from %d to %d",
252 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700253 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700254 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700255}
256
257aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700258 audio_port_handle_t clientHandle __unused) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700259 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700260
261 // Round 64-bit counter up to a multiple of the buffer capacity.
262 // This is required because the 64-bit counter is used as an index
263 // into a circular buffer and the actual HW position is reset to zero
264 // when the stream is stopped.
265 mFramesTransferred.roundUp64(getBufferCapacity());
266
Phil Burkbbd52862018-04-13 11:37:42 -0700267 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700268 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700269 return stopClient(mPortHandle);
270}
271
272aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700273 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700274 audio_port_handle_t *clientHandle) {
275 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
jiabind1f1cb62020-03-24 11:57:57 -0700276 status_t status = mMmapStream->start(client, attr, clientHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700277 return AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700278}
279
280aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
281 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
282 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700283 return result;
284}
285
jiabinf7f06152021-11-22 18:10:14 +0000286aaudio_result_t AAudioServiceEndpointMMAP::standby() {
287 if (mMmapStream == nullptr) {
288 return AAUDIO_ERROR_NULL;
289 }
290 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->standby());
291 return result;
292}
293
294aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
295 if (mMmapStream == nullptr) {
296 return AAUDIO_ERROR_NULL;
297 }
298 mAudioDataFileDescriptor.reset();
299 aaudio_result_t result = createMmapBuffer(&mAudioDataFileDescriptor);
300 if (result == AAUDIO_OK) {
301 int32_t bytesPerFrame = calculateBytesPerFrame();
302 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
303 int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
304 parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
305 parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
306 parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
307 parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
308 }
309 return result;
310}
311
Phil Burk39f02dd2017-08-04 09:13:31 -0700312// Get free-running DSP or DMA hardware position from the HAL.
313aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
314 int64_t *timeNanos) {
315 struct audio_mmap_position position;
316 if (mMmapStream == nullptr) {
317 return AAUDIO_ERROR_NULL;
318 }
319 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700320 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
321 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
Phil Burk39f02dd2017-08-04 09:13:31 -0700322 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
323 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700324 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700325 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700326 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700327 } else {
328 // Convert 32-bit position to 64-bit position.
329 mFramesTransferred.update32(position.position_frames);
330 *positionFrames = mFramesTransferred.get();
331 *timeNanos = position.time_nanoseconds;
332 }
333 return result;
334}
335
336aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
337 int64_t *timeNanos) {
338 return 0; // TODO
339}
340
Phil Burka77869d2020-05-07 10:39:47 -0700341// This is called by onTearDown() in a separate thread to avoid deadlocks.
342void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
Phil Burkbbd52862018-04-13 11:37:42 -0700343 // Are we tearing down the EXCLUSIVE MMAP stream?
344 if (isStreamRegistered(portHandle)) {
345 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
346 disconnectRegisteredStreams();
347 } else {
348 // Must be a SHARED stream?
349 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
350 aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
351 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
352 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700353};
354
Phil Burka77869d2020-05-07 10:39:47 -0700355// This is called by AudioFlinger when it wants to destroy a stream.
356void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
357 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
Phil Burk3d201942021-04-08 23:27:04 +0000358 android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
359 std::thread asyncTask([holdEndpoint, portHandle]() {
360 holdEndpoint->handleTearDownAsync(portHandle);
361 });
Phil Burka77869d2020-05-07 10:39:47 -0700362 asyncTask.detach();
363}
364
Phil Burk39f02dd2017-08-04 09:13:31 -0700365void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
366 android::Vector<float> values) {
Phil Burk19e990e2018-03-22 13:59:34 -0700367 // TODO Do we really need a different volume for each channel?
368 // We get called with an array filled with a single value!
Phil Burk39f02dd2017-08-04 09:13:31 -0700369 float volume = values[0];
Phil Burk29ccc292019-04-15 08:58:08 -0700370 ALOGD("%s() volume[0] = %f", __func__, volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700371 std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800372 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700373 stream->onVolumeChanged(volume);
374 }
375};
376
Phil Burka77869d2020-05-07 10:39:47 -0700377void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
378 const int32_t deviceId = static_cast<int32_t>(portHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700379 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burka77869d2020-05-07 10:39:47 -0700380 if (getDeviceId() != deviceId) {
381 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
Phil Burk3d201942021-04-08 23:27:04 +0000382 android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
383 std::thread asyncTask([holdEndpoint, deviceId]() {
384 ALOGD("onRoutingChanged() asyncTask launched");
385 holdEndpoint->disconnectRegisteredStreams();
386 holdEndpoint->setDeviceId(deviceId);
Phil Burka77869d2020-05-07 10:39:47 -0700387 });
388 asyncTask.detach();
389 } else {
390 setDeviceId(deviceId);
391 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700392 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700393};
394
395/**
396 * Get an immutable description of the data queue from the HAL.
397 */
jiabin2a594622021-10-14 00:32:25 +0000398aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
399 AudioEndpointParcelable* parcelable)
Phil Burk39f02dd2017-08-04 09:13:31 -0700400{
401 // Gather information on the data queue based on HAL info.
402 int32_t bytesPerFrame = calculateBytesPerFrame();
403 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
jiabin2a594622021-10-14 00:32:25 +0000404 int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
405 parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
406 parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
407 parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
408 parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700409 return AAUDIO_OK;
410}
jiabinb7d8c5a2020-08-26 17:24:52 -0700411
412aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
413 int64_t *timeNanos)
414{
jiabina5df87b2020-12-29 10:45:19 -0800415 if (mHalExternalPositionStatus != AAUDIO_OK) {
416 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700417 }
jiabina5df87b2020-12-29 10:45:19 -0800418 uint64_t tempPositionFrames;
419 int64_t tempTimeNanos;
420 status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
421 if (status != OK) {
422 // getExternalPosition reports error. The HAL may not support the API. Cache the result
jiabinb7d8c5a2020-08-26 17:24:52 -0700423 // so that the call will not go to the HAL next time.
jiabina5df87b2020-12-29 10:45:19 -0800424 mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
425 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700426 }
jiabina5df87b2020-12-29 10:45:19 -0800427
428 // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
429 // to report correct external position. In that case, we will not trust the values reported from
430 // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
431 // correct position within a period. But it may not be a good idea to get system time too often.
432 // In that case, a maximum number of frozen external position is defined so that if the
433 // count of the same timestamp or position is reported by the HAL continuously, the values from
434 // the HAL will no longer be trusted.
435 static constexpr int kMaxFrozenCount = 20;
436 // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
437 // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
438 // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
439 // position is a valid one. Do a simple validation, which is checking if the position is
440 // forward within half a second or not, here so that this function can return error if
441 // the validation fails. Note that we don't only apply this validation logic to HAL API
442 // less than 7.0. The reason is that there is a chance the HAL is not reporting the
443 // timestamp and position correctly.
444 if (mLastPositionFrames > tempPositionFrames) {
445 // If the position is going backwards, there must be something wrong with the HAL.
446 // In that case, we do not trust the values reported by the HAL.
447 ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
448 __func__, mLastPositionFrames, tempPositionFrames);
449 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
450 return mHalExternalPositionStatus;
451 } else if (mLastPositionFrames == tempPositionFrames) {
452 if (tempTimeNanos - mTimestampNanosForLastPosition >
453 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
454 ALOGW("%s, the reported position is not changed within %d msec. "
455 "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
456 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
457 return mHalExternalPositionStatus;
458 }
459 mFrozenPositionCount++;
460 } else {
461 mFrozenPositionCount = 0;
462 }
463
464 if (mTimestampNanosForLastPosition > tempTimeNanos) {
465 // If the timestamp 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 timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
468 __func__, mTimestampNanosForLastPosition, tempTimeNanos);
469 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
470 return mHalExternalPositionStatus;
471 } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
472 mFrozenTimestampCount++;
473 } else {
474 mFrozenTimestampCount = 0;
475 }
476
477 if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
478 ALOGW("%s too many frozen external position from HAL.", __func__);
479 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
480 return mHalExternalPositionStatus;
481 }
482
483 mLastPositionFrames = tempPositionFrames;
484 mTimestampNanosForLastPosition = tempTimeNanos;
485
486 // Only update the timestamp and position when they looks valid.
487 *positionFrames = tempPositionFrames;
488 *timeNanos = tempTimeNanos;
489 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700490}
jiabinf7f06152021-11-22 18:10:14 +0000491
492aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer(
493 android::base::unique_fd* fileDescriptor)
494{
495 memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
496 int32_t minSizeFrames = getBufferCapacity();
497 if (minSizeFrames <= 0) { // zero will get rejected
498 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
499 }
500 status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
501 bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
502 if (status != OK) {
503 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
504 __func__, status, strerror(-status));
505 return AAUDIO_ERROR_UNAVAILABLE;
506 } else {
507 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
508 ", Sharable FD: %s",
509 __func__,
510 mMmapBufferinfo.buffer_size_frames,
511 mMmapBufferinfo.burst_size_frames,
512 isBufferShareable ? "Yes" : "No");
513 }
514
515 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
516 if (!isBufferShareable) {
517 // Exclusive mode can only be used by the service because the FD cannot be shared.
518 int32_t audioServiceUid =
519 VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
520 if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
521 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
522 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
523 return AAUDIO_ERROR_UNAVAILABLE;
524 }
525 }
526
527 // AAudio creates a copy of this FD and retains ownership of the copy.
528 // Assume that AudioFlinger will close the original shared_memory_fd.
529 fileDescriptor->reset(dup(mMmapBufferinfo.shared_memory_fd));
530 if (fileDescriptor->get() == -1) {
531 ALOGE("%s() - could not dup shared_memory_fd", __func__);
532 return AAUDIO_ERROR_INTERNAL;
533 }
534
535 // Call to HAL to make sure the transport FD was able to be closed by binder.
536 // This is a tricky workaround for a problem in Binder.
537 // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
538 struct audio_mmap_position position;
539 mMmapStream->getMmapPosition(&position);
540
541 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
542
543 return AAUDIO_OK;
544}