blob: 5bdb8eb860892eea183f40473a751cff21120326 [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
Phil Burkd4ccc622017-12-20 15:32:44 -080082 aaudio_direction_t direction = getDirection();
83
84 const audio_content_type_t contentType =
85 AAudioConvert_contentTypeToInternal(getContentType());
Phil Burk55e5eab2018-04-10 15:16:38 -070086 // Usage only used for OUTPUT
Phil Burkd4ccc622017-12-20 15:32:44 -080087 const audio_usage_t usage = (direction == AAUDIO_DIRECTION_OUTPUT)
88 ? AAudioConvert_usageToInternal(getUsage())
89 : AUDIO_USAGE_UNKNOWN;
90 const audio_source_t source = (direction == AAUDIO_DIRECTION_INPUT)
91 ? AAudioConvert_inputPresetToAudioSource(getInputPreset())
92 : AUDIO_SOURCE_DEFAULT;
Eric Laurentd17c8502019-10-24 15:58:35 -070093 audio_flags_mask_t flags;
94 if (direction == AAUDIO_DIRECTION_OUTPUT) {
95 flags = AUDIO_FLAG_LOW_LATENCY
96 | AAudioConvert_allowCapturePolicyToAudioFlagsMask(getAllowedCapturePolicy());
97 } else {
98 flags = AUDIO_FLAG_LOW_LATENCY
99 | AAudioConvert_privacySensitiveToAudioFlagsMask(isPrivacySensitive());
100 }
Phil Burkd4ccc622017-12-20 15:32:44 -0800101 const audio_attributes_t attributes = {
102 .content_type = contentType,
103 .usage = usage,
104 .source = source,
Kevin Rocard68646ba2019-03-20 13:26:49 -0700105 .flags = flags,
Phil Burkd4ccc622017-12-20 15:32:44 -0800106 .tags = ""
107 };
Phil Burka62fb952018-01-16 12:44:06 -0800108
Phil Burk39f02dd2017-08-04 09:13:31 -0700109 mMmapClient.clientUid = request.getUserId();
110 mMmapClient.clientPid = request.getProcessId();
111 mMmapClient.packageName.setTo(String16(""));
112
113 mRequestedDeviceId = deviceId = getDeviceId();
114
115 // Fill in config
Phil Burk0127c1b2018-03-29 13:48:06 -0700116 audio_format_t audioFormat = getFormat();
117 if (audioFormat == AUDIO_FORMAT_DEFAULT || audioFormat == AUDIO_FORMAT_PCM_FLOAT) {
118 audioFormat = AUDIO_FORMAT_PCM_16_BIT;
Phil Burk39f02dd2017-08-04 09:13:31 -0700119 }
Phil Burk0127c1b2018-03-29 13:48:06 -0700120 config.format = audioFormat;
Phil Burk39f02dd2017-08-04 09:13:31 -0700121
122 int32_t aaudioSampleRate = getSampleRate();
123 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
124 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
125 }
126 config.sample_rate = aaudioSampleRate;
127
128 int32_t aaudioSamplesPerFrame = getSamplesPerFrame();
129
Phil Burk39f02dd2017-08-04 09:13:31 -0700130 if (direction == AAUDIO_DIRECTION_OUTPUT) {
131 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
132 ? AUDIO_CHANNEL_OUT_STEREO
133 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
134 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
135
136 } else if (direction == AAUDIO_DIRECTION_INPUT) {
137 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
138 ? AUDIO_CHANNEL_IN_STEREO
139 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
140 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
156 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
157 &attributes,
158 &config,
159 mMmapClient,
160 &deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800161 &sessionId,
Phil Burk39f02dd2017-08-04 09:13:31 -0700162 this, // callback
163 mMmapStream,
164 &mPortHandle);
Phil Burk19e990e2018-03-22 13:59:34 -0700165 ALOGD("%s() mMapClient.uid = %d, pid = %d => portHandle = %d\n",
166 __func__, mMmapClient.clientUid, mMmapClient.clientPid, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700167 if (status != OK) {
Phil Burk29ccc292019-04-15 08:58:08 -0700168 // This can happen if the resource is busy or the config does
169 // not match the hardware.
170 ALOGD("%s() - openMmapStream() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700171 return AAUDIO_ERROR_UNAVAILABLE;
172 }
173
174 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burka3901e92018-10-08 13:54:38 -0700175 ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700176 }
177 setDeviceId(deviceId);
178
Phil Burk4e1af9f2018-01-03 15:54:35 -0800179 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700180 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800181 }
182
183 aaudio_session_id_t actualSessionId =
184 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
185 ? AAUDIO_SESSION_ID_NONE
186 : (aaudio_session_id_t) sessionId;
187 setSessionId(actualSessionId);
Phil Burk19e990e2018-03-22 13:59:34 -0700188 ALOGD("%s() deviceId = %d, sessionId = %d", __func__, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800189
Phil Burk39f02dd2017-08-04 09:13:31 -0700190 // Create MMAP/NOIRQ buffer.
191 int32_t minSizeFrames = getBufferCapacity();
192 if (minSizeFrames <= 0) { // zero will get rejected
193 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
194 }
195 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
Kevin Rocard734334f2018-07-12 19:37:41 -0700196 bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
Phil Burk39f02dd2017-08-04 09:13:31 -0700197 if (status != OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700198 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
199 __func__, status, strerror(-status));
Phil Burk39f02dd2017-08-04 09:13:31 -0700200 result = AAUDIO_ERROR_UNAVAILABLE;
201 goto error;
202 } else {
Phil Burk29ccc292019-04-15 08:58:08 -0700203 ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
Phil Burk39f02dd2017-08-04 09:13:31 -0700204 ", Sharable FD: %s",
Phil Burk29ccc292019-04-15 08:58:08 -0700205 __func__,
Kevin Rocard734334f2018-07-12 19:37:41 -0700206 mMmapBufferinfo.buffer_size_frames,
Phil Burk39f02dd2017-08-04 09:13:31 -0700207 mMmapBufferinfo.burst_size_frames,
Kevin Rocard734334f2018-07-12 19:37:41 -0700208 isBufferShareable ? "Yes" : "No");
Phil Burk39f02dd2017-08-04 09:13:31 -0700209 }
210
211 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
Kevin Rocard734334f2018-07-12 19:37:41 -0700212 if (!isBufferShareable) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700213 // Exclusive mode can only be used by the service because the FD cannot be shared.
214 uid_t audioServiceUid = getuid();
215 if ((mMmapClient.clientUid != audioServiceUid) &&
216 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700217 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700218 result = AAUDIO_ERROR_UNAVAILABLE;
219 goto error;
220 }
221 }
222
223 // Get information about the stream and pass it back to the caller.
224 setSamplesPerFrame((direction == AAUDIO_DIRECTION_OUTPUT)
225 ? audio_channel_count_from_out_mask(config.channel_mask)
226 : audio_channel_count_from_in_mask(config.channel_mask));
227
228 // AAudio creates a copy of this FD and retains ownership of the copy.
229 // Assume that AudioFlinger will close the original shared_memory_fd.
230 mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
231 if (mAudioDataFileDescriptor.get() == -1) {
Phil Burk19e990e2018-03-22 13:59:34 -0700232 ALOGE("%s() - could not dup shared_memory_fd", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700233 result = AAUDIO_ERROR_INTERNAL;
234 goto error;
235 }
236 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
Phil Burk0127c1b2018-03-29 13:48:06 -0700237 setFormat(config.format);
Phil Burk39f02dd2017-08-04 09:13:31 -0700238 setSampleRate(config.sample_rate);
239
Phil Burk3c4e6b52019-01-22 15:53:36 -0800240 ALOGD("%s() actual rate = %d, channels = %d"
241 ", deviceId = %d, capacity = %d\n",
242 __func__, getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700243
Phil Burk3c4e6b52019-01-22 15:53:36 -0800244 ALOGD("%s() format = 0x%08x, frame size = %d, burst size = %d",
245 __func__, getFormat(), 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
254aaudio_result_t AAudioServiceEndpointMMAP::close() {
Phil Burk39f02dd2017-08-04 09:13:31 -0700255 if (mMmapStream != 0) {
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();
258 // Apparently the above close is asynchronous. An attempt to open a new device
259 // right after a close can fail. Also some callbacks may still be in flight!
260 // FIXME Make closing synchronous.
261 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
262 }
263
264 return AAUDIO_OK;
265}
266
267aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
Phil Burkbbd52862018-04-13 11:37:42 -0700268 audio_port_handle_t *clientHandle __unused) {
Phil Burkbcc36742017-08-31 17:24:51 -0700269 // Start the client on behalf of the AAudio service.
270 // Use the port handle that was provided by openMmapStream().
Phil Burkbbd52862018-04-13 11:37:42 -0700271 audio_port_handle_t tempHandle = mPortHandle;
272 aaudio_result_t result = startClient(mMmapClient, &tempHandle);
273 // 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,
297 audio_port_handle_t *clientHandle) {
298 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burkbcc36742017-08-31 17:24:51 -0700299 status_t status = mMmapStream->start(client, clientHandle);
Phil Burk29ccc292019-04-15 08:58:08 -0700300 return AAudioConvert_androidToAAudioResult(status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700301}
302
303aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
304 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
305 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk39f02dd2017-08-04 09:13:31 -0700306 return result;
307}
308
309// Get free-running DSP or DMA hardware position from the HAL.
310aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
311 int64_t *timeNanos) {
312 struct audio_mmap_position position;
313 if (mMmapStream == nullptr) {
314 return AAUDIO_ERROR_NULL;
315 }
316 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700317 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
318 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
Phil Burk39f02dd2017-08-04 09:13:31 -0700319 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
320 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700321 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700322 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700323 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700324 } else {
325 // Convert 32-bit position to 64-bit position.
326 mFramesTransferred.update32(position.position_frames);
327 *positionFrames = mFramesTransferred.get();
328 *timeNanos = position.time_nanoseconds;
329 }
330 return result;
331}
332
333aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
334 int64_t *timeNanos) {
335 return 0; // TODO
336}
337
Phil Burkbbd52862018-04-13 11:37:42 -0700338// This is called by AudioFlinger when it wants to destroy a stream.
339void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
340 ALOGD("%s(portHandle = %d) called", __func__, portHandle);
341 // Are we tearing down the EXCLUSIVE MMAP stream?
342 if (isStreamRegistered(portHandle)) {
343 ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
344 disconnectRegisteredStreams();
345 } else {
346 // Must be a SHARED stream?
347 ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
348 aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
349 ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
350 }
Phil Burk39f02dd2017-08-04 09:13:31 -0700351};
352
353void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
354 android::Vector<float> values) {
Phil Burk19e990e2018-03-22 13:59:34 -0700355 // TODO Do we really need a different volume for each channel?
356 // We get called with an array filled with a single value!
Phil Burk39f02dd2017-08-04 09:13:31 -0700357 float volume = values[0];
Phil Burk29ccc292019-04-15 08:58:08 -0700358 ALOGD("%s() volume[0] = %f", __func__, volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700359 std::lock_guard<std::mutex> lock(mLockStreams);
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800360 for(const auto& stream : mRegisteredStreams) {
Phil Burk39f02dd2017-08-04 09:13:31 -0700361 stream->onVolumeChanged(volume);
362 }
363};
364
365void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
Phil Burk29ccc292019-04-15 08:58:08 -0700366 ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
Phil Burk39f02dd2017-08-04 09:13:31 -0700367 if (getDeviceId() != AUDIO_PORT_HANDLE_NONE && getDeviceId() != deviceId) {
368 disconnectRegisteredStreams();
369 }
370 setDeviceId(deviceId);
371};
372
373/**
374 * Get an immutable description of the data queue from the HAL.
375 */
376aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
377{
378 // Gather information on the data queue based on HAL info.
379 int32_t bytesPerFrame = calculateBytesPerFrame();
380 int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
381 int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
382 parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
383 parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
384 parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
385 parcelable.mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
386 return AAUDIO_OK;
387}