• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 <thread>
27 #include <utils/Singleton.h>
28 #include <vector>
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 #define AAUDIO_BUFFER_CAPACITY_MIN    4 * 512
40 #define AAUDIO_SAMPLE_RATE_DEFAULT    48000
41 
42 // This is an estimate of the time difference between the HW and the MMAP time.
43 // TODO Get presentation timestamps from the HAL instead of using these estimates.
44 #define OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS  (3 * AAUDIO_NANOS_PER_MILLISECOND)
45 #define INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS   (-1 * AAUDIO_NANOS_PER_MILLISECOND)
46 
47 using namespace android;  // TODO just import names needed
48 using namespace aaudio;   // TODO just import names needed
49 
AAudioServiceEndpointMMAP(AAudioService & audioService)50 AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
51         : mMmapStream(nullptr)
52         , mAAudioService(audioService) {}
53 
dump() const54 std::string AAudioServiceEndpointMMAP::dump() const {
55     std::stringstream result;
56 
57     result << "  MMAP: framesTransferred = " << mFramesTransferred.get();
58     result << ", HW nanos = " << mHardwareTimeOffsetNanos;
59     result << ", port handle = " << mPortHandle;
60     result << ", audio data FD = " << mAudioDataFileDescriptor;
61     result << "\n";
62 
63     result << "    HW Offset Micros:     " <<
64                                       (getHardwareTimeOffsetNanos()
65                                        / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
66 
67     result << AAudioServiceEndpoint::dump();
68     return result.str();
69 }
70 
open(const aaudio::AAudioStreamRequest & request)71 aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
72     aaudio_result_t result = AAUDIO_OK;
73     copyFrom(request.getConstantConfiguration());
74     mMmapClient.attributionSource = request.getAttributionSource();
75     // TODO b/182392769: use attribution source util
76     mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
77         legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
78     mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
79         legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
80 
81     audio_format_t audioFormat = getFormat();
82 
83     // FLOAT is not directly supported by the HAL so ask for a 32-bit.
84     if (audioFormat == AUDIO_FORMAT_PCM_FLOAT) {
85         // TODO remove these logs when finished debugging.
86         ALOGD("%s() change format from %d to 32_BIT", __func__, audioFormat);
87         audioFormat = AUDIO_FORMAT_PCM_32_BIT;
88     }
89 
90     result = openWithFormat(audioFormat);
91     if (result == AAUDIO_OK) return result;
92 
93     if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_32_BIT) {
94         ALOGD("%s() 32_BIT failed, perhaps due to format. Try again with 24_BIT_PACKED", __func__);
95         audioFormat = AUDIO_FORMAT_PCM_24_BIT_PACKED;
96         result = openWithFormat(audioFormat);
97     }
98     if (result == AAUDIO_OK) return result;
99 
100     // TODO The HAL and AudioFlinger should be recommending a format if the open fails.
101     //      But that recommendation is not propagating back from the HAL.
102     //      So for now just try something very likely to work.
103     if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
104         ALOGD("%s() 24_BIT failed, perhaps due to format. Try again with 16_BIT", __func__);
105         audioFormat = AUDIO_FORMAT_PCM_16_BIT;
106         result = openWithFormat(audioFormat);
107     }
108     return result;
109 }
110 
openWithFormat(audio_format_t audioFormat)111 aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(audio_format_t audioFormat) {
112     aaudio_result_t result = AAUDIO_OK;
113     audio_config_base_t config;
114     audio_port_handle_t deviceId;
115 
116     const audio_attributes_t attributes = getAudioAttributesFrom(this);
117 
118     mRequestedDeviceId = deviceId = getDeviceId();
119 
120     // Fill in config
121     config.format = audioFormat;
122 
123     int32_t aaudioSampleRate = getSampleRate();
124     if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
125         aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
126     }
127     config.sample_rate = aaudioSampleRate;
128 
129     int32_t aaudioSamplesPerFrame = getSamplesPerFrame();
130 
131     const aaudio_direction_t direction = getDirection();
132 
133     if (direction == AAUDIO_DIRECTION_OUTPUT) {
134         config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
135                               ? AUDIO_CHANNEL_OUT_STEREO
136                               : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
137         mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
138 
139     } else if (direction == AAUDIO_DIRECTION_INPUT) {
140         config.channel_mask =  (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
141                                ? AUDIO_CHANNEL_IN_STEREO
142                                : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
143         mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
144 
145     } else {
146         ALOGE("%s() invalid direction = %d", __func__, direction);
147         return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
148     }
149 
150     MmapStreamInterface::stream_direction_t streamDirection =
151             (direction == AAUDIO_DIRECTION_OUTPUT)
152             ? MmapStreamInterface::DIRECTION_OUTPUT
153             : MmapStreamInterface::DIRECTION_INPUT;
154 
155     aaudio_session_id_t requestedSessionId = getSessionId();
156     audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
157 
158     // Open HAL stream. Set mMmapStream
159     status_t status = MmapStreamInterface::openMmapStream(streamDirection,
160                                                           &attributes,
161                                                           &config,
162                                                           mMmapClient,
163                                                           &deviceId,
164                                                           &sessionId,
165                                                           this, // callback
166                                                           mMmapStream,
167                                                           &mPortHandle);
168     ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
169           __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
170     if (status != OK) {
171         // This can happen if the resource is busy or the config does
172         // not match the hardware.
173         ALOGD("%s() - openMmapStream() returned status %d",  __func__, status);
174         return AAUDIO_ERROR_UNAVAILABLE;
175     }
176 
177     if (deviceId == AAUDIO_UNSPECIFIED) {
178         ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
179     }
180     setDeviceId(deviceId);
181 
182     if (sessionId == AUDIO_SESSION_ALLOCATE) {
183         ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
184     }
185 
186     aaudio_session_id_t actualSessionId =
187             (requestedSessionId == AAUDIO_SESSION_ID_NONE)
188             ? AAUDIO_SESSION_ID_NONE
189             : (aaudio_session_id_t) sessionId;
190     setSessionId(actualSessionId);
191     ALOGD("%s() deviceId = %d, sessionId = %d", __func__, getDeviceId(), getSessionId());
192 
193     // Create MMAP/NOIRQ buffer.
194     int32_t minSizeFrames = getBufferCapacity();
195     if (minSizeFrames <= 0) { // zero will get rejected
196         minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
197     }
198     status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
199     bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
200     if (status != OK) {
201         ALOGE("%s() - createMmapBuffer() failed with status %d %s",
202               __func__, status, strerror(-status));
203         result = AAUDIO_ERROR_UNAVAILABLE;
204         goto error;
205     } else {
206         ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
207                       ", Sharable FD: %s",
208               __func__,
209               mMmapBufferinfo.buffer_size_frames,
210               mMmapBufferinfo.burst_size_frames,
211               isBufferShareable ? "Yes" : "No");
212     }
213 
214     setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
215     if (!isBufferShareable) {
216         // Exclusive mode can only be used by the service because the FD cannot be shared.
217         int32_t audioServiceUid =
218             VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
219         if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
220             getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
221             ALOGW("%s() - exclusive FD cannot be used by client", __func__);
222             result = AAUDIO_ERROR_UNAVAILABLE;
223             goto error;
224         }
225     }
226 
227     // Get information about the stream and pass it back to the caller.
228     setSamplesPerFrame((direction == AAUDIO_DIRECTION_OUTPUT)
229                        ? audio_channel_count_from_out_mask(config.channel_mask)
230                        : audio_channel_count_from_in_mask(config.channel_mask));
231 
232     // AAudio creates a copy of this FD and retains ownership of the copy.
233     // Assume that AudioFlinger will close the original shared_memory_fd.
234     mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
235     if (mAudioDataFileDescriptor.get() == -1) {
236         ALOGE("%s() - could not dup shared_memory_fd", __func__);
237         result = AAUDIO_ERROR_INTERNAL;
238         goto error;
239     }
240     // Call to HAL to make sure the transport FD was able to be closed by binder.
241     // This is a tricky workaround for a problem in Binder.
242     // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
243     struct audio_mmap_position position;
244     mMmapStream->getMmapPosition(&position);
245 
246     mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
247     setFormat(config.format);
248     setSampleRate(config.sample_rate);
249 
250     ALOGD("%s() actual rate = %d, channels = %d"
251           ", deviceId = %d, capacity = %d\n",
252           __func__, getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
253 
254     ALOGD("%s() format = 0x%08x, frame size = %d, burst size = %d",
255           __func__, getFormat(), calculateBytesPerFrame(), mFramesPerBurst);
256 
257     return result;
258 
259 error:
260     close();
261     return result;
262 }
263 
close()264 void AAudioServiceEndpointMMAP::close() {
265     if (mMmapStream != nullptr) {
266         // Needs to be explicitly cleared or CTS will fail but it is not clear why.
267         mMmapStream.clear();
268         // Apparently the above close is asynchronous. An attempt to open a new device
269         // right after a close can fail. Also some callbacks may still be in flight!
270         // FIXME Make closing synchronous.
271         AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
272     }
273 }
274 
startStream(sp<AAudioServiceStreamBase> stream,audio_port_handle_t * clientHandle __unused)275 aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
276                                                    audio_port_handle_t *clientHandle __unused) {
277     // Start the client on behalf of the AAudio service.
278     // Use the port handle that was provided by openMmapStream().
279     audio_port_handle_t tempHandle = mPortHandle;
280     audio_attributes_t attr = {};
281     if (stream != nullptr) {
282         attr = getAudioAttributesFrom(stream.get());
283     }
284     aaudio_result_t result = startClient(
285             mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
286     // When AudioFlinger is passed a valid port handle then it should not change it.
287     LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
288                         "%s() port handle not expected to change from %d to %d",
289                         __func__, mPortHandle, tempHandle);
290     ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
291     return result;
292 }
293 
stopStream(sp<AAudioServiceStreamBase> stream,audio_port_handle_t clientHandle __unused)294 aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
295                                                   audio_port_handle_t clientHandle __unused) {
296     mFramesTransferred.reset32();
297 
298     // Round 64-bit counter up to a multiple of the buffer capacity.
299     // This is required because the 64-bit counter is used as an index
300     // into a circular buffer and the actual HW position is reset to zero
301     // when the stream is stopped.
302     mFramesTransferred.roundUp64(getBufferCapacity());
303 
304     // Use the port handle that was provided by openMmapStream().
305     ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
306     return stopClient(mPortHandle);
307 }
308 
startClient(const android::AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * clientHandle)309 aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
310                                                        const audio_attributes_t *attr,
311                                                        audio_port_handle_t *clientHandle) {
312     if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
313     status_t status = mMmapStream->start(client, attr, clientHandle);
314     return AAudioConvert_androidToAAudioResult(status);
315 }
316 
stopClient(audio_port_handle_t clientHandle)317 aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
318     if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
319     aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
320     return result;
321 }
322 
323 // Get free-running DSP or DMA hardware position from the HAL.
getFreeRunningPosition(int64_t * positionFrames,int64_t * timeNanos)324 aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
325                                                                 int64_t *timeNanos) {
326     struct audio_mmap_position position;
327     if (mMmapStream == nullptr) {
328         return AAUDIO_ERROR_NULL;
329     }
330     status_t status = mMmapStream->getMmapPosition(&position);
331     ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
332           __func__, status, position.position_frames, (long long) position.time_nanoseconds);
333     aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
334     if (result == AAUDIO_ERROR_UNAVAILABLE) {
335         ALOGW("%s(): getMmapPosition() has no position data available", __func__);
336     } else if (result != AAUDIO_OK) {
337         ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
338     } else {
339         // Convert 32-bit position to 64-bit position.
340         mFramesTransferred.update32(position.position_frames);
341         *positionFrames = mFramesTransferred.get();
342         *timeNanos = position.time_nanoseconds;
343     }
344     return result;
345 }
346 
getTimestamp(int64_t * positionFrames,int64_t * timeNanos)347 aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
348                                                     int64_t *timeNanos) {
349     return 0; // TODO
350 }
351 
352 // This is called by onTearDown() in a separate thread to avoid deadlocks.
handleTearDownAsync(audio_port_handle_t portHandle)353 void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
354     // Are we tearing down the EXCLUSIVE MMAP stream?
355     if (isStreamRegistered(portHandle)) {
356         ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
357         disconnectRegisteredStreams();
358     } else {
359         // Must be a SHARED stream?
360         ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
361         aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
362         ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
363     }
364 };
365 
366 // This is called by AudioFlinger when it wants to destroy a stream.
onTearDown(audio_port_handle_t portHandle)367 void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
368     ALOGD("%s(portHandle = %d) called", __func__, portHandle);
369     android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
370     std::thread asyncTask([holdEndpoint, portHandle]() {
371         holdEndpoint->handleTearDownAsync(portHandle);
372     });
373     asyncTask.detach();
374 }
375 
onVolumeChanged(audio_channel_mask_t channels,android::Vector<float> values)376 void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
377                                               android::Vector<float> values) {
378     // TODO Do we really need a different volume for each channel?
379     // We get called with an array filled with a single value!
380     float volume = values[0];
381     ALOGD("%s() volume[0] = %f", __func__, volume);
382     std::lock_guard<std::mutex> lock(mLockStreams);
383     for(const auto& stream : mRegisteredStreams) {
384         stream->onVolumeChanged(volume);
385     }
386 };
387 
onRoutingChanged(audio_port_handle_t portHandle)388 void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
389     const int32_t deviceId = static_cast<int32_t>(portHandle);
390     ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
391     if (getDeviceId() != deviceId) {
392         if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
393             android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
394             std::thread asyncTask([holdEndpoint, deviceId]() {
395                 ALOGD("onRoutingChanged() asyncTask launched");
396                 holdEndpoint->disconnectRegisteredStreams();
397                 holdEndpoint->setDeviceId(deviceId);
398             });
399             asyncTask.detach();
400         } else {
401             setDeviceId(deviceId);
402         }
403     }
404 };
405 
406 /**
407  * Get an immutable description of the data queue from the HAL.
408  */
getDownDataDescription(AudioEndpointParcelable & parcelable)409 aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
410 {
411     // Gather information on the data queue based on HAL info.
412     int32_t bytesPerFrame = calculateBytesPerFrame();
413     int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
414     int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
415     parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
416     parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
417     parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
418     parcelable.mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
419     return AAUDIO_OK;
420 }
421 
getExternalPosition(uint64_t * positionFrames,int64_t * timeNanos)422 aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
423                                                                int64_t *timeNanos)
424 {
425     if (!mExternalPositionSupported) {
426         return AAUDIO_ERROR_INVALID_STATE;
427     }
428     status_t status = mMmapStream->getExternalPosition(positionFrames, timeNanos);
429     if (status == INVALID_OPERATION) {
430         // getExternalPosition is not supported. Set mExternalPositionSupported as false
431         // so that the call will not go to the HAL next time.
432         mExternalPositionSupported = false;
433     }
434     return AAudioConvert_androidToAAudioResult(status);
435 }
436