blob: da7cdf78457b89c1e8f82bde8ede736df0bab278 [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
17#define LOG_TAG "AAudioService"
18//#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
34using namespace android;
35using namespace aaudio;
36
37#define AAUDIO_BUFFER_CAPACITY_MIN 4 * 512
38#define AAUDIO_SAMPLE_RATE_DEFAULT 48000
39
40/**
Phil Burk11e8d332017-05-24 09:59:02 -070041 * Service Stream that uses an MMAP buffer.
Phil Burkc0c70e32017-02-09 13:18:38 -080042 */
43
Eric Laurentd51329e2017-06-30 16:06:16 -070044AAudioServiceStreamMMAP::AAudioServiceStreamMMAP(uid_t serviceUid)
Phil Burkc0c70e32017-02-09 13:18:38 -080045 : AAudioServiceStreamBase()
46 , mMmapStreamCallback(new MyMmapStreamCallback(*this))
47 , mPreviousFrameCounter(0)
Eric Laurentd51329e2017-06-30 16:06:16 -070048 , mMmapStream(nullptr)
49 , mCachedUserId(serviceUid) {
Phil Burkc0c70e32017-02-09 13:18:38 -080050}
51
52AAudioServiceStreamMMAP::~AAudioServiceStreamMMAP() {
53 close();
54}
55
56aaudio_result_t AAudioServiceStreamMMAP::close() {
Phil Burkc0c70e32017-02-09 13:18:38 -080057 mMmapStream.clear(); // TODO review. Is that all we have to do?
Phil Burk71f35bb2017-04-13 16:05:07 -070058 // Apparently the above close is asynchronous. An attempt to open a new device
59 // right after a close can fail. Also some callbacks may still be in flight!
60 // FIXME Make closing synchronous.
61 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
62
Phil Burk942bdc02017-05-03 11:36:50 -070063 if (mAudioDataFileDescriptor != -1) {
Phil Burk942bdc02017-05-03 11:36:50 -070064 ::close(mAudioDataFileDescriptor);
65 mAudioDataFileDescriptor = -1;
66 }
67
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();
91
Phil Burkc0c70e32017-02-09 13:18:38 -080092 mMmapClient.clientUid = request.getUserId();
93 mMmapClient.clientPid = request.getProcessId();
94 aaudio_direction_t direction = request.getDirection();
95
96 // Fill in config
Phil Burk9dca9822017-05-26 14:27:43 -070097 aaudio_format_t aaudioFormat = configurationInput.getAudioFormat();
Phil Burkc0c70e32017-02-09 13:18:38 -080098 if (aaudioFormat == AAUDIO_UNSPECIFIED || aaudioFormat == AAUDIO_FORMAT_PCM_FLOAT) {
Phil Burkc0c70e32017-02-09 13:18:38 -080099 aaudioFormat = AAUDIO_FORMAT_PCM_I16;
100 }
101 config.format = AAudioConvert_aaudioToAndroidDataFormat(aaudioFormat);
102
103 int32_t aaudioSampleRate = configurationInput.getSampleRate();
104 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
105 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
106 }
107 config.sample_rate = aaudioSampleRate;
108
109 int32_t aaudioSamplesPerFrame = configurationInput.getSamplesPerFrame();
110
111 if (direction == AAUDIO_DIRECTION_OUTPUT) {
112 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
113 ? AUDIO_CHANNEL_OUT_STEREO
114 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
115 } else if (direction == AAUDIO_DIRECTION_INPUT) {
116 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
117 ? AUDIO_CHANNEL_IN_STEREO
118 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
119 } else {
120 ALOGE("openMmapStream - invalid direction = %d", direction);
121 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
122 }
123
124 mMmapClient.packageName.setTo(String16("aaudio_service")); // FIXME what should we do here?
125
126 MmapStreamInterface::stream_direction_t streamDirection = (direction == AAUDIO_DIRECTION_OUTPUT)
127 ? MmapStreamInterface::DIRECTION_OUTPUT : MmapStreamInterface::DIRECTION_INPUT;
128
129 // Open HAL stream.
130 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
131 &attributes,
132 &config,
133 mMmapClient,
134 &deviceId,
135 mMmapStreamCallback,
136 mMmapStream);
137 if (status != OK) {
138 ALOGE("openMmapStream returned status %d", status);
139 return AAUDIO_ERROR_UNAVAILABLE;
140 }
141
Phil Burkec89b2e2017-06-20 15:05:06 -0700142 if (deviceId == AAUDIO_UNSPECIFIED) {
143 ALOGW("AAudioServiceStreamMMAP::open() - openMmapStream() failed to set deviceId");
144 }
145
Phil Burkc0c70e32017-02-09 13:18:38 -0800146 // Create MMAP/NOIRQ buffer.
147 int32_t minSizeFrames = configurationInput.getBufferCapacity();
Phil Burkec89b2e2017-06-20 15:05:06 -0700148 if (minSizeFrames <= 0) { // zero will get rejected
Phil Burkc0c70e32017-02-09 13:18:38 -0800149 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
150 }
151 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
152 if (status != OK) {
Phil Burkec89b2e2017-06-20 15:05:06 -0700153 ALOGE("AAudioServiceStreamMMAP::open() - createMmapBuffer() returned status %d",
154 status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800155 return AAUDIO_ERROR_UNAVAILABLE;
156 } else {
Eric Laurentd51329e2017-06-30 16:06:16 -0700157 ALOGD("createMmapBuffer status %d shared_address = %p buffer_size %d burst_size %d"
158 "Sharable FD: %s",
Phil Burkc0c70e32017-02-09 13:18:38 -0800159 status, mMmapBufferinfo.shared_memory_address,
Eric Laurentd51329e2017-06-30 16:06:16 -0700160 abs(mMmapBufferinfo.buffer_size_frames),
161 mMmapBufferinfo.burst_size_frames,
162 mMmapBufferinfo.buffer_size_frames < 0 ? "Yes" : "No");
163 }
164
165 mCapacityInFrames = mMmapBufferinfo.buffer_size_frames;
166 // FIXME: the audio HAL indicates if the shared memory fd can be shared outside of audioserver
167 // by returning a negative buffer size
168 if (mCapacityInFrames < 0) {
169 // Exclusive mode is possible from any client
170 mCapacityInFrames = -mCapacityInFrames;
171 } else {
172 // exclusive mode is only possible if the final fd destination is inside audioserver
173 if ((mMmapClient.clientUid != mCachedUserId) &&
174 configurationInput.getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
175 // Fallback is handled by caller but indicate what is possible in case
176 // this is used in the future
177 configurationOutput.setSharingMode(AAUDIO_SHARING_MODE_SHARED);
178 return AAUDIO_ERROR_UNAVAILABLE;
179 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800180 }
181
182 // Get information about the stream and pass it back to the caller.
183 mSamplesPerFrame = (direction == AAUDIO_DIRECTION_OUTPUT)
184 ? audio_channel_count_from_out_mask(config.channel_mask)
185 : audio_channel_count_from_in_mask(config.channel_mask);
186
187 mAudioDataFileDescriptor = mMmapBufferinfo.shared_memory_fd;
188 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
Phil Burkc0c70e32017-02-09 13:18:38 -0800189 mAudioFormat = AAudioConvert_androidToAAudioDataFormat(config.format);
190 mSampleRate = config.sample_rate;
191
Phil Burkc8f69a02017-05-11 15:53:06 -0700192 // Scale up the burst size to meet the minimum equivalent in microseconds.
193 // This is to avoid waking the CPU too often when the HW burst is very small
194 // or at high sample rates.
195 int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
196 int32_t burstMicros = 0;
197 do {
198 if (burstMicros > 0) { // skip first loop
199 mFramesPerBurst *= 2;
200 }
201 burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / mSampleRate;
202 } while (burstMicros < burstMinMicros);
203
204 ALOGD("AAudioServiceStreamMMAP::open() original burst = %d, minMicros = %d, final burst = %d\n",
205 mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
206
Phil Burkec89b2e2017-06-20 15:05:06 -0700207 ALOGD("AAudioServiceStreamMMAP::open() actual rate = %d, channels = %d, deviceId = %d\n",
208 mSampleRate, mSamplesPerFrame, deviceId);
209
Phil Burkc0c70e32017-02-09 13:18:38 -0800210 // Fill in AAudioStreamConfiguration
211 configurationOutput.setSampleRate(mSampleRate);
212 configurationOutput.setSamplesPerFrame(mSamplesPerFrame);
213 configurationOutput.setAudioFormat(mAudioFormat);
214 configurationOutput.setDeviceId(deviceId);
215
216 return AAUDIO_OK;
217}
218
Phil Burkc0c70e32017-02-09 13:18:38 -0800219/**
220 * Start the flow of data.
221 */
222aaudio_result_t AAudioServiceStreamMMAP::start() {
223 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burk87c9f642017-05-17 07:22:39 -0700224 aaudio_result_t result;
225 status_t status = mMmapStream->start(mMmapClient, &mPortHandle);
226 if (status != OK) {
227 ALOGE("AAudioServiceStreamMMAP::start() mMmapStream->start() returned %d", status);
Phil Burk5ef003b2017-06-30 11:43:37 -0700228 disconnect();
Phil Burk87c9f642017-05-17 07:22:39 -0700229 result = AAudioConvert_androidToAAudioResult(status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800230 } else {
231 result = AAudioServiceStreamBase::start();
232 }
233 return result;
234}
235
236/**
237 * Stop the flow of data such that start() can resume with loss of data.
238 */
239aaudio_result_t AAudioServiceStreamMMAP::pause() {
240 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
241
242 aaudio_result_t result1 = AAudioServiceStreamBase::pause();
Phil Burk87c9f642017-05-17 07:22:39 -0700243 status_t status = mMmapStream->stop(mPortHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800244 mFramesRead.reset32();
Phil Burk87c9f642017-05-17 07:22:39 -0700245 return (result1 != AAUDIO_OK) ? result1 : AAudioConvert_androidToAAudioResult(status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800246}
247
Phil Burk71f35bb2017-04-13 16:05:07 -0700248aaudio_result_t AAudioServiceStreamMMAP::stop() {
249 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
250
251 aaudio_result_t result1 = AAudioServiceStreamBase::stop();
Phil Burk87c9f642017-05-17 07:22:39 -0700252 aaudio_result_t status = mMmapStream->stop(mPortHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700253 mFramesRead.reset32();
Phil Burk87c9f642017-05-17 07:22:39 -0700254 return (result1 != AAUDIO_OK) ? result1 : AAudioConvert_androidToAAudioResult(status);
Phil Burk71f35bb2017-04-13 16:05:07 -0700255}
256
Phil Burkc0c70e32017-02-09 13:18:38 -0800257/**
258 * Discard any data held by the underlying HAL or Service.
259 */
260aaudio_result_t AAudioServiceStreamMMAP::flush() {
261 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
262 // TODO how do we flush an MMAP/NOIRQ buffer? sync pointers?
Phil Burk71f35bb2017-04-13 16:05:07 -0700263 return AAudioServiceStreamBase::flush();;
Phil Burkc0c70e32017-02-09 13:18:38 -0800264}
265
Phil Burkc0c70e32017-02-09 13:18:38 -0800266aaudio_result_t AAudioServiceStreamMMAP::getFreeRunningPosition(int64_t *positionFrames,
267 int64_t *timeNanos) {
268 struct audio_mmap_position position;
269 if (mMmapStream == nullptr) {
Phil Burk5ef003b2017-06-30 11:43:37 -0700270 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800271 return AAUDIO_ERROR_NULL;
272 }
273 status_t status = mMmapStream->getMmapPosition(&position);
274 if (status != OK) {
275 ALOGE("sendCurrentTimestamp(): getMmapPosition() returned %d", status);
Phil Burk5ef003b2017-06-30 11:43:37 -0700276 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800277 return AAudioConvert_androidToAAudioResult(status);
278 } else {
279 mFramesRead.update32(position.position_frames);
280 *positionFrames = mFramesRead.get();
281 *timeNanos = position.time_nanoseconds;
282 }
283 return AAUDIO_OK;
284}
285
286void AAudioServiceStreamMMAP::onTearDown() {
Phil Burk5ef003b2017-06-30 11:43:37 -0700287 ALOGD("AAudioServiceStreamMMAP::onTearDown() called");
288 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800289};
290
291void AAudioServiceStreamMMAP::onVolumeChanged(audio_channel_mask_t channels,
292 android::Vector<float> values) {
293 // TODO do we really need a different volume for each channel?
294 float volume = values[0];
295 ALOGD("AAudioServiceStreamMMAP::onVolumeChanged() volume[0] = %f", volume);
296 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
297};
298
299void AAudioServiceStreamMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
300 ALOGD("AAudioServiceStreamMMAP::onRoutingChanged() called with %d, old = %d",
301 deviceId, mPortHandle);
302 if (mPortHandle > 0 && mPortHandle != deviceId) {
Phil Burk5ef003b2017-06-30 11:43:37 -0700303 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800304 }
305 mPortHandle = deviceId;
306};
307
308/**
309 * Get an immutable description of the data queue from the HAL.
310 */
311aaudio_result_t AAudioServiceStreamMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
312{
313 // Gather information on the data queue based on HAL info.
314 int32_t bytesPerFrame = calculateBytesPerFrame();
315 int32_t capacityInBytes = mCapacityInFrames * bytesPerFrame;
316 int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
317 parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
318 parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
319 parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
320 parcelable.mDownDataQueueParcelable.setCapacityInFrames(mCapacityInFrames);
321 return AAUDIO_OK;
Phil Burkec89b2e2017-06-20 15:05:06 -0700322}