blob: 970d734e60903d61843065d6a1cfe2c4ac887492 [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
34using namespace android;
35using namespace aaudio;
36
37#define AAUDIO_BUFFER_CAPACITY_MIN 4 * 512
38#define AAUDIO_SAMPLE_RATE_DEFAULT 48000
39
Phil Burk97350f92017-07-21 15:59:44 -070040// This is an estimate of the time difference between the HW and the MMAP time.
41// TODO Get presentation timestamps from the HAL instead of using these estimates.
42#define OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (3 * AAUDIO_NANOS_PER_MILLISECOND)
43#define INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS (-1 * AAUDIO_NANOS_PER_MILLISECOND)
44
Phil Burkc0c70e32017-02-09 13:18:38 -080045/**
Phil Burk11e8d332017-05-24 09:59:02 -070046 * Service Stream that uses an MMAP buffer.
Phil Burkc0c70e32017-02-09 13:18:38 -080047 */
48
Eric Laurentcb4dae22017-07-01 19:39:32 -070049AAudioServiceStreamMMAP::AAudioServiceStreamMMAP(const android::AudioClient& serviceClient,
50 bool inService)
Phil Burkc0c70e32017-02-09 13:18:38 -080051 : AAudioServiceStreamBase()
52 , mMmapStreamCallback(new MyMmapStreamCallback(*this))
53 , mPreviousFrameCounter(0)
Eric Laurentd51329e2017-06-30 16:06:16 -070054 , mMmapStream(nullptr)
Eric Laurentcb4dae22017-07-01 19:39:32 -070055 , mServiceClient(serviceClient)
56 , mInService(inService) {
Phil Burkc0c70e32017-02-09 13:18:38 -080057}
58
Phil Burkc0c70e32017-02-09 13:18:38 -080059aaudio_result_t AAudioServiceStreamMMAP::close() {
Phil Burk98d6d922017-07-06 11:52:45 -070060 if (mState == AAUDIO_STREAM_STATE_CLOSED) {
61 return AAUDIO_OK;
62 }
Eric Laurentcb4dae22017-07-01 19:39:32 -070063 stop();
Phil Burk98d6d922017-07-06 11:52:45 -070064 if (mMmapStream != 0) {
65 mMmapStream.clear(); // TODO review. Is that all we have to do?
66 // Apparently the above close is asynchronous. An attempt to open a new device
67 // right after a close can fail. Also some callbacks may still be in flight!
68 // FIXME Make closing synchronous.
69 AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
70 }
Phil Burk71f35bb2017-04-13 16:05:07 -070071
Phil Burk942bdc02017-05-03 11:36:50 -070072 if (mAudioDataFileDescriptor != -1) {
Phil Burk942bdc02017-05-03 11:36:50 -070073 ::close(mAudioDataFileDescriptor);
74 mAudioDataFileDescriptor = -1;
75 }
76
Phil Burkc0c70e32017-02-09 13:18:38 -080077 return AAudioServiceStreamBase::close();
78}
79
80// Open stream on HAL and pass information about the shared memory buffer back to the client.
81aaudio_result_t AAudioServiceStreamMMAP::open(const aaudio::AAudioStreamRequest &request,
82 aaudio::AAudioStreamConfiguration &configurationOutput) {
83 const audio_attributes_t attributes = {
84 .content_type = AUDIO_CONTENT_TYPE_MUSIC,
85 .usage = AUDIO_USAGE_MEDIA,
Phil Burk87c9f642017-05-17 07:22:39 -070086 .source = AUDIO_SOURCE_VOICE_RECOGNITION,
Phil Burkc0c70e32017-02-09 13:18:38 -080087 .flags = AUDIO_FLAG_LOW_LATENCY,
88 .tags = ""
89 };
90 audio_config_base_t config;
91
92 aaudio_result_t result = AAudioServiceStreamBase::open(request, configurationOutput);
93 if (result != AAUDIO_OK) {
94 ALOGE("AAudioServiceStreamBase open returned %d", result);
95 return result;
96 }
97
98 const AAudioStreamConfiguration &configurationInput = request.getConstantConfiguration();
99 audio_port_handle_t deviceId = configurationInput.getDeviceId();
Phil Burkc0c70e32017-02-09 13:18:38 -0800100 aaudio_direction_t direction = request.getDirection();
101
102 // Fill in config
jiabin901f65d2017-07-12 17:56:35 -0700103 aaudio_format_t aaudioFormat = configurationInput.getFormat();
Phil Burkc0c70e32017-02-09 13:18:38 -0800104 if (aaudioFormat == AAUDIO_UNSPECIFIED || aaudioFormat == AAUDIO_FORMAT_PCM_FLOAT) {
Phil Burkc0c70e32017-02-09 13:18:38 -0800105 aaudioFormat = AAUDIO_FORMAT_PCM_I16;
106 }
107 config.format = AAudioConvert_aaudioToAndroidDataFormat(aaudioFormat);
108
109 int32_t aaudioSampleRate = configurationInput.getSampleRate();
110 if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
111 aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
112 }
113 config.sample_rate = aaudioSampleRate;
114
115 int32_t aaudioSamplesPerFrame = configurationInput.getSamplesPerFrame();
116
117 if (direction == AAUDIO_DIRECTION_OUTPUT) {
118 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
119 ? AUDIO_CHANNEL_OUT_STEREO
120 : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
Phil Burk97350f92017-07-21 15:59:44 -0700121 mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
122
Phil Burkc0c70e32017-02-09 13:18:38 -0800123 } else if (direction == AAUDIO_DIRECTION_INPUT) {
124 config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
125 ? AUDIO_CHANNEL_IN_STEREO
126 : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
Phil Burk97350f92017-07-21 15:59:44 -0700127 mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
128
Phil Burkc0c70e32017-02-09 13:18:38 -0800129 } else {
130 ALOGE("openMmapStream - invalid direction = %d", direction);
131 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
132 }
133
Phil Burkc0c70e32017-02-09 13:18:38 -0800134 MmapStreamInterface::stream_direction_t streamDirection = (direction == AAUDIO_DIRECTION_OUTPUT)
135 ? MmapStreamInterface::DIRECTION_OUTPUT : MmapStreamInterface::DIRECTION_INPUT;
136
137 // Open HAL stream.
138 status_t status = MmapStreamInterface::openMmapStream(streamDirection,
139 &attributes,
140 &config,
141 mMmapClient,
142 &deviceId,
143 mMmapStreamCallback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700144 mMmapStream,
145 &mPortHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800146 if (status != OK) {
147 ALOGE("openMmapStream returned status %d", status);
148 return AAUDIO_ERROR_UNAVAILABLE;
149 }
150
Phil Burkec89b2e2017-06-20 15:05:06 -0700151 if (deviceId == AAUDIO_UNSPECIFIED) {
152 ALOGW("AAudioServiceStreamMMAP::open() - openMmapStream() failed to set deviceId");
153 }
154
Phil Burkc0c70e32017-02-09 13:18:38 -0800155 // Create MMAP/NOIRQ buffer.
156 int32_t minSizeFrames = configurationInput.getBufferCapacity();
Phil Burkec89b2e2017-06-20 15:05:06 -0700157 if (minSizeFrames <= 0) { // zero will get rejected
Phil Burkc0c70e32017-02-09 13:18:38 -0800158 minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
159 }
160 status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
161 if (status != OK) {
Phil Burkec89b2e2017-06-20 15:05:06 -0700162 ALOGE("AAudioServiceStreamMMAP::open() - createMmapBuffer() returned status %d",
163 status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800164 return AAUDIO_ERROR_UNAVAILABLE;
165 } else {
Phil Burkfd34a932017-07-19 07:03:52 -0700166 ALOGD("createMmapBuffer status = %d, buffer_size = %d, burst_size %d"
Phil Burkc7abac42017-07-17 11:13:37 -0700167 ", Sharable FD: %s",
168 status,
Eric Laurentd51329e2017-06-30 16:06:16 -0700169 abs(mMmapBufferinfo.buffer_size_frames),
170 mMmapBufferinfo.burst_size_frames,
171 mMmapBufferinfo.buffer_size_frames < 0 ? "Yes" : "No");
172 }
173
174 mCapacityInFrames = mMmapBufferinfo.buffer_size_frames;
175 // FIXME: the audio HAL indicates if the shared memory fd can be shared outside of audioserver
176 // by returning a negative buffer size
177 if (mCapacityInFrames < 0) {
178 // Exclusive mode is possible from any client
179 mCapacityInFrames = -mCapacityInFrames;
180 } else {
181 // exclusive mode is only possible if the final fd destination is inside audioserver
Eric Laurentcb4dae22017-07-01 19:39:32 -0700182 if ((mMmapClient.clientUid != mServiceClient.clientUid) &&
Eric Laurentd51329e2017-06-30 16:06:16 -0700183 configurationInput.getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
184 // Fallback is handled by caller but indicate what is possible in case
185 // this is used in the future
186 configurationOutput.setSharingMode(AAUDIO_SHARING_MODE_SHARED);
187 return AAUDIO_ERROR_UNAVAILABLE;
188 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800189 }
190
191 // Get information about the stream and pass it back to the caller.
192 mSamplesPerFrame = (direction == AAUDIO_DIRECTION_OUTPUT)
193 ? audio_channel_count_from_out_mask(config.channel_mask)
194 : audio_channel_count_from_in_mask(config.channel_mask);
195
196 mAudioDataFileDescriptor = mMmapBufferinfo.shared_memory_fd;
197 mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
Phil Burkc0c70e32017-02-09 13:18:38 -0800198 mAudioFormat = AAudioConvert_androidToAAudioDataFormat(config.format);
199 mSampleRate = config.sample_rate;
200
Phil Burkc8f69a02017-05-11 15:53:06 -0700201 // Scale up the burst size to meet the minimum equivalent in microseconds.
202 // This is to avoid waking the CPU too often when the HW burst is very small
203 // or at high sample rates.
204 int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
205 int32_t burstMicros = 0;
206 do {
207 if (burstMicros > 0) { // skip first loop
208 mFramesPerBurst *= 2;
209 }
210 burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / mSampleRate;
211 } while (burstMicros < burstMinMicros);
212
213 ALOGD("AAudioServiceStreamMMAP::open() original burst = %d, minMicros = %d, final burst = %d\n",
214 mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
215
Phil Burkec89b2e2017-06-20 15:05:06 -0700216 ALOGD("AAudioServiceStreamMMAP::open() actual rate = %d, channels = %d, deviceId = %d\n",
217 mSampleRate, mSamplesPerFrame, deviceId);
218
Phil Burkc0c70e32017-02-09 13:18:38 -0800219 // Fill in AAudioStreamConfiguration
220 configurationOutput.setSampleRate(mSampleRate);
221 configurationOutput.setSamplesPerFrame(mSamplesPerFrame);
jiabin901f65d2017-07-12 17:56:35 -0700222 configurationOutput.setFormat(mAudioFormat);
Phil Burkc0c70e32017-02-09 13:18:38 -0800223 configurationOutput.setDeviceId(deviceId);
224
Phil Burk5a26e662017-07-07 12:44:48 -0700225 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burkc0c70e32017-02-09 13:18:38 -0800226 return AAUDIO_OK;
227}
228
Phil Burkc0c70e32017-02-09 13:18:38 -0800229/**
230 * Start the flow of data.
231 */
232aaudio_result_t AAudioServiceStreamMMAP::start() {
Eric Laurentcb4dae22017-07-01 19:39:32 -0700233 if (isRunning()) {
234 return AAUDIO_OK;
235 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800236 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burk87c9f642017-05-17 07:22:39 -0700237 aaudio_result_t result;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700238 status_t status = mMmapStream->start(mServiceClient, &mPortHandle);
Phil Burk87c9f642017-05-17 07:22:39 -0700239 if (status != OK) {
240 ALOGE("AAudioServiceStreamMMAP::start() mMmapStream->start() returned %d", status);
Phil Burk5ef003b2017-06-30 11:43:37 -0700241 disconnect();
Phil Burk87c9f642017-05-17 07:22:39 -0700242 result = AAudioConvert_androidToAAudioResult(status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800243 } else {
244 result = AAudioServiceStreamBase::start();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700245 if (!mInService && result == AAUDIO_OK) {
246 startClient(mMmapClient, &mClientHandle);
247 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800248 }
249 return result;
250}
251
252/**
253 * Stop the flow of data such that start() can resume with loss of data.
254 */
255aaudio_result_t AAudioServiceStreamMMAP::pause() {
Eric Laurentcb4dae22017-07-01 19:39:32 -0700256 if (!isRunning()) {
257 return AAUDIO_OK;
258 }
Phil Burkc0c70e32017-02-09 13:18:38 -0800259 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burkc0c70e32017-02-09 13:18:38 -0800260 aaudio_result_t result1 = AAudioServiceStreamBase::pause();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700261 if (!mInService) {
262 stopClient(mClientHandle);
263 }
Phil Burk87c9f642017-05-17 07:22:39 -0700264 status_t status = mMmapStream->stop(mPortHandle);
Phil Burkc0c70e32017-02-09 13:18:38 -0800265 mFramesRead.reset32();
Phil Burk87c9f642017-05-17 07:22:39 -0700266 return (result1 != AAUDIO_OK) ? result1 : AAudioConvert_androidToAAudioResult(status);
Phil Burkc0c70e32017-02-09 13:18:38 -0800267}
268
Phil Burk71f35bb2017-04-13 16:05:07 -0700269aaudio_result_t AAudioServiceStreamMMAP::stop() {
Eric Laurentcb4dae22017-07-01 19:39:32 -0700270 if (!isRunning()) {
271 return AAUDIO_OK;
272 }
Phil Burk71f35bb2017-04-13 16:05:07 -0700273 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
Phil Burk71f35bb2017-04-13 16:05:07 -0700274 aaudio_result_t result1 = AAudioServiceStreamBase::stop();
Eric Laurentcb4dae22017-07-01 19:39:32 -0700275 if (!mInService) {
276 stopClient(mClientHandle);
277 }
Phil Burk87c9f642017-05-17 07:22:39 -0700278 aaudio_result_t status = mMmapStream->stop(mPortHandle);
Phil Burk71f35bb2017-04-13 16:05:07 -0700279 mFramesRead.reset32();
Phil Burk87c9f642017-05-17 07:22:39 -0700280 return (result1 != AAUDIO_OK) ? result1 : AAudioConvert_androidToAAudioResult(status);
Phil Burk71f35bb2017-04-13 16:05:07 -0700281}
282
Phil Burkc0c70e32017-02-09 13:18:38 -0800283/**
284 * Discard any data held by the underlying HAL or Service.
285 */
286aaudio_result_t AAudioServiceStreamMMAP::flush() {
287 if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
288 // TODO how do we flush an MMAP/NOIRQ buffer? sync pointers?
Phil Burk71f35bb2017-04-13 16:05:07 -0700289 return AAudioServiceStreamBase::flush();;
Phil Burkc0c70e32017-02-09 13:18:38 -0800290}
291
Eric Laurentcb4dae22017-07-01 19:39:32 -0700292aaudio_result_t AAudioServiceStreamMMAP::startClient(const android::AudioClient& client,
293 audio_port_handle_t *clientHandle) {
294 return AAudioConvert_androidToAAudioResult(mMmapStream->start(client, clientHandle));
295}
296
297aaudio_result_t AAudioServiceStreamMMAP::stopClient(audio_port_handle_t clientHandle) {
298 return AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
299}
300
Phil Burk97350f92017-07-21 15:59:44 -0700301// Get free-running DSP or DMA hardware position from the HAL.
Phil Burkc0c70e32017-02-09 13:18:38 -0800302aaudio_result_t AAudioServiceStreamMMAP::getFreeRunningPosition(int64_t *positionFrames,
303 int64_t *timeNanos) {
304 struct audio_mmap_position position;
305 if (mMmapStream == nullptr) {
Phil Burk5ef003b2017-06-30 11:43:37 -0700306 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800307 return AAUDIO_ERROR_NULL;
308 }
309 status_t status = mMmapStream->getMmapPosition(&position);
Phil Burk940083c2017-07-17 17:00:02 -0700310 aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
311 if (result == AAUDIO_ERROR_UNAVAILABLE) {
312 ALOGW("sendCurrentTimestamp(): getMmapPosition() has no position data yet");
313 } else if (result != AAUDIO_OK) {
314 ALOGE("sendCurrentTimestamp(): getMmapPosition() returned status %d", status);
Phil Burk5ef003b2017-06-30 11:43:37 -0700315 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800316 } else {
317 mFramesRead.update32(position.position_frames);
Phil Burk97350f92017-07-21 15:59:44 -0700318
319 Timestamp timestamp(mFramesRead.get(), position.time_nanoseconds);
320 mAtomicTimestamp.write(timestamp);
321 *positionFrames = timestamp.getPosition();
322 *timeNanos = timestamp.getNanoseconds();
Phil Burkc0c70e32017-02-09 13:18:38 -0800323 }
Phil Burk940083c2017-07-17 17:00:02 -0700324 return result;
Phil Burkc0c70e32017-02-09 13:18:38 -0800325}
326
Phil Burk97350f92017-07-21 15:59:44 -0700327// Get timestamp that was written by getFreeRunningPosition()
328aaudio_result_t AAudioServiceStreamMMAP::getHardwareTimestamp(int64_t *positionFrames,
329 int64_t *timeNanos) {
330 // TODO Get presentation timestamp from the HAL
331 if (mAtomicTimestamp.isValid()) {
332 Timestamp timestamp = mAtomicTimestamp.read();
333 *positionFrames = timestamp.getPosition();
334 *timeNanos = timestamp.getNanoseconds() + mHardwareTimeOffsetNanos;
335 return AAUDIO_OK;
336 } else {
337 return AAUDIO_ERROR_UNAVAILABLE;
338 }
339}
340
Phil Burkc0c70e32017-02-09 13:18:38 -0800341void AAudioServiceStreamMMAP::onTearDown() {
Phil Burk5ef003b2017-06-30 11:43:37 -0700342 ALOGD("AAudioServiceStreamMMAP::onTearDown() called");
343 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800344};
345
346void AAudioServiceStreamMMAP::onVolumeChanged(audio_channel_mask_t channels,
347 android::Vector<float> values) {
348 // TODO do we really need a different volume for each channel?
349 float volume = values[0];
350 ALOGD("AAudioServiceStreamMMAP::onVolumeChanged() volume[0] = %f", volume);
351 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);
352};
353
354void AAudioServiceStreamMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
355 ALOGD("AAudioServiceStreamMMAP::onRoutingChanged() called with %d, old = %d",
Eric Laurentcb4dae22017-07-01 19:39:32 -0700356 deviceId, mDeviceId);
357 if (mDeviceId != AUDIO_PORT_HANDLE_NONE && mDeviceId != deviceId) {
Phil Burk5ef003b2017-06-30 11:43:37 -0700358 disconnect();
Phil Burkc0c70e32017-02-09 13:18:38 -0800359 }
Eric Laurentcb4dae22017-07-01 19:39:32 -0700360 mDeviceId = deviceId;
Phil Burkc0c70e32017-02-09 13:18:38 -0800361};
362
363/**
364 * Get an immutable description of the data queue from the HAL.
365 */
366aaudio_result_t AAudioServiceStreamMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
367{
368 // Gather information on the data queue based on HAL info.
369 int32_t bytesPerFrame = calculateBytesPerFrame();
370 int32_t capacityInBytes = mCapacityInFrames * bytesPerFrame;
371 int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
372 parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
373 parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
374 parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
375 parcelable.mDownDataQueueParcelable.setCapacityInFrames(mCapacityInFrames);
376 return AAUDIO_OK;
Phil Burkec89b2e2017-06-20 15:05:06 -0700377}