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 <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 
48 using namespace android;  // TODO just import names needed
49 using namespace aaudio;   // TODO just import names needed
50 
51 
AAudioServiceEndpointMMAP(AAudioService & audioService)52 AAudioServiceEndpointMMAP::AAudioServiceEndpointMMAP(AAudioService &audioService)
53         : mMmapStream(nullptr)
54         , mAAudioService(audioService) {}
55 
~AAudioServiceEndpointMMAP()56 AAudioServiceEndpointMMAP::~AAudioServiceEndpointMMAP() {}
57 
dump() const58 std::string AAudioServiceEndpointMMAP::dump() const {
59     std::stringstream result;
60 
61     result << "  MMAP: framesTransferred = " << mFramesTransferred.get();
62     result << ", HW nanos = " << mHardwareTimeOffsetNanos;
63     result << ", port handle = " << mPortHandle;
64     result << ", audio data FD = " << mAudioDataFileDescriptor;
65     result << "\n";
66 
67     result << "    HW Offset Micros:     " <<
68                                       (getHardwareTimeOffsetNanos()
69                                        / AAUDIO_NANOS_PER_MICROSECOND) << "\n";
70 
71     result << AAudioServiceEndpoint::dump();
72     return result.str();
73 }
74 
open(const aaudio::AAudioStreamRequest & request)75 aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) {
76     aaudio_result_t result = AAUDIO_OK;
77     audio_config_base_t config;
78     audio_port_handle_t deviceId;
79 
80     int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
81     int32_t burstMicros = 0;
82 
83     copyFrom(request.getConstantConfiguration());
84 
85     aaudio_direction_t direction = getDirection();
86 
87     const audio_content_type_t contentType =
88             AAudioConvert_contentTypeToInternal(getContentType());
89     // Usage only used for OUTPUT
90     const audio_usage_t usage = (direction == AAUDIO_DIRECTION_OUTPUT)
91             ? AAudioConvert_usageToInternal(getUsage())
92             : AUDIO_USAGE_UNKNOWN;
93     const audio_source_t source = (direction == AAUDIO_DIRECTION_INPUT)
94             ? AAudioConvert_inputPresetToAudioSource(getInputPreset())
95             : AUDIO_SOURCE_DEFAULT;
96 
97     const audio_attributes_t attributes = {
98             .content_type = contentType,
99             .usage = usage,
100             .source = source,
101             .flags = AUDIO_FLAG_LOW_LATENCY,
102             .tags = ""
103     };
104     ALOGD("%s(%p) MMAP attributes.usage = %d, content_type = %d, source = %d",
105           __func__, this, attributes.usage, attributes.content_type, attributes.source);
106 
107     mMmapClient.clientUid = request.getUserId();
108     mMmapClient.clientPid = request.getProcessId();
109     mMmapClient.packageName.setTo(String16(""));
110 
111     mRequestedDeviceId = deviceId = getDeviceId();
112 
113     // Fill in config
114     aaudio_format_t aaudioFormat = getFormat();
115     if (aaudioFormat == AAUDIO_UNSPECIFIED || aaudioFormat == AAUDIO_FORMAT_PCM_FLOAT) {
116         aaudioFormat = AAUDIO_FORMAT_PCM_I16;
117     }
118     config.format = AAudioConvert_aaudioToAndroidDataFormat(aaudioFormat);
119 
120     int32_t aaudioSampleRate = getSampleRate();
121     if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
122         aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
123     }
124     config.sample_rate = aaudioSampleRate;
125 
126     int32_t aaudioSamplesPerFrame = getSamplesPerFrame();
127 
128     if (direction == AAUDIO_DIRECTION_OUTPUT) {
129         config.channel_mask = (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
130                               ? AUDIO_CHANNEL_OUT_STEREO
131                               : audio_channel_out_mask_from_count(aaudioSamplesPerFrame);
132         mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
133 
134     } else if (direction == AAUDIO_DIRECTION_INPUT) {
135         config.channel_mask =  (aaudioSamplesPerFrame == AAUDIO_UNSPECIFIED)
136                                ? AUDIO_CHANNEL_IN_STEREO
137                                : audio_channel_in_mask_from_count(aaudioSamplesPerFrame);
138         mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
139 
140     } else {
141         ALOGE("%s() invalid direction = %d", __func__, direction);
142         return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
143     }
144 
145     MmapStreamInterface::stream_direction_t streamDirection =
146             (direction == AAUDIO_DIRECTION_OUTPUT)
147             ? MmapStreamInterface::DIRECTION_OUTPUT
148             : MmapStreamInterface::DIRECTION_INPUT;
149 
150     aaudio_session_id_t requestedSessionId = getSessionId();
151     audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
152 
153     // Open HAL stream. Set mMmapStream
154     status_t status = MmapStreamInterface::openMmapStream(streamDirection,
155                                                           &attributes,
156                                                           &config,
157                                                           mMmapClient,
158                                                           &deviceId,
159                                                           &sessionId,
160                                                           this, // callback
161                                                           mMmapStream,
162                                                           &mPortHandle);
163     ALOGD("%s() mMapClient.uid = %d, pid = %d => portHandle = %d\n",
164           __func__, mMmapClient.clientUid,  mMmapClient.clientPid, mPortHandle);
165     if (status != OK) {
166         ALOGE("%s() openMmapStream() returned status %d",  __func__, status);
167         return AAUDIO_ERROR_UNAVAILABLE;
168     }
169 
170     if (deviceId == AAUDIO_UNSPECIFIED) {
171         ALOGW("%s() openMmapStream() failed to set deviceId", __func__);
172     }
173     setDeviceId(deviceId);
174 
175     if (sessionId == AUDIO_SESSION_ALLOCATE) {
176         ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
177     }
178 
179     aaudio_session_id_t actualSessionId =
180             (requestedSessionId == AAUDIO_SESSION_ID_NONE)
181             ? AAUDIO_SESSION_ID_NONE
182             : (aaudio_session_id_t) sessionId;
183     setSessionId(actualSessionId);
184     ALOGD("%s() deviceId = %d, sessionId = %d", __func__, getDeviceId(), getSessionId());
185 
186     // Create MMAP/NOIRQ buffer.
187     int32_t minSizeFrames = getBufferCapacity();
188     if (minSizeFrames <= 0) { // zero will get rejected
189         minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
190     }
191     status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
192     if (status != OK) {
193         ALOGE("%s() - createMmapBuffer() failed with status %d %s",
194               __func__, status, strerror(-status));
195         result = AAUDIO_ERROR_UNAVAILABLE;
196         goto error;
197     } else {
198         ALOGD("%s() createMmapBuffer() returned = %d, buffer_size = %d, burst_size %d"
199                       ", Sharable FD: %s",
200               __func__, status,
201               abs(mMmapBufferinfo.buffer_size_frames),
202               mMmapBufferinfo.burst_size_frames,
203               mMmapBufferinfo.buffer_size_frames < 0 ? "Yes" : "No");
204     }
205 
206     setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
207     // The audio HAL indicates if the shared memory fd can be shared outside of audioserver
208     // by returning a negative buffer size
209     if (getBufferCapacity() < 0) {
210         // Exclusive mode can be used by client or service.
211         setBufferCapacity(-getBufferCapacity());
212     } else {
213         // Exclusive mode can only be used by the service because the FD cannot be shared.
214         uid_t audioServiceUid = getuid();
215         if ((mMmapClient.clientUid != audioServiceUid) &&
216             getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
217             // Fallback is handled by caller but indicate what is possible in case
218             // this is used in the future
219             setSharingMode(AAUDIO_SHARING_MODE_SHARED);
220             ALOGW("%s() - exclusive FD cannot be used by client", __func__);
221             result = AAUDIO_ERROR_UNAVAILABLE;
222             goto error;
223         }
224     }
225 
226     // Get information about the stream and pass it back to the caller.
227     setSamplesPerFrame((direction == AAUDIO_DIRECTION_OUTPUT)
228                        ? audio_channel_count_from_out_mask(config.channel_mask)
229                        : audio_channel_count_from_in_mask(config.channel_mask));
230 
231     // AAudio creates a copy of this FD and retains ownership of the copy.
232     // Assume that AudioFlinger will close the original shared_memory_fd.
233     mAudioDataFileDescriptor.reset(dup(mMmapBufferinfo.shared_memory_fd));
234     if (mAudioDataFileDescriptor.get() == -1) {
235         ALOGE("%s() - could not dup shared_memory_fd", __func__);
236         result = AAUDIO_ERROR_INTERNAL;
237         goto error;
238     }
239     mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
240     setFormat(AAudioConvert_androidToAAudioDataFormat(config.format));
241     setSampleRate(config.sample_rate);
242 
243     // Scale up the burst size to meet the minimum equivalent in microseconds.
244     // This is to avoid waking the CPU too often when the HW burst is very small
245     // or at high sample rates.
246     do {
247         if (burstMicros > 0) {  // skip first loop
248             mFramesPerBurst *= 2;
249         }
250         burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
251     } while (burstMicros < burstMinMicros);
252 
253     ALOGD("%s() original burst = %d, minMicros = %d, to burst = %d\n",
254           __func__, mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
255 
256     ALOGD("%s() actual rate = %d, channels = %d"
257           ", deviceId = %d, capacity = %d\n",
258           __func__, getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
259 
260     return result;
261 
262 error:
263     close();
264     return result;
265 }
266 
close()267 aaudio_result_t AAudioServiceEndpointMMAP::close() {
268     if (mMmapStream != 0) {
269         ALOGD("%s() clear() endpoint", __func__);
270         // Needs to be explicitly cleared or CTS will fail but it is not clear why.
271         mMmapStream.clear();
272         // Apparently the above close is asynchronous. An attempt to open a new device
273         // right after a close can fail. Also some callbacks may still be in flight!
274         // FIXME Make closing synchronous.
275         AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
276     }
277 
278     return AAUDIO_OK;
279 }
280 
startStream(sp<AAudioServiceStreamBase> stream,audio_port_handle_t * clientHandle __unused)281 aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
282                                                    audio_port_handle_t *clientHandle __unused) {
283     // Start the client on behalf of the AAudio service.
284     // Use the port handle that was provided by openMmapStream().
285     audio_port_handle_t tempHandle = mPortHandle;
286     aaudio_result_t result = startClient(mMmapClient, &tempHandle);
287     // When AudioFlinger is passed a valid port handle then it should not change it.
288     LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
289                         "%s() port handle not expected to change from %d to %d",
290                         __func__, mPortHandle, tempHandle);
291     ALOGV("%s(%p) mPortHandle = %d", __func__, stream.get(), mPortHandle);
292     return result;
293 }
294 
stopStream(sp<AAudioServiceStreamBase> stream,audio_port_handle_t clientHandle __unused)295 aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
296                                                   audio_port_handle_t clientHandle __unused) {
297     mFramesTransferred.reset32();
298 
299     // Round 64-bit counter up to a multiple of the buffer capacity.
300     // This is required because the 64-bit counter is used as an index
301     // into a circular buffer and the actual HW position is reset to zero
302     // when the stream is stopped.
303     mFramesTransferred.roundUp64(getBufferCapacity());
304 
305     // Use the port handle that was provided by openMmapStream().
306     ALOGV("%s(%p) mPortHandle = %d", __func__, stream.get(), mPortHandle);
307     return stopClient(mPortHandle);
308 }
309 
startClient(const android::AudioClient & client,audio_port_handle_t * clientHandle)310 aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
311                                                        audio_port_handle_t *clientHandle) {
312     if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
313     ALOGD("%s(%p(uid=%d, pid=%d))", __func__, &client, client.clientUid, client.clientPid);
314     audio_port_handle_t originalHandle =  *clientHandle;
315     status_t status = mMmapStream->start(client, clientHandle);
316     aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
317     ALOGD("%s() , portHandle %d => %d, returns %d", __func__, originalHandle, *clientHandle, result);
318     return result;
319 }
320 
stopClient(audio_port_handle_t clientHandle)321 aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
322     ALOGD("%s(portHandle = %d), called", __func__, clientHandle);
323     if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
324     aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
325     ALOGD("%s(portHandle = %d), returns %d", __func__, clientHandle, result);
326     return result;
327 }
328 
329 // Get free-running DSP or DMA hardware position from the HAL.
getFreeRunningPosition(int64_t * positionFrames,int64_t * timeNanos)330 aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
331                                                                 int64_t *timeNanos) {
332     struct audio_mmap_position position;
333     if (mMmapStream == nullptr) {
334         return AAUDIO_ERROR_NULL;
335     }
336     status_t status = mMmapStream->getMmapPosition(&position);
337     ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
338           __func__, status, position.position_frames, (long long) position.time_nanoseconds);
339     aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
340     if (result == AAUDIO_ERROR_UNAVAILABLE) {
341         ALOGW("%s(): getMmapPosition() has no position data available", __func__);
342     } else if (result != AAUDIO_OK) {
343         ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
344     } else {
345         // Convert 32-bit position to 64-bit position.
346         mFramesTransferred.update32(position.position_frames);
347         *positionFrames = mFramesTransferred.get();
348         *timeNanos = position.time_nanoseconds;
349     }
350     return result;
351 }
352 
getTimestamp(int64_t * positionFrames,int64_t * timeNanos)353 aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
354                                                     int64_t *timeNanos) {
355     return 0; // TODO
356 }
357 
358 // This is called by AudioFlinger when it wants to destroy a stream.
onTearDown(audio_port_handle_t portHandle)359 void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
360     ALOGD("%s(portHandle = %d) called", __func__, portHandle);
361     // Are we tearing down the EXCLUSIVE MMAP stream?
362     if (isStreamRegistered(portHandle)) {
363         ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
364         disconnectRegisteredStreams();
365     } else {
366         // Must be a SHARED stream?
367         ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
368         aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
369         ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
370     }
371 };
372 
onVolumeChanged(audio_channel_mask_t channels,android::Vector<float> values)373 void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
374                                               android::Vector<float> values) {
375     // TODO Do we really need a different volume for each channel?
376     // We get called with an array filled with a single value!
377     float volume = values[0];
378     ALOGD("%s(%p) volume[0] = %f", __func__, this, volume);
379     std::lock_guard<std::mutex> lock(mLockStreams);
380     for(const auto stream : mRegisteredStreams) {
381         stream->onVolumeChanged(volume);
382     }
383 };
384 
onRoutingChanged(audio_port_handle_t deviceId)385 void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t deviceId) {
386     ALOGD("%s(%p) called with dev %d, old = %d", __func__, this, deviceId, getDeviceId());
387     if (getDeviceId() != AUDIO_PORT_HANDLE_NONE  && getDeviceId() != deviceId) {
388         disconnectRegisteredStreams();
389     }
390     setDeviceId(deviceId);
391 };
392 
393 /**
394  * Get an immutable description of the data queue from the HAL.
395  */
getDownDataDescription(AudioEndpointParcelable & parcelable)396 aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(AudioEndpointParcelable &parcelable)
397 {
398     // Gather information on the data queue based on HAL info.
399     int32_t bytesPerFrame = calculateBytesPerFrame();
400     int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
401     int fdIndex = parcelable.addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
402     parcelable.mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
403     parcelable.mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
404     parcelable.mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
405     parcelable.mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
406     return AAUDIO_OK;
407 }
408