blob: 8db17612a45506ac2e52b21763438a9ccb7aba61 [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());
87 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;
93
94 const audio_attributes_t attributes = {
95 .content_type = contentType,
96 .usage = usage,
97 .source = source,
98 .flags = AUDIO_FLAG_LOW_LATENCY,
99 .tags = ""
100 };
Phil Burk39f02dd2017-08-04 09:13:31 -0700101 mMmapClient.clientUid = request.getUserId();
102 mMmapClient.clientPid = request.getProcessId();
103 mMmapClient.packageName.setTo(String16(""));
104
105 mRequestedDeviceId = deviceId = getDeviceId();
106
107 // Fill in config
108 aaudio_format_t aaudioFormat = getFormat();
109 if (aaudioFormat == AAUDIO_UNSPECIFIED || aaudioFormat == AAUDIO_FORMAT_PCM_FLOAT) {
110 aaudioFormat = AAUDIO_FORMAT_PCM_I16;
111 }
112 config.format = AAudioConvert_aaudioToAndroidDataFormat(aaudioFormat);
113
114 int32_t aaudioSampleRate = getSampleRate();
115 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
116 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
117 }
118 config.sample_rate = aaudioSampleRate;
119
120 int32_t aaudioSamplesPerFrame = getSamplesPerFrame();
121
Phil Burk39f02dd2017-08-04 09:13:31 -0700122 if (direction == AAUDIO_DIRECTION_OUTPUT) {
123 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
124 ? AUDIO_CHANNEL_OUT_STEREO
125 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
126 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
127
128 } else if (direction == AAUDIO_DIRECTION_INPUT) {
129 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
130 ? AUDIO_CHANNEL_IN_STEREO
131 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
132 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
133
134 } else {
135 ALOGE("openMmapStream - invalid direction = %d", direction);
136 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
137 }
138
139 MmapStreamInterface::stream_direction_t streamDirection =
140 (direction == AAUDIO_DIRECTION_OUTPUT)
141 ? MmapStreamInterface::DIRECTION_OUTPUT
142 : MmapStreamInterface::DIRECTION_INPUT;
143
144 // Open HAL stream. Set mMmapStream
145 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
146 &attributes,
147 &config,
148 mMmapClient,
149 &deviceId,
150 this, // callback
151 mMmapStream,
152 &mPortHandle);
Phil Burkfbf031e2017-10-12 15:58:31 -0700153 ALOGD("open() mMapClient.uid = %d, pid = %d => portHandle = %d\n",
Phil Burk39f02dd2017-08-04 09:13:31 -0700154 mMmapClient.clientUid, mMmapClient.clientPid, mPortHandle);
155 if (status != OK) {
156 ALOGE("openMmapStream returned status %d", status);
157 return AAUDIO_ERROR_UNAVAILABLE;
158 }
159
160 if (deviceId == AAUDIO_UNSPECIFIED) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700161 ALOGW("open() - openMmapStream() failed to set deviceId");
Phil Burk39f02dd2017-08-04 09:13:31 -0700162 }
163 setDeviceId(deviceId);
164
165 // Create MMAP/NOIRQ buffer.
166 int32_t minSizeFrames = getBufferCapacity();
167 if (minSizeFrames <= 0) { // zero will get rejected
168 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
169 }
170 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
171 if (status != OK) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700172 ALOGE("open() - createMmapBuffer() failed with status %d %s",
Phil Burk39f02dd2017-08-04 09:13:31 -0700173 status, strerror(-status));
174 result = AAUDIO_ERROR_UNAVAILABLE;
175 goto error;
176 } else {
177 ALOGD("createMmapBuffer status = %d, buffer_size = %d, burst_size %d"
178 ", Sharable FD: %s",
179 status,
180 abs(mMmapBufferinfo.buffer_size_frames),
181 mMmapBufferinfo.burst_size_frames,
182 mMmapBufferinfo.buffer_size_frames < 0 ? "Yes" : "No");
183 }
184
185 setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
186 // The audio HAL indicates if the shared memory fd can be shared outside of audioserver
187 // by returning a negative buffer size
188 if (getBufferCapacity() < 0) {
189 // Exclusive mode can be used by client or service.
190 setBufferCapacity(-getBufferCapacity());
191 } else {
192 // Exclusive mode can only be used by the service because the FD cannot be shared.
193 uid_t audioServiceUid = getuid();
194 if ((mMmapClient.clientUid != audioServiceUid) &&
195 getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
196 // Fallback is handled by caller but indicate what is possible in case
197 // this is used in the future
198 setSharingMode(AAUDIO_SHARING_MODE_SHARED);
Phil Burkfbf031e2017-10-12 15:58:31 -0700199 ALOGW("open() - exclusive FD cannot be used by client");
Phil Burk39f02dd2017-08-04 09:13:31 -0700200 result = AAUDIO_ERROR_UNAVAILABLE;
201 goto error;
202 }
203 }
204
205 // Get information about the stream and pass it back to the caller.
206 setSamplesPerFrame((direction == AAUDIO_DIRECTION_OUTPUT)
207 ? audio_channel_count_from_out_mask(config.channel_mask)
208 : audio_channel_count_from_in_mask(config.channel_mask));
209
210 // AAudio creates a copy of this FD and retains ownership of the copy.
211 // Assume that AudioFlinger will close the original shared_memory_fd.
212 mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
213 if (mAudioDataFileDescriptor.get() == -1) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700214 ALOGE("open() - could not dup shared_memory_fd");
Phil Burk39f02dd2017-08-04 09:13:31 -0700215 result = AAUDIO_ERROR_INTERNAL;
216 goto error;
217 }
218 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
219 setFormat(AAudioConvert_androidToAAudioDataFormat(config.format));
220 setSampleRate(config.sample_rate);
221
222 // Scale up the burst size to meet the minimum equivalent in microseconds.
223 // This is to avoid waking the CPU too often when the HW burst is very small
224 // or at high sample rates.
225 do {
226 if (burstMicros > 0) { // skip first loop
227 mFramesPerBurst *= 2;
228 }
229 burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
230 } while (burstMicros < burstMinMicros);
231
Phil Burkfbf031e2017-10-12 15:58:31 -0700232 ALOGD("open() original burst = %d, minMicros = %d, to burst = %d\n",
Phil Burk39f02dd2017-08-04 09:13:31 -0700233 mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
234
Phil Burkfbf031e2017-10-12 15:58:31 -0700235 ALOGD("open() actual rate = %d, channels = %d"
Phil Burk39f02dd2017-08-04 09:13:31 -0700236 ", deviceId = %d, capacity = %d\n",
237 getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
238
239 return result;
240
241error:
242 close();
243 return result;
244}
245
246aaudio_result_t AAudioServiceEndpointMMAP::close() {
247
248 if (mMmapStream != 0) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700249 ALOGD("close() clear() endpoint");
Phil Burk39f02dd2017-08-04 09:13:31 -0700250 // Needs to be explicitly cleared or CTS will fail but it is not clear why.
251 mMmapStream.clear();
252 // Apparently the above close is asynchronous. An attempt to open a new device
253 // right after a close can fail. Also some callbacks may still be in flight!
254 // FIXME Make closing synchronous.
255 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
256 }
257
258 return AAUDIO_OK;
259}
260
261aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
262 audio_port_handle_t *clientHandle) {
Phil Burkbcc36742017-08-31 17:24:51 -0700263 // Start the client on behalf of the AAudio service.
264 // Use the port handle that was provided by openMmapStream().
Phil Burk39f02dd2017-08-04 09:13:31 -0700265 return startClient(mMmapClient, &mPortHandle);
266}
267
268aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
269 audio_port_handle_t clientHandle) {
270 mFramesTransferred.reset32();
Phil Burk73af62a2017-10-26 12:11:47 -0700271
272 // Round 64-bit counter up to a multiple of the buffer capacity.
273 // This is required because the 64-bit counter is used as an index
274 // into a circular buffer and the actual HW position is reset to zero
275 // when the stream is stopped.
276 mFramesTransferred.roundUp64(getBufferCapacity());
277
Phil Burk39f02dd2017-08-04 09:13:31 -0700278 return stopClient(mPortHandle);
279}
280
281aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
282 audio_port_handle_t *clientHandle) {
283 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burkfbf031e2017-10-12 15:58:31 -0700284 ALOGD("startClient(%p(uid=%d, pid=%d))",
Phil Burkbcc36742017-08-31 17:24:51 -0700285 &client, client.clientUid, client.clientPid);
Phil Burk39f02dd2017-08-04 09:13:31 -0700286 audio_port_handle_t originalHandle = *clientHandle;
Phil Burkbcc36742017-08-31 17:24:51 -0700287 status_t status = mMmapStream->start(client, clientHandle);
288 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
Phil Burkfbf031e2017-10-12 15:58:31 -0700289 ALOGD("startClient() , %d => %d returns %d",
Phil Burk39f02dd2017-08-04 09:13:31 -0700290 originalHandle, *clientHandle, result);
291 return result;
292}
293
294aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
295 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
296 aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
Phil Burkfbf031e2017-10-12 15:58:31 -0700297 ALOGD("stopClient(%d) returns %d", clientHandle, result);
Phil Burk39f02dd2017-08-04 09:13:31 -0700298 return result;
299}
300
301// Get free-running DSP or DMA hardware position from the HAL.
302aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
303 int64_t *timeNanos) {
304 struct audio_mmap_position position;
305 if (mMmapStream == nullptr) {
306 return AAUDIO_ERROR_NULL;
307 }
308 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burkfbf031e2017-10-12 15:58:31 -0700309 ALOGV("getFreeRunningPosition() status= %d, pos = %d, nanos = %lld\n",
Phil Burk39f02dd2017-08-04 09:13:31 -0700310 status, position.position_frames, (long long) position.time_nanoseconds);
311 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
312 if (result == AAUDIO_ERROR_UNAVAILABLE) {
313 ALOGW("sendCurrentTimestamp(): getMmapPosition() has no position data available");
314 } else if (result != AAUDIO_OK) {
315 ALOGE("sendCurrentTimestamp(): getMmapPosition() returned status %d", status);
316 } else {
317 // Convert 32-bit position to 64-bit position.
318 mFramesTransferred.update32(position.position_frames);
319 *positionFrames = mFramesTransferred.get();
320 *timeNanos = position.time_nanoseconds;
321 }
322 return result;
323}
324
325aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
326 int64_t *timeNanos) {
327 return 0; // TODO
328}
329
330
331void AAudioServiceEndpointMMAP::onTearDown() {
Phil Burkfbf031e2017-10-12 15:58:31 -0700332 ALOGD("onTearDown() called");
Phil Burk39f02dd2017-08-04 09:13:31 -0700333 disconnectRegisteredStreams();
334};
335
336void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
337 android::Vector<float> values) {
338 // TODO do we really need a different volume for each channel?
339 float volume = values[0];
Phil Burkfbf031e2017-10-12 15:58:31 -0700340 ALOGD("onVolumeChanged() volume[0] = %f", volume);
Phil Burk39f02dd2017-08-04 09:13:31 -0700341 std::lock_guard<std::mutex> lock(mLockStreams);
342 for(const auto stream : mRegisteredStreams) {
343 stream->onVolumeChanged(volume);
344 }
345};
346
347void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700348 ALOGD("onRoutingChanged() called with dev %d, old = %d",
Phil Burk39f02dd2017-08-04 09:13:31 -0700349 deviceId, getDeviceId());
350 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}