blob: 5f1de760a97f1d65c48016ae469a8992ba2be872 [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
51AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP()
52 : mMmapStream(nullptr) {}
53
54AAudioServiceEndpointMMAP::~AAudioServiceEndpointMMAP() {}
55
56std::string AAudioServiceEndpointMMAP::dump() const {
57 std::stringstream result;
58
59 result << " MMAP: framesTransferred = " << mFramesTransferred.get();
60 result << ", HW nanos = " << mHardwareTimeOffsetNanos;
61 result << ", port handle = " << mPortHandle;
62 result << ", audio data FD = " << mAudioDataFileDescriptor;
63 result << "\n";
64
65 result << " HW Offset Micros: " <<
66 (getHardwareTimeOffsetNanos()
67 / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
68
69 result << AAudioServiceEndpoint::dump();
70 return result.str();
71}
72
73aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
74 aaudio_result_t result = AAUDIO_OK;
Phil Burk39f02dd2017-08-04 09:13:31 -070075 audio_config_base_t config;
76 audio_port_handle_t deviceId;
77
78 int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
79 int32_t burstMicros = 0;
80
81 copyFrom(request.getConstantConfiguration());
82
Phil Burkd4ccc622017-12-20 15:32:44 -080083 aaudio_direction_t direction = getDirection();
84
85 const audio_content_type_t contentType =
86 AAudioConvert_contentTypeToInternal(getContentType());
Phil Burk55e5eab2018-04-10 15:16:38 -070087 // Usage only used for OUTPUT
Phil Burkd4ccc622017-12-20 15:32:44 -080088 const audio_usage_t usage = (direction == AAUDIO_DIRECTION_OUTPUT)
89 ? AAudioConvert_usageToInternal(getUsage())
90 : AUDIO_USAGE_UNKNOWN;
91 const audio_source_t source = (direction == AAUDIO_DIRECTION_INPUT)
92 ? AAudioConvert_inputPresetToAudioSource(getInputPreset())
93 : AUDIO_SOURCE_DEFAULT;
94
95 const audio_attributes_t attributes = {
96 .content_type = contentType,
97 .usage = usage,
98 .source = source,
99 .flags = AUDIO_FLAG_LOW_LATENCY,
100 .tags = ""
101 };
Phil Burk19e990e2018-03-22 13:59:34 -0700102 ALOGD("%s(%p) MMAP attributes.usage = %d, content_type = %d, source = %d",
103 __func__, this, attributes.usage, attributes.content_type, attributes.source);
Phil Burka62fb952018-01-16 12:44:06 -0800104
Phil Burk39f02dd2017-08-04 09:13:31 -0700105 mMmapClient.clientUid = request.getUserId();
106 mMmapClient.clientPid = request.getProcessId();
107 mMmapClient.packageName.setTo(String16(""));
108
109 mRequestedDeviceId = deviceId = getDeviceId();
110
111 // Fill in config
112 aaudio_format_t aaudioFormat = getFormat();
113 if (aaudioFormat == AAUDIO_UNSPECIFIED || aaudioFormat == AAUDIO_FORMAT_PCM_FLOAT) {
114 aaudioFormat = AAUDIO_FORMAT_PCM_I16;
115 }
116 config.format = AAudioConvert_aaudioToAndroidDataFormat(aaudioFormat);
117
118 int32_t aaudioSampleRate = getSampleRate();
119 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
120 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
121 }
122 config.sample_rate = aaudioSampleRate;
123
124 int32_t aaudioSamplesPerFrame = getSamplesPerFrame();
125
Phil Burk39f02dd2017-08-04 09:13:31 -0700126 if (direction == AAUDIO_DIRECTION_OUTPUT) {
127 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
128 ? AUDIO_CHANNEL_OUT_STEREO
129 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
130 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
131
132 } else if (direction == AAUDIO_DIRECTION_INPUT) {
133 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
134 ? AUDIO_CHANNEL_IN_STEREO
135 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
136 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
137
138 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700139 ALOGE("%s() invalid direction = %d", __func__, direction);
Phil Burk39f02dd2017-08-04 09:13:31 -0700140 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
141 }
142
143 MmapStreamInterface::stream_direction_t streamDirection =
144 (direction == AAUDIO_DIRECTION_OUTPUT)
145 ? MmapStreamInterface::DIRECTION_OUTPUT
146 : MmapStreamInterface::DIRECTION_INPUT;
147
Phil Burk4e1af9f2018-01-03 15:54:35 -0800148 aaudio_session_id_t requestedSessionId = getSessionId();
149 audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
150
Phil Burk39f02dd2017-08-04 09:13:31 -0700151 // Open HAL stream. Set mMmapStream
152 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
153 &attributes,
154 &config,
155 mMmapClient,
156 &deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800157 &sessionId,
Phil Burk39f02dd2017-08-04 09:13:31 -0700158 this, // callback
159 mMmapStream,
160 &mPortHandle);
Phil Burk19e990e2018-03-22 13:59:34 -0700161 ALOGD("%s() mMapClient.uid = %d, pid = %d => portHandle = %d\n",
162 __func__, mMmapClient.clientUid, mMmapClient.clientPid, mPortHandle);
Phil Burk39f02dd2017-08-04 09:13:31 -0700163 if (status != OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700164 ALOGE("%s() openMmapStream() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700165 return AAUDIO_ERROR_UNAVAILABLE;
166 }
167
168 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burk19e990e2018-03-22 13:59:34 -0700169 ALOGW("%s() openMmapStream() failed to set deviceId", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700170 }
171 setDeviceId(deviceId);
172
Phil Burk4e1af9f2018-01-03 15:54:35 -0800173 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700174 ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800175 }
176
177 aaudio_session_id_t actualSessionId =
178 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
179 ? AAUDIO_SESSION_ID_NONE
180 : (aaudio_session_id_t) sessionId;
181 setSessionId(actualSessionId);
Phil Burk19e990e2018-03-22 13:59:34 -0700182 ALOGD("%s() deviceId = %d, sessionId = %d", __func__, getDeviceId(), getSessionId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800183
Phil Burk39f02dd2017-08-04 09:13:31 -0700184 // Create MMAP/NOIRQ buffer.
185 int32_t minSizeFrames = getBufferCapacity();
186 if (minSizeFrames <= 0) { // zero will get rejected
187 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
188 }
189 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
190 if (status != OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700191 ALOGE("%s() - createMmapBuffer() failed with status %d %s",
192 __func__, status, strerror(-status));
Phil Burk39f02dd2017-08-04 09:13:31 -0700193 result = AAUDIO_ERROR_UNAVAILABLE;
194 goto error;
195 } else {
Phil Burk19e990e2018-03-22 13:59:34 -0700196 ALOGD("%s() createMmapBuffer() returned = %d, buffer_size = %d, burst_size %d"
Phil Burk39f02dd2017-08-04 09:13:31 -0700197 ", Sharable FD: %s",
Phil Burk19e990e2018-03-22 13:59:34 -0700198 __func__, status,
Phil Burk39f02dd2017-08-04 09:13:31 -0700199 abs(mMmapBufferinfo.buffer_size_frames),
200 mMmapBufferinfo.burst_size_frames,
201 mMmapBufferinfo.buffer_size_frames < 0 ? "Yes" : "No");
202 }
203
204 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
205 // The audio HAL indicates if the shared memory fd can be shared outside of audioserver
206 // by returning a negative buffer size
207 if (getBufferCapacity() < 0) {
208 // Exclusive mode can be used by client or service.
209 setBufferCapacity(-getBufferCapacity());
210 } else {
211 // Exclusive mode can only be used by the service because the FD cannot be shared.
212 uid_t audioServiceUid = getuid();
213 if ((mMmapClient.clientUid != audioServiceUid) &&
214 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
215 // Fallback is handled by caller but indicate what is possible in case
216 // this is used in the future
217 setSharingMode(AAUDIO_SHARING_MODE_SHARED);
Phil Burk19e990e2018-03-22 13:59:34 -0700218 ALOGW("%s() - exclusive FD cannot be used by client", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700219 result = AAUDIO_ERROR_UNAVAILABLE;
220 goto error;
221 }
222 }
223
224 // Get information about the stream and pass it back to the caller.
225 setSamplesPerFrame((direction == AAUDIO_DIRECTION_OUTPUT)
226 ? audio_channel_count_from_out_mask(config.channel_mask)
227 : audio_channel_count_from_in_mask(config.channel_mask));
228
229 // AAudio creates a copy of this FD and retains ownership of the copy.
230 // Assume that AudioFlinger will close the original shared_memory_fd.
231 mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
232 if (mAudioDataFileDescriptor.get() == -1) {
Phil Burk19e990e2018-03-22 13:59:34 -0700233 ALOGE("%s() - could not dup shared_memory_fd", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700234 result = AAUDIO_ERROR_INTERNAL;
235 goto error;
236 }
237 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
238 setFormat(AAudioConvert_androidToAAudioDataFormat(config.format));
239 setSampleRate(config.sample_rate);
240
241 // Scale up the burst size to meet the minimum equivalent in microseconds.
242 // This is to avoid waking the CPU too often when the HW burst is very small
243 // or at high sample rates.
244 do {
245 if (burstMicros > 0) { // skip first loop
246 mFramesPerBurst *= 2;
247 }
248 burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
249 } while (burstMicros < burstMinMicros);
250
Phil Burk19e990e2018-03-22 13:59:34 -0700251 ALOGD("%s() original burst = %d, minMicros = %d, to burst = %d\n",
252 __func__, mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
Phil Burk39f02dd2017-08-04 09:13:31 -0700253
Phil Burk19e990e2018-03-22 13:59:34 -0700254 ALOGD("%s() actual rate = %d, channels = %d"
Phil Burk39f02dd2017-08-04 09:13:31 -0700255 ", deviceId = %d, capacity = %d\n",
Phil Burk19e990e2018-03-22 13:59:34 -0700256 __func__, getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
Phil Burk39f02dd2017-08-04 09:13:31 -0700257
258 return result;
259
260error:
261 close();
262 return result;
263}
264
265aaudio_result_t AAudioServiceEndpointMMAP::close() {
Phil Burk39f02dd2017-08-04 09:13:31 -0700266 if (mMmapStream != 0) {
Phil Burk19e990e2018-03-22 13:59:34 -0700267 ALOGD("%s() clear() endpoint", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700268 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
269 mMmapStream.clear();
270 // Apparently the above close is asynchronous. An attempt to open a new device
271 // right after a close can fail. Also some callbacks may still be in flight!
272 // FIXME Make closing synchronous.
273 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
274 }
275
276 return AAUDIO_OK;
277}
278
279aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
280 audio_port_handle_t *clientHandle) {
Phil Burkbcc36742017-08-31 17:24:51 -0700281 // Start the client on behalf of the AAudio service.
282 // Use the port handle that was provided by openMmapStream().
Phil Burk39f02dd2017-08-04 09:13:31 -0700283 return startClient(mMmapClient, &mPortHandle);
284}
285
286aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
287 audio_port_handle_t clientHandle) {
288 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700289
290 // Round 64-bit counter up to a multiple of the buffer capacity.
291 // This is required because the 64-bit counter is used as an index
292 // into a circular buffer and the actual HW position is reset to zero
293 // when the stream is stopped.
294 mFramesTransferred.roundUp64(getBufferCapacity());
295
Phil Burk39f02dd2017-08-04 09:13:31 -0700296 return stopClient(mPortHandle);
297}
298
299aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
300 audio_port_handle_t *clientHandle) {
301 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burk19e990e2018-03-22 13:59:34 -0700302 ALOGV("%s(%p(uid=%d, pid=%d))", __func__, &client, client.clientUid, client.clientPid);
Phil Burk39f02dd2017-08-04 09:13:31 -0700303 audio_port_handle_t originalHandle = *clientHandle;
Phil Burkbcc36742017-08-31 17:24:51 -0700304 status_t status = mMmapStream->start(client, clientHandle);
305 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
Phil Burk19e990e2018-03-22 13:59:34 -0700306 ALOGV("%s() , %d => %d returns %d", __func__, originalHandle, *clientHandle, result);
Phil Burk39f02dd2017-08-04 09:13:31 -0700307 return result;
308}
309
310aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
311 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
312 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burk19e990e2018-03-22 13:59:34 -0700313 ALOGV("%s(%d) returns %d", __func__, clientHandle, result);
Phil Burk39f02dd2017-08-04 09:13:31 -0700314 return result;
315}
316
317// Get free-running DSP or DMA hardware position from the HAL.
318aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
319 int64_t *timeNanos) {
320 struct audio_mmap_position position;
321 if (mMmapStream == nullptr) {
322 return AAUDIO_ERROR_NULL;
323 }
324 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk19e990e2018-03-22 13:59:34 -0700325 ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
326 __func__, status, position.position_frames, (long long) position.time_nanoseconds);
Phil Burk39f02dd2017-08-04 09:13:31 -0700327 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
328 if (result == AAUDIO_ERROR_UNAVAILABLE) {
Phil Burk19e990e2018-03-22 13:59:34 -0700329 ALOGW("%s(): getMmapPosition() has no position data available", __func__);
Phil Burk39f02dd2017-08-04 09:13:31 -0700330 } else if (result != AAUDIO_OK) {
Phil Burk19e990e2018-03-22 13:59:34 -0700331 ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
Phil Burk39f02dd2017-08-04 09:13:31 -0700332 } else {
333 // Convert 32-bit position to 64-bit position.
334 mFramesTransferred.update32(position.position_frames);
335 *positionFrames = mFramesTransferred.get();
336 *timeNanos = position.time_nanoseconds;
337 }
338 return result;
339}
340
341aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
342 int64_t *timeNanos) {
343 return 0; // TODO
344}
345
346
Eric Laurenta2f478c2018-04-10 19:09:40 -0700347void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t handle __unused) {
Phil Burk19e990e2018-03-22 13:59:34 -0700348 ALOGD("%s(%p) called", __func__, this);
Eric Laurenta2f478c2018-04-10 19:09:40 -0700349 //TODO: disconnect only stream corresponding to handle received
Phil Burk39f02dd2017-08-04 09:13:31 -0700350 disconnectRegisteredStreams();
351};
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 Burk19e990e2018-03-22 13:59:34 -0700358 ALOGD("%s(%p) volume[0] = %f", __func__, this, volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700359 std::lock_guard<std::mutex> lock(mLockStreams);
360 for(const auto stream : mRegisteredStreams) {
361 stream->onVolumeChanged(volume);
362 }
363};
364
365void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
Phil Burk19e990e2018-03-22 13:59:34 -0700366 ALOGD("%s(%p) called with dev %d, old = %d", __func__, this, 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}