blob: ea817ab9309475accfa870f0c5e65da831c758b8 [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());
Phil Burk4238a5d2022-09-01 16:57:00 +000074 mRequestedDeviceId = getDeviceId();
75
Svet Ganov33761132021-05-13 22:51:08 +000076 mMmapClient.attributionSource = request.getAttributionSource();
77 // TODO b/182392769: use attribution source util
78 mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070079 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +000080 mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -070081 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Phil Burk39f02dd2017-08-04 09:13:31 -070082
Phil Burk04e805b2018-03-27 09:13:53 -070083 audio_format_t audioFormat = getFormat();
84
Phil Burk04e805b2018-03-27 09:13:53 -070085 result = openWithFormat(audioFormat);
86 if (result == AAUDIO_OK) return result;
87
millerliang8eebeba2021-11-03 21:45:58 +080088 if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_FLOAT) {
89 ALOGD("%s() FLOAT failed, perhaps due to format. Try again with 32_BIT", __func__);
90 audioFormat = AUDIO_FORMAT_PCM_32_BIT;
91 result = openWithFormat(audioFormat);
92 }
93 if (result == AAUDIO_OK) return result;
94
millerlianga75a83f2021-04-30 17:43:00 +080095 if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_32_BIT) {
96 ALOGD("%s() 32_BIT failed, perhaps due to format. Try again with 24_BIT_PACKED", __func__);
97 audioFormat = AUDIO_FORMAT_PCM_24_BIT_PACKED;
98 result = openWithFormat(audioFormat);
99 }
100 if (result == AAUDIO_OK) return result;
101
Phil Burk04e805b2018-03-27 09:13:53 -0700102 // TODO The HAL and AudioFlinger should be recommending a format if the open fails.
103 // But that recommendation is not propagating back from the HAL.
104 // So for now just try something very likely to work.
105 if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
106 ALOGD("%s() 24_BIT failed, perhaps due to format. Try again with 16_BIT", __func__);
107 audioFormat = AUDIO_FORMAT_PCM_16_BIT;
108 result = openWithFormat(audioFormat);
109 }
110 return result;
111}
112
113aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(audio_format_t audioFormat) {
114 aaudio_result_t result = AAUDIO_OK;
115 audio_config_base_t config;
116 audio_port_handle_t deviceId;
117
118 const audio_attributes_t attributes = getAudioAttributesFrom(this);
119
Phil Burk4238a5d2022-09-01 16:57:00 +0000120 deviceId = mRequestedDeviceId;
Phil Burk39f02dd2017-08-04 09:13:31 -0700121
122 // Fill in config
Phil Burk0127c1b2018-03-29 13:48:06 -0700123 config.format = audioFormat;
Phil Burk39f02dd2017-08-04 09:13:31 -0700124
125 int32_t aaudioSampleRate = getSampleRate();
126 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
127 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
128 }
129 config.sample_rate = aaudioSampleRate;
130
jiabind1f1cb62020-03-24 11:57:57 -0700131 const aaudio_direction_t direction = getDirection();
132
jiabina9094092021-06-28 20:36:45 +0000133 config.channel_mask = AAudio_getChannelMaskForOpen(
134 getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
135
Phil Burk39f02dd2017-08-04 09:13:31 -0700136 if (direction == AAUDIO_DIRECTION_OUTPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700137 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
138
139 } else if (direction == AAUDIO_DIRECTION_INPUT) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700140 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
141
142 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700143 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700144 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
145 }
146
147 MmapStreamInterface::stream_direction_t streamDirection =
148 (direction == AAUDIO_DIRECTION_OUTPUT)
149 ? MmapStreamInterface::DIRECTION_OUTPUT
150 : MmapStreamInterface::DIRECTION_INPUT;
151
Phil Burk4e1af9f2018-01-03 15:54:35 -0800152 aaudio_session_id_t requestedSessionId = getSessionId();
153 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
154
Phil Burk39f02dd2017-08-04 09:13:31 -0700155 // Open HAL stream. Set mMmapStream
Phil Burk4238a5d2022-09-01 16:57:00 +0000156 ALOGD("%s trying to open MMAP stream with format=%#x, "
157 "sample_rate=%u, channel_mask=%#x, device=%d",
158 __func__, config.format, config.sample_rate,
159 config.channel_mask, deviceId);
Phil Burk39f02dd2017-08-04 09:13:31 -0700160 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
161 &attributes,
162 &config,
163 mMmapClient,
164 &deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800165 &sessionId,
Phil Burk39f02dd2017-08-04 09:13:31 -0700166 this, // callback
167 mMmapStream,
168 &mPortHandle);
Svet Ganov33761132021-05-13 22:51:08 +0000169 ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
170 __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700171 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700172 // This can happen if the resource is busy or the config does
173 // not match the hardware.
174 ALOGD("%s() - openMmapStream() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700175 return AAUDIO_ERROR_UNAVAILABLE;
176 }
177
178 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700179 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700180 }
181 setDeviceId(deviceId);
182
Phil Burk4e1af9f2018-01-03 15:54:35 -0800183 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700184 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800185 }
186
187 aaudio_session_id_t actualSessionId =
188 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
189 ? AAUDIO_SESSION_ID_NONE
190 : (aaudio_session_id_t) sessionId;
191 setSessionId(actualSessionId);
Phil Burked782c82022-02-08 21:43:53 +0000192
193 ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
194 __func__, audioFormat, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800195
Phil Burk39f02dd2017-08-04 09:13:31 -0700196 // Create MMAP/NOIRQ buffer.
millerliang18d1e6c2022-02-08 15:43:40 +0800197 result = createMmapBuffer(&mAudioDataFileDescriptor);
198 if (result != AAUDIO_OK) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700199 goto error;
Phil Burk39f02dd2017-08-04 09:13:31 -0700200 }
201
202 // Get information about the stream and pass it back to the caller.
jiabina9094092021-06-28 20:36:45 +0000203 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
204 config.channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
205 AAudio_isChannelIndexMask(config.channel_mask)));
Phil Burk39f02dd2017-08-04 09:13:31 -0700206
Phil Burk0127c1b2018-03-29 13:48:06 -0700207 setFormat(config.format);
Phil Burk39f02dd2017-08-04 09:13:31 -0700208 setSampleRate(config.sample_rate);
209
jiabina5df87b2020-12-29 10:45:19 -0800210 // If the position is not updated while the timestamp is updated for more than a certain amount,
211 // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
212 // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
213 // that is too short.
214 static constexpr int kTimestampGraceBurstCount = 5;
215 mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
216 * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
217
Phil Burked782c82022-02-08 21:43:53 +0000218 ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
jiabina9094092021-06-28 20:36:45 +0000219 __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
220 deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700221
Phil Burked782c82022-02-08 21:43:53 +0000222 ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
223 __func__, getFormat(), audio_format_to_string(getFormat()),
224 calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700225
Phil Burk39f02dd2017-08-04 09:13:31 -0700226 return result;
227
228error:
229 close();
Phil Burk4238a5d2022-09-01 16:57:00 +0000230 // restore original requests
231 setDeviceId(mRequestedDeviceId);
232 setSessionId(requestedSessionId);
Phil Burk39f02dd2017-08-04 09:13:31 -0700233 return result;
234}
235
Phil Burk320910f2020-08-12 14:29:10 +0000236void AAudioServiceEndpointMMAP::close() {
Phil Burk6e463ce2020-04-13 10:20:20 -0700237 if (mMmapStream != nullptr) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700238 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
239 mMmapStream.clear();
240 // Apparently the above close is asynchronous. An attempt to open a new device
241 // right after a close can fail. Also some callbacks may still be in flight!
242 // FIXME Make closing synchronous.
243 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
244 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700245}
246
247aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700248 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700249 // Start the client on behalf of the AAudio service.
250 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700251 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700252 audio_attributes_t attr = {};
253 if (stream != nullptr) {
254 attr = getAudioAttributesFrom(stream.get());
255 }
256 aaudio_result_t result = startClient(
257 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700258 // When AudioFlinger is passed a valid port handle then it should not change it.
259 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
260 "%s() port handle not expected to change from %d to %d",
261 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700262 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700263 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700264}
265
266aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700267 audio_port_handle_t clientHandle __unused) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700268 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700269
270 // Round 64-bit counter up to a multiple of the buffer capacity.
271 // This is required because the 64-bit counter is used as an index
272 // into a circular buffer and the actual HW position is reset to zero
273 // when the stream is stopped.
274 mFramesTransferred.roundUp64(getBufferCapacity());
275
Phil Burkbbd52862018-04-13 11:37:42 -0700276 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700277 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700278 return stopClient(mPortHandle);
279}
280
281aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700282 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700283 audio_port_handle_t *clientHandle) {
284 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
jiabind1f1cb62020-03-24 11:57:57 -0700285 status_t status = mMmapStream->start(client, attr, clientHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700286 return AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700287}
288
289aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
290 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
291 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700292 return result;
293}
294
jiabinf7f06152021-11-22 18:10:14 +0000295aaudio_result_t AAudioServiceEndpointMMAP::standby() {
296 if (mMmapStream == nullptr) {
297 return AAUDIO_ERROR_NULL;
298 }
299 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->standby());
300 return result;
301}
302
303aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
304 if (mMmapStream == nullptr) {
305 return AAUDIO_ERROR_NULL;
306 }
307 mAudioDataFileDescriptor.reset();
308 aaudio_result_t result = createMmapBuffer(&mAudioDataFileDescriptor);
309 if (result == AAUDIO_OK) {
310 int32_t bytesPerFrame = calculateBytesPerFrame();
311 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
312 int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
313 parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
314 parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
315 parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
316 parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
317 }
318 return result;
319}
320
Phil Burk39f02dd2017-08-04 09:13:31 -0700321// Get free-running DSP or DMA hardware position from the HAL.
322aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
323 int64_t *timeNanos) {
324 struct audio_mmap_position position;
325 if (mMmapStream == nullptr) {
326 return AAUDIO_ERROR_NULL;
327 }
328 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700329 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
330 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
Phil Burk39f02dd2017-08-04 09:13:31 -0700331 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
332 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700333 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700334 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700335 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700336 } else {
337 // Convert 32-bit position to 64-bit position.
338 mFramesTransferred.update32(position.position_frames);
339 *positionFrames = mFramesTransferred.get();
340 *timeNanos = position.time_nanoseconds;
341 }
342 return result;
343}
344
345aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
346 int64_t *timeNanos) {
347 return 0; // TODO
348}
349
Phil Burka77869d2020-05-07 10:39:47 -0700350// This is called by onTearDown() in a separate thread to avoid deadlocks.
351void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
Phil Burkbbd52862018-04-13 11:37:42 -0700352 // Are we tearing down the EXCLUSIVE MMAP stream?
353 if (isStreamRegistered(portHandle)) {
354 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
355 disconnectRegisteredStreams();
356 } else {
357 // Must be a SHARED stream?
358 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
359 aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
360 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
361 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700362};
363
Phil Burka77869d2020-05-07 10:39:47 -0700364// This is called by AudioFlinger when it wants to destroy a stream.
365void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
366 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
Phil Burk3d201942021-04-08 23:27:04 +0000367 android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
368 std::thread asyncTask([holdEndpoint, portHandle]() {
369 holdEndpoint->handleTearDownAsync(portHandle);
370 });
Phil Burka77869d2020-05-07 10:39:47 -0700371 asyncTask.detach();
372}
373
Phil Burk39f02dd2017-08-04 09:13:31 -0700374void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
375 android::Vector<float> values) {
Phil Burk19e990e2018-03-22 13:59:34 -0700376 // TODO Do we really need a different volume for each channel?
377 // We get called with an array filled with a single value!
Phil Burk39f02dd2017-08-04 09:13:31 -0700378 float volume = values[0];
Phil Burk29ccc292019-04-15 08:58:08 -0700379 ALOGD("%s() volume[0] = %f", __func__, volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700380 std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800381 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700382 stream->onVolumeChanged(volume);
383 }
384};
385
Phil Burka77869d2020-05-07 10:39:47 -0700386void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
387 const int32_t deviceId = static_cast<int32_t>(portHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700388 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burka77869d2020-05-07 10:39:47 -0700389 if (getDeviceId() != deviceId) {
390 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
Phil Burk3d201942021-04-08 23:27:04 +0000391 android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
392 std::thread asyncTask([holdEndpoint, deviceId]() {
393 ALOGD("onRoutingChanged() asyncTask launched");
394 holdEndpoint->disconnectRegisteredStreams();
395 holdEndpoint->setDeviceId(deviceId);
Phil Burka77869d2020-05-07 10:39:47 -0700396 });
397 asyncTask.detach();
398 } else {
399 setDeviceId(deviceId);
400 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700401 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700402};
403
404/**
405 * Get an immutable description of the data queue from the HAL.
406 */
jiabin2a594622021-10-14 00:32:25 +0000407aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
408 AudioEndpointParcelable* parcelable)
Phil Burk39f02dd2017-08-04 09:13:31 -0700409{
410 // Gather information on the data queue based on HAL info.
411 int32_t bytesPerFrame = calculateBytesPerFrame();
412 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
jiabin2a594622021-10-14 00:32:25 +0000413 int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
414 parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
415 parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
416 parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
417 parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700418 return AAUDIO_OK;
419}
jiabinb7d8c5a2020-08-26 17:24:52 -0700420
421aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
422 int64_t *timeNanos)
423{
jiabina5df87b2020-12-29 10:45:19 -0800424 if (mHalExternalPositionStatus != AAUDIO_OK) {
425 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700426 }
jiabina5df87b2020-12-29 10:45:19 -0800427 uint64_t tempPositionFrames;
428 int64_t tempTimeNanos;
429 status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
430 if (status != OK) {
431 // getExternalPosition reports error. The HAL may not support the API. Cache the result
jiabinb7d8c5a2020-08-26 17:24:52 -0700432 // so that the call will not go to the HAL next time.
jiabina5df87b2020-12-29 10:45:19 -0800433 mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
434 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700435 }
jiabina5df87b2020-12-29 10:45:19 -0800436
437 // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
438 // to report correct external position. In that case, we will not trust the values reported from
439 // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
440 // correct position within a period. But it may not be a good idea to get system time too often.
441 // In that case, a maximum number of frozen external position is defined so that if the
442 // count of the same timestamp or position is reported by the HAL continuously, the values from
443 // the HAL will no longer be trusted.
444 static constexpr int kMaxFrozenCount = 20;
445 // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
446 // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
447 // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
448 // position is a valid one. Do a simple validation, which is checking if the position is
449 // forward within half a second or not, here so that this function can return error if
450 // the validation fails. Note that we don't only apply this validation logic to HAL API
451 // less than 7.0. The reason is that there is a chance the HAL is not reporting the
452 // timestamp and position correctly.
453 if (mLastPositionFrames > tempPositionFrames) {
454 // If the position is going backwards, there must be something wrong with the HAL.
455 // In that case, we do not trust the values reported by the HAL.
456 ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
457 __func__, mLastPositionFrames, tempPositionFrames);
458 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
459 return mHalExternalPositionStatus;
460 } else if (mLastPositionFrames == tempPositionFrames) {
461 if (tempTimeNanos - mTimestampNanosForLastPosition >
462 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
463 ALOGW("%s, the reported position is not changed within %d msec. "
464 "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
465 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
466 return mHalExternalPositionStatus;
467 }
468 mFrozenPositionCount++;
469 } else {
470 mFrozenPositionCount = 0;
471 }
472
473 if (mTimestampNanosForLastPosition > tempTimeNanos) {
474 // If the timestamp is going backwards, there must be something wrong with the HAL.
475 // In that case, we do not trust the values reported by the HAL.
476 ALOGW("%s timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
477 __func__, mTimestampNanosForLastPosition, tempTimeNanos);
478 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
479 return mHalExternalPositionStatus;
480 } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
481 mFrozenTimestampCount++;
482 } else {
483 mFrozenTimestampCount = 0;
484 }
485
486 if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
487 ALOGW("%s too many frozen external position from HAL.", __func__);
488 mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
489 return mHalExternalPositionStatus;
490 }
491
492 mLastPositionFrames = tempPositionFrames;
493 mTimestampNanosForLastPosition = tempTimeNanos;
494
495 // Only update the timestamp and position when they looks valid.
496 *positionFrames = tempPositionFrames;
497 *timeNanos = tempTimeNanos;
498 return mHalExternalPositionStatus;
jiabinb7d8c5a2020-08-26 17:24:52 -0700499}
jiabinf7f06152021-11-22 18:10:14 +0000500
501aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer(
502 android::base::unique_fd* fileDescriptor)
503{
504 memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
505 int32_t minSizeFrames = getBufferCapacity();
506 if (minSizeFrames <= 0) { // zero will get rejected
507 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
508 }
509 status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
510 bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
511 if (status != OK) {
512 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
513 __func__, status, strerror(-status));
514 return AAUDIO_ERROR_UNAVAILABLE;
515 } else {
516 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
517 ", Sharable FD: %s",
518 __func__,
519 mMmapBufferinfo.buffer_size_frames,
520 mMmapBufferinfo.burst_size_frames,
521 isBufferShareable ? "Yes" : "No");
522 }
523
524 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
525 if (!isBufferShareable) {
526 // Exclusive mode can only be used by the service because the FD cannot be shared.
527 int32_t audioServiceUid =
528 VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
529 if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
530 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
531 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
532 return AAUDIO_ERROR_UNAVAILABLE;
533 }
534 }
535
536 // AAudio creates a copy of this FD and retains ownership of the copy.
537 // Assume that AudioFlinger will close the original shared_memory_fd.
538 fileDescriptor->reset(dup(mMmapBufferinfo.shared_memory_fd));
539 if (fileDescriptor->get() == -1) {
540 ALOGE("%s() - could not dup shared_memory_fd", __func__);
541 return AAUDIO_ERROR_INTERNAL;
542 }
543
544 // Call to HAL to make sure the transport FD was able to be closed by binder.
545 // This is a tricky workaround for a problem in Binder.
546 // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
547 struct audio_mmap_position position;
548 mMmapStream->getMmapPosition(&position);
549
550 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
551
552 return AAUDIO_OK;
553}