blob: 08dd680f37e884cf3d62d84bfe6630d3ff9712d3 [file] [log] [blame]
Phil Burkc0c70e32017-02-09 13:18:38 -08001/*
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
Eric Laurentcb4dae22017-07-01 19:39:32 -070017#define LOG_TAG "AAudioServiceStreamMMAP"
Phil Burkc0c70e32017-02-09 13:18:38 -080018//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <atomic>
22#include <stdint.h>
23
24#include <utils/String16.h>
25#include <media/nbaio/AudioStreamOutSink.h>
26#include <media/MmapStreamInterface.h>
27
28#include "AAudioServiceStreamBase.h"
29#include "AAudioServiceStreamMMAP.h"
30#include "binding/AudioEndpointParcelable.h"
31#include "SharedMemoryProxy.h"
32#include "utility/AAudioUtilities.h"
33
Phil Burk37417522017-08-08 13:20:45 -070034using android::base::unique_fd;
Phil Burkc0c70e32017-02-09 13:18:38 -080035using namespace android;
36using namespace aaudio;
37
38#define AAUDIO_BUFFER_CAPACITY_MIN 4 * 512
39#define AAUDIO_SAMPLE_RATE_DEFAULT 48000
40
41/**
Phil Burk11e8d332017-05-24 09:59:02 -070042 * Service Stream that uses an MMAP buffer.
Phil Burkc0c70e32017-02-09 13:18:38 -080043 */
44
Eric Laurentcb4dae22017-07-01 19:39:32 -070045AAudioServiceStreamMMAP::AAudioServiceStreamMMAP(const android::AudioClient& serviceClient,
46 bool inService)
Phil Burkc0c70e32017-02-09 13:18:38 -080047 : AAudioServiceStreamBase()
48 , mMmapStreamCallback(new MyMmapStreamCallback(*this))
49 , mPreviousFrameCounter(0)
Eric Laurentd51329e2017-06-30 16:06:16 -070050 , mMmapStream(nullptr)
Eric Laurentcb4dae22017-07-01 19:39:32 -070051 , mServiceClient(serviceClient)
52 , mInService(inService) {
Phil Burkc0c70e32017-02-09 13:18:38 -080053}
54
Phil Burkc0c70e32017-02-09 13:18:38 -080055aaudio_result_t AAudioServiceStreamMMAP::close() {
Phil Burk98d6d922017-07-06 11:52:45 -070056 if (mState == AAUDIO_STREAM_STATE_CLOSED) {
57 return AAUDIO_OK;
58 }
Eric Laurentcb4dae22017-07-01 19:39:32 -070059 stop();
Phil Burk98d6d922017-07-06 11:52:45 -070060 if (mMmapStream != 0) {
61 mMmapStream.clear(); // TODO review. Is that all we have to do?
62 // Apparently the above close is asynchronous. An attempt to open a new device
63 // right after a close can fail. Also some callbacks may still be in flight!
64 // FIXME Make closing synchronous.
65 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
66 }
Phil Burk71f35bb2017-04-13 16:05:07 -070067
Phil Burkc0c70e32017-02-09 13:18:38 -080068 return AAudioServiceStreamBase::close();
69}
70
71// Open stream on HAL and pass information about the shared memory buffer back to the client.
72aaudio_result_t AAudioServiceStreamMMAP::open(const aaudio::AAudioStreamRequest &request,
73 aaudio::AAudioStreamConfiguration &configurationOutput) {
74 const audio_attributes_t attributes = {
75 .content_type = AUDIO_CONTENT_TYPE_MUSIC,
76 .usage = AUDIO_USAGE_MEDIA,
Phil Burk87c9f642017-05-17 07:22:39 -070077 .source = AUDIO_SOURCE_VOICE_RECOGNITION,
Phil Burkc0c70e32017-02-09 13:18:38 -080078 .flags = AUDIO_FLAG_LOW_LATENCY,
79 .tags = ""
80 };
81 audio_config_base_t config;
82
83 aaudio_result_t result = AAudioServiceStreamBase::open(request, configurationOutput);
84 if (result != AAUDIO_OK) {
85 ALOGE("AAudioServiceStreamBase open returned %d", result);
86 return result;
87 }
88
89 const AAudioStreamConfiguration &configurationInput = request.getConstantConfiguration();
90 audio_port_handle_t deviceId = configurationInput.getDeviceId();
Phil Burkc0c70e32017-02-09 13:18:38 -080091 aaudio_direction_t direction = request.getDirection();
92
93 // Fill in config
jiabin901f65d2017-07-12 17:56:35 -070094 aaudio_format_t aaudioFormat = configurationInput.getFormat();
Phil Burkc0c70e32017-02-09 13:18:38 -080095 if (aaudioFormat == AAUDIO_UNSPECIFIED || aaudioFormat == AAUDIO_FORMAT_PCM_FLOAT) {
Phil Burkc0c70e32017-02-09 13:18:38 -080096 aaudioFormat = AAUDIO_FORMAT_PCM_I16;
97 }
98 config.format = AAudioConvert_aaudioToAndroidDataFormat(aaudioFormat);
99
100 int32_t aaudioSampleRate = configurationInput.getSampleRate();
101 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
102 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
103 }
104 config.sample_rate = aaudioSampleRate;
105
106 int32_t aaudioSamplesPerFrame = configurationInput.getSamplesPerFrame();
107
108 if (direction == AAUDIO_DIRECTION_OUTPUT) {
109 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
110 ? AUDIO_CHANNEL_OUT_STEREO
111 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
112 } else if (direction == AAUDIO_DIRECTION_INPUT) {
113 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
114 ? AUDIO_CHANNEL_IN_STEREO
115 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
116 } else {
117 ALOGE("openMmapStream - invalid direction = %d", direction);
118 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
119 }
120
Phil Burkc0c70e32017-02-09 13:18:38 -0800121 MmapStreamInterface::stream_direction_t streamDirection = (direction == AAUDIO_DIRECTION_OUTPUT)
122 ? MmapStreamInterface::DIRECTION_OUTPUT : MmapStreamInterface::DIRECTION_INPUT;
123
124 // Open HAL stream.
125 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
126 &attributes,
127 &config,
128 mMmapClient,
129 &deviceId,
130 mMmapStreamCallback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700131 mMmapStream,
132 &mPortHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800133 if (status != OK) {
134 ALOGE("openMmapStream returned status %d", status);
135 return AAUDIO_ERROR_UNAVAILABLE;
136 }
137
Phil Burkec89b2e2017-06-20 15:05:06 -0700138 if (deviceId == AAUDIO_UNSPECIFIED) {
139 ALOGW("AAudioServiceStreamMMAP::open() - openMmapStream() failed to set deviceId");
140 }
141
Phil Burkc0c70e32017-02-09 13:18:38 -0800142 // Create MMAP/NOIRQ buffer.
143 int32_t minSizeFrames = configurationInput.getBufferCapacity();
Phil Burkec89b2e2017-06-20 15:05:06 -0700144 if (minSizeFrames <= 0) { // zero will get rejected
Phil Burkc0c70e32017-02-09 13:18:38 -0800145 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
146 }
147 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
148 if (status != OK) {
Phil Burkec89b2e2017-06-20 15:05:06 -0700149 ALOGE("AAudioServiceStreamMMAP::open() - createMmapBuffer() returned status %d",
150 status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800151 return AAUDIO_ERROR_UNAVAILABLE;
152 } else {
Phil Burkfd34a932017-07-19 07:03:52 -0700153 ALOGD("createMmapBuffer status = %d, buffer_size = %d, burst_size %d"
Phil Burkc7abac42017-07-17 11:13:37 -0700154 ", Sharable FD: %s",
155 status,
Eric Laurentd51329e2017-06-30 16:06:16 -0700156 abs(mMmapBufferinfo.buffer_size_frames),
157 mMmapBufferinfo.burst_size_frames,
158 mMmapBufferinfo.buffer_size_frames < 0 ? "Yes" : "No");
159 }
160
161 mCapacityInFrames = mMmapBufferinfo.buffer_size_frames;
162 // FIXME: the audio HAL indicates if the shared memory fd can be shared outside of audioserver
163 // by returning a negative buffer size
164 if (mCapacityInFrames < 0) {
165 // Exclusive mode is possible from any client
166 mCapacityInFrames = -mCapacityInFrames;
167 } else {
168 // exclusive mode is only possible if the final fd destination is inside audioserver
Eric Laurentcb4dae22017-07-01 19:39:32 -0700169 if ((mMmapClient.clientUid != mServiceClient.clientUid) &&
Eric Laurentd51329e2017-06-30 16:06:16 -0700170 configurationInput.getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
171 // Fallback is handled by caller but indicate what is possible in case
172 // this is used in the future
173 configurationOutput.setSharingMode(AAUDIO_SHARING_MODE_SHARED);
174 return AAUDIO_ERROR_UNAVAILABLE;
175 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800176 }
177
178 // Get information about the stream and pass it back to the caller.
179 mSamplesPerFrame = (direction == AAUDIO_DIRECTION_OUTPUT)
180 ? audio_channel_count_from_out_mask(config.channel_mask)
181 : audio_channel_count_from_in_mask(config.channel_mask);
182
Phil Burk37417522017-08-08 13:20:45 -0700183 // AAudio creates a copy of this FD and retains ownership of the copy.
184 // Assume that AudioFlinger will close the original shared_memory_fd.
185 mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
186 if (mAudioDataFileDescriptor.get() == -1) {
187 ALOGE("AAudioServiceStreamMMAP::open() - could not dup shared_memory_fd");
188 return AAUDIO_ERROR_INTERNAL; // TODO review
189 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800190 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
Phil Burkc0c70e32017-02-09 13:18:38 -0800191 mAudioFormat = AAudioConvert_androidToAAudioDataFormat(config.format);
192 mSampleRate = config.sample_rate;
193
Phil Burkc8f69a02017-05-11 15:53:06 -0700194 // Scale up the burst size to meet the minimum equivalent in microseconds.
195 // This is to avoid waking the CPU too often when the HW burst is very small
196 // or at high sample rates.
197 int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
198 int32_t burstMicros = 0;
199 do {
200 if (burstMicros > 0) { // skip first loop
201 mFramesPerBurst *= 2;
202 }
203 burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / mSampleRate;
204 } while (burstMicros < burstMinMicros);
205
206 ALOGD("AAudioServiceStreamMMAP::open() original burst = %d, minMicros = %d, final burst = %d\n",
207 mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
208
Phil Burkec89b2e2017-06-20 15:05:06 -0700209 ALOGD("AAudioServiceStreamMMAP::open() actual rate = %d, channels = %d, deviceId = %d\n",
210 mSampleRate, mSamplesPerFrame, deviceId);
211
Phil Burkc0c70e32017-02-09 13:18:38 -0800212 // Fill in AAudioStreamConfiguration
213 configurationOutput.setSampleRate(mSampleRate);
214 configurationOutput.setSamplesPerFrame(mSamplesPerFrame);
jiabin901f65d2017-07-12 17:56:35 -0700215 configurationOutput.setFormat(mAudioFormat);
Phil Burkc0c70e32017-02-09 13:18:38 -0800216 configurationOutput.setDeviceId(deviceId);
217
Phil Burk5a26e662017-07-07 12:44:48 -0700218 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burkc0c70e32017-02-09 13:18:38 -0800219 return AAUDIO_OK;
220}
221
Phil Burkc0c70e32017-02-09 13:18:38 -0800222/**
223 * Start the flow of data.
224 */
225aaudio_result_t AAudioServiceStreamMMAP::start() {
Eric Laurentcb4dae22017-07-01 19:39:32 -0700226 if (isRunning()) {
227 return AAUDIO_OK;
228 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800229 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burk87c9f642017-05-17 07:22:39 -0700230 aaudio_result_t result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700231 status_t status = mMmapStream->start(mServiceClient, &mPortHandle);
Phil Burk87c9f642017-05-17 07:22:39 -0700232 if (status != OK) {
233 ALOGE("AAudioServiceStreamMMAP::start() mMmapStream->start() returned %d", status);
Phil Burk5ef003b2017-06-30 11:43:37 -0700234 disconnect();
Phil Burk87c9f642017-05-17 07:22:39 -0700235 result = AAudioConvert_androidToAAudioResult(status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800236 } else {
237 result = AAudioServiceStreamBase::start();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700238 if (!mInService && result == AAUDIO_OK) {
239 startClient(mMmapClient, &mClientHandle);
240 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800241 }
242 return result;
243}
244
245/**
246 * Stop the flow of data such that start() can resume with loss of data.
247 */
248aaudio_result_t AAudioServiceStreamMMAP::pause() {
Eric Laurentcb4dae22017-07-01 19:39:32 -0700249 if (!isRunning()) {
250 return AAUDIO_OK;
251 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800252 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burkc0c70e32017-02-09 13:18:38 -0800253 aaudio_result_t result1 = AAudioServiceStreamBase::pause();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700254 if (!mInService) {
255 stopClient(mClientHandle);
256 }
Phil Burk87c9f642017-05-17 07:22:39 -0700257 status_t status = mMmapStream->stop(mPortHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800258 mFramesRead.reset32();
Phil Burk87c9f642017-05-17 07:22:39 -0700259 return (result1 != AAUDIO_OK) ? result1 : AAudioConvert_androidToAAudioResult(status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800260}
261
Phil Burk71f35bb2017-04-13 16:05:07 -0700262aaudio_result_t AAudioServiceStreamMMAP::stop() {
Eric Laurentcb4dae22017-07-01 19:39:32 -0700263 if (!isRunning()) {
264 return AAUDIO_OK;
265 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700266 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burk71f35bb2017-04-13 16:05:07 -0700267 aaudio_result_t result1 = AAudioServiceStreamBase::stop();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700268 if (!mInService) {
269 stopClient(mClientHandle);
270 }
Phil Burk87c9f642017-05-17 07:22:39 -0700271 aaudio_result_t status = mMmapStream->stop(mPortHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700272 mFramesRead.reset32();
Phil Burk87c9f642017-05-17 07:22:39 -0700273 return (result1 != AAUDIO_OK) ? result1 : AAudioConvert_androidToAAudioResult(status);
Phil Burk71f35bb2017-04-13 16:05:07 -0700274}
275
Phil Burkc0c70e32017-02-09 13:18:38 -0800276/**
277 * Discard any data held by the underlying HAL or Service.
278 */
279aaudio_result_t AAudioServiceStreamMMAP::flush() {
280 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
281 // TODO how do we flush an MMAP/NOIRQ buffer? sync pointers?
Phil Burk71f35bb2017-04-13 16:05:07 -0700282 return AAudioServiceStreamBase::flush();;
Phil Burkc0c70e32017-02-09 13:18:38 -0800283}
284
Eric Laurentcb4dae22017-07-01 19:39:32 -0700285aaudio_result_t AAudioServiceStreamMMAP::startClient(const android::AudioClient& client,
286 audio_port_handle_t *clientHandle) {
287 return AAudioConvert_androidToAAudioResult(mMmapStream->start(client, clientHandle));
288}
289
290aaudio_result_t AAudioServiceStreamMMAP::stopClient(audio_port_handle_t clientHandle) {
291 return AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
292}
293
Phil Burkc0c70e32017-02-09 13:18:38 -0800294aaudio_result_t AAudioServiceStreamMMAP::getFreeRunningPosition(int64_t *positionFrames,
295 int64_t *timeNanos) {
296 struct audio_mmap_position position;
297 if (mMmapStream == nullptr) {
Phil Burk5ef003b2017-06-30 11:43:37 -0700298 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800299 return AAUDIO_ERROR_NULL;
300 }
301 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk940083c2017-07-17 17:00:02 -0700302 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
303 if (result == AAUDIO_ERROR_UNAVAILABLE) {
304 ALOGW("sendCurrentTimestamp(): getMmapPosition() has no position data yet");
305 } else if (result != AAUDIO_OK) {
306 ALOGE("sendCurrentTimestamp(): getMmapPosition() returned status %d", status);
Phil Burk5ef003b2017-06-30 11:43:37 -0700307 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800308 } else {
309 mFramesRead.update32(position.position_frames);
310 *positionFrames = mFramesRead.get();
311 *timeNanos = position.time_nanoseconds;
312 }
Phil Burk940083c2017-07-17 17:00:02 -0700313 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800314}
315
316void AAudioServiceStreamMMAP::onTearDown() {
Phil Burk5ef003b2017-06-30 11:43:37 -0700317 ALOGD("AAudioServiceStreamMMAP::onTearDown() called");
318 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800319};
320
321void AAudioServiceStreamMMAP::onVolumeChanged(audio_channel_mask_t channels,
322 android::Vector<float> values) {
323 // TODO do we really need a different volume for each channel?
324 float volume = values[0];
325 ALOGD("AAudioServiceStreamMMAP::onVolumeChanged() volume[0] = %f", volume);
326 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
327};
328
329void AAudioServiceStreamMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
330 ALOGD("AAudioServiceStreamMMAP::onRoutingChanged() called with %d, old = %d",
Eric Laurentcb4dae22017-07-01 19:39:32 -0700331 deviceId, mDeviceId);
332 if (mDeviceId != AUDIO_PORT_HANDLE_NONE && mDeviceId != deviceId) {
Phil Burk5ef003b2017-06-30 11:43:37 -0700333 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800334 }
Eric Laurentcb4dae22017-07-01 19:39:32 -0700335 mDeviceId = deviceId;
Phil Burkc0c70e32017-02-09 13:18:38 -0800336};
337
338/**
339 * Get an immutable description of the data queue from the HAL.
340 */
341aaudio_result_t AAudioServiceStreamMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
342{
343 // Gather information on the data queue based on HAL info.
344 int32_t bytesPerFrame = calculateBytesPerFrame();
345 int32_t capacityInBytes = mCapacityInFrames * bytesPerFrame;
346 int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
347 parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
348 parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
349 parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
350 parcelable.mDownDataQueueParcelable.setCapacityInFrames(mCapacityInFrames);
351 return AAUDIO_OK;
Phil Burkec89b2e2017-06-20 15:05:06 -0700352}