blob: af2710dc42da7973c878a6e9245465ec5ca4c9d0 [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>
26#include <utils/Singleton.h>
27#include <vector>
28
29
30#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
39
40#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 -070051
52AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
53 : mMmapStream(nullptr)
54 , mAAudioService(audioService) {}
Phil Burk39f02dd2017-08-04 09:13:31 -070055
56AAudioServiceEndpointMMAP::~AAudioServiceEndpointMMAP() {}
57
58std::string AAudioServiceEndpointMMAP::dump() const {
59 std::stringstream result;
60
61 result << " MMAP: framesTransferred = " << mFramesTransferred.get();
62 result << ", HW nanos = " << mHardwareTimeOffsetNanos;
63 result << ", port handle = " << mPortHandle;
64 result << ", audio data FD = " << mAudioDataFileDescriptor;
65 result << "\n";
66
67 result << " HW Offset Micros: " <<
68 (getHardwareTimeOffsetNanos()
69 / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
70
71 result << AAudioServiceEndpoint::dump();
72 return result.str();
73}
74
75aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
76 aaudio_result_t result = AAUDIO_OK;
Phil Burk39f02dd2017-08-04 09:13:31 -070077 audio_config_base_t config;
78 audio_port_handle_t deviceId;
79
Phil Burk39f02dd2017-08-04 09:13:31 -070080 copyFrom(request.getConstantConfiguration());
81
jiabind1f1cb62020-03-24 11:57:57 -070082 const audio_attributes_t attributes = getAudioAttributesFrom(this);
Phil Burka62fb952018-01-16 12:44:06 -080083
Phil Burk39f02dd2017-08-04 09:13:31 -070084 mMmapClient.clientUid = request.getUserId();
85 mMmapClient.clientPid = request.getProcessId();
86 mMmapClient.packageName.setTo(String16(""));
87
88 mRequestedDeviceId = deviceId = getDeviceId();
89
90 // Fill in config
Phil Burk0127c1b2018-03-29 13:48:06 -070091 audio_format_t audioFormat = getFormat();
92 if (audioFormat == AUDIO_FORMAT_DEFAULT || audioFormat == AUDIO_FORMAT_PCM_FLOAT) {
93 audioFormat = AUDIO_FORMAT_PCM_16_BIT;
Phil Burk39f02dd2017-08-04 09:13:31 -070094 }
Phil Burk0127c1b2018-03-29 13:48:06 -070095 config.format = audioFormat;
Phil Burk39f02dd2017-08-04 09:13:31 -070096
97 int32_t aaudioSampleRate = getSampleRate();
98 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
99 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
100 }
101 config.sample_rate = aaudioSampleRate;
102
103 int32_t aaudioSamplesPerFrame = getSamplesPerFrame();
104
jiabind1f1cb62020-03-24 11:57:57 -0700105 const aaudio_direction_t direction = getDirection();
106
Phil Burk39f02dd2017-08-04 09:13:31 -0700107 if (direction == AAUDIO_DIRECTION_OUTPUT) {
108 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
109 ? AUDIO_CHANNEL_OUT_STEREO
110 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
111 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
112
113 } else if (direction == AAUDIO_DIRECTION_INPUT) {
114 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
115 ? AUDIO_CHANNEL_IN_STEREO
116 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
117 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
118
119 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700120 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700121 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
122 }
123
124 MmapStreamInterface::stream_direction_t streamDirection =
125 (direction == AAUDIO_DIRECTION_OUTPUT)
126 ? MmapStreamInterface::DIRECTION_OUTPUT
127 : MmapStreamInterface::DIRECTION_INPUT;
128
Phil Burk4e1af9f2018-01-03 15:54:35 -0800129 aaudio_session_id_t requestedSessionId = getSessionId();
130 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
131
Phil Burk39f02dd2017-08-04 09:13:31 -0700132 // Open HAL stream. Set mMmapStream
133 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
134 &attributes,
135 &config,
136 mMmapClient,
137 &deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800138 &sessionId,
Phil Burk39f02dd2017-08-04 09:13:31 -0700139 this, // callback
140 mMmapStream,
141 &mPortHandle);
Phil Burk19e990e2018-03-22 13:59:34 -0700142 ALOGD("%s() mMapClient.uid = %d, pid = %d => portHandle = %d\n",
143 __func__, mMmapClient.clientUid, mMmapClient.clientPid, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700144 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700145 // This can happen if the resource is busy or the config does
146 // not match the hardware.
147 ALOGD("%s() - openMmapStream() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700148 return AAUDIO_ERROR_UNAVAILABLE;
149 }
150
151 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700152 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700153 }
154 setDeviceId(deviceId);
155
Phil Burk4e1af9f2018-01-03 15:54:35 -0800156 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700157 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800158 }
159
160 aaudio_session_id_t actualSessionId =
161 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
162 ? AAUDIO_SESSION_ID_NONE
163 : (aaudio_session_id_t) sessionId;
164 setSessionId(actualSessionId);
Phil Burk19e990e2018-03-22 13:59:34 -0700165 ALOGD("%s() deviceId = %d, sessionId = %d", __func__, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800166
Phil Burk39f02dd2017-08-04 09:13:31 -0700167 // Create MMAP/NOIRQ buffer.
168 int32_t minSizeFrames = getBufferCapacity();
169 if (minSizeFrames <= 0) { // zero will get rejected
170 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
171 }
172 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
Kevin Rocard734334f2018-07-12 19:37:41 -0700173 bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
Phil Burk39f02dd2017-08-04 09:13:31 -0700174 if (status != OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700175 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
176 __func__, status, strerror(-status));
Phil Burk39f02dd2017-08-04 09:13:31 -0700177 result = AAUDIO_ERROR_UNAVAILABLE;
178 goto error;
179 } else {
Phil Burk29ccc292019-04-15 08:58:08 -0700180 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
Phil Burk39f02dd2017-08-04 09:13:31 -0700181 ", Sharable FD: %s",
Phil Burk29ccc292019-04-15 08:58:08 -0700182 __func__,
Kevin Rocard734334f2018-07-12 19:37:41 -0700183 mMmapBufferinfo.buffer_size_frames,
Phil Burk39f02dd2017-08-04 09:13:31 -0700184 mMmapBufferinfo.burst_size_frames,
Kevin Rocard734334f2018-07-12 19:37:41 -0700185 isBufferShareable ? "Yes" : "No");
Phil Burk39f02dd2017-08-04 09:13:31 -0700186 }
187
188 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
Kevin Rocard734334f2018-07-12 19:37:41 -0700189 if (!isBufferShareable) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700190 // Exclusive mode can only be used by the service because the FD cannot be shared.
191 uid_t audioServiceUid = getuid();
192 if ((mMmapClient.clientUid != audioServiceUid) &&
193 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700194 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700195 result = AAUDIO_ERROR_UNAVAILABLE;
196 goto error;
197 }
198 }
199
200 // Get information about the stream and pass it back to the caller.
201 setSamplesPerFrame((direction == AAUDIO_DIRECTION_OUTPUT)
202 ? audio_channel_count_from_out_mask(config.channel_mask)
203 : audio_channel_count_from_in_mask(config.channel_mask));
204
205 // AAudio creates a copy of this FD and retains ownership of the copy.
206 // Assume that AudioFlinger will close the original shared_memory_fd.
207 mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
208 if (mAudioDataFileDescriptor.get() == -1) {
Phil Burk19e990e2018-03-22 13:59:34 -0700209 ALOGE("%s() - could not dup shared_memory_fd", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700210 result = AAUDIO_ERROR_INTERNAL;
211 goto error;
212 }
213 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
Phil Burk0127c1b2018-03-29 13:48:06 -0700214 setFormat(config.format);
Phil Burk39f02dd2017-08-04 09:13:31 -0700215 setSampleRate(config.sample_rate);
216
Phil Burk3c4e6b52019-01-22 15:53:36 -0800217 ALOGD("%s() actual rate = %d, channels = %d"
218 ", deviceId = %d, capacity = %d\n",
219 __func__, getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700220
Phil Burk3c4e6b52019-01-22 15:53:36 -0800221 ALOGD("%s() format = 0x%08x, frame size = %d, burst size = %d",
222 __func__, getFormat(), calculateBytesPerFrame(), mFramesPerBurst);
Phil Burk0127c1b2018-03-29 13:48:06 -0700223
Phil Burk39f02dd2017-08-04 09:13:31 -0700224 return result;
225
226error:
227 close();
228 return result;
229}
230
231aaudio_result_t AAudioServiceEndpointMMAP::close() {
Phil Burk39f02dd2017-08-04 09:13:31 -0700232 if (mMmapStream != 0) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700233 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
234 mMmapStream.clear();
235 // Apparently the above close is asynchronous. An attempt to open a new device
236 // right after a close can fail. Also some callbacks may still be in flight!
237 // FIXME Make closing synchronous.
238 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
239 }
240
241 return AAUDIO_OK;
242}
243
244aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700245 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700246 // Start the client on behalf of the AAudio service.
247 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700248 audio_port_handle_t tempHandle = mPortHandle;
jiabind1f1cb62020-03-24 11:57:57 -0700249 audio_attributes_t attr = {};
250 if (stream != nullptr) {
251 attr = getAudioAttributesFrom(stream.get());
252 }
253 aaudio_result_t result = startClient(
254 mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700255 // When AudioFlinger is passed a valid port handle then it should not change it.
256 LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
257 "%s() port handle not expected to change from %d to %d",
258 __func__, mPortHandle, tempHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700259 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burkbbd52862018-04-13 11:37:42 -0700260 return result;
Phil Burk39f02dd2017-08-04 09:13:31 -0700261}
262
263aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700264 audio_port_handle_t clientHandle __unused) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700265 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700266
267 // Round 64-bit counter up to a multiple of the buffer capacity.
268 // This is required because the 64-bit counter is used as an index
269 // into a circular buffer and the actual HW position is reset to zero
270 // when the stream is stopped.
271 mFramesTransferred.roundUp64(getBufferCapacity());
272
Phil Burkbbd52862018-04-13 11:37:42 -0700273 // Use the port handle that was provided by openMmapStream().
Phil Burk29ccc292019-04-15 08:58:08 -0700274 ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700275 return stopClient(mPortHandle);
276}
277
278aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -0700279 const audio_attributes_t *attr,
Phil Burk39f02dd2017-08-04 09:13:31 -0700280 audio_port_handle_t *clientHandle) {
281 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
jiabind1f1cb62020-03-24 11:57:57 -0700282 status_t status = mMmapStream->start(client, attr, clientHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700283 return AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700284}
285
286aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
287 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
288 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700289 return result;
290}
291
292// Get free-running DSP or DMA hardware position from the HAL.
293aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
294 int64_t *timeNanos) {
295 struct audio_mmap_position position;
296 if (mMmapStream == nullptr) {
297 return AAUDIO_ERROR_NULL;
298 }
299 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700300 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
301 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
Phil Burk39f02dd2017-08-04 09:13:31 -0700302 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
303 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700304 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700305 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700306 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700307 } else {
308 // Convert 32-bit position to 64-bit position.
309 mFramesTransferred.update32(position.position_frames);
310 *positionFrames = mFramesTransferred.get();
311 *timeNanos = position.time_nanoseconds;
312 }
313 return result;
314}
315
316aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
317 int64_t *timeNanos) {
318 return 0; // TODO
319}
320
Phil Burkbbd52862018-04-13 11:37:42 -0700321// This is called by AudioFlinger when it wants to destroy a stream.
322void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
323 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
324 // Are we tearing down the EXCLUSIVE MMAP stream?
325 if (isStreamRegistered(portHandle)) {
326 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
327 disconnectRegisteredStreams();
328 } else {
329 // Must be a SHARED stream?
330 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
331 aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
332 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
333 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700334};
335
336void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
337 android::Vector<float> values) {
Phil Burk19e990e2018-03-22 13:59:34 -0700338 // TODO Do we really need a different volume for each channel?
339 // We get called with an array filled with a single value!
Phil Burk39f02dd2017-08-04 09:13:31 -0700340 float volume = values[0];
Phil Burk29ccc292019-04-15 08:58:08 -0700341 ALOGD("%s() volume[0] = %f", __func__, volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700342 std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800343 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700344 stream->onVolumeChanged(volume);
345 }
346};
347
348void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
Phil Burk29ccc292019-04-15 08:58:08 -0700349 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burk39f02dd2017-08-04 09:13:31 -0700350 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE && getDeviceId() != deviceId) {
351 disconnectRegisteredStreams();
352 }
353 setDeviceId(deviceId);
354};
355
356/**
357 * Get an immutable description of the data queue from the HAL.
358 */
359aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
360{
361 // Gather information on the data queue based on HAL info.
362 int32_t bytesPerFrame = calculateBytesPerFrame();
363 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
364 int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
365 parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
366 parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
367 parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
368 parcelable.mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
369 return AAUDIO_OK;
370}