• 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     mRequestedDeviceId = getDeviceId();
75 
76     mMmapClient.attributionSource = request.getAttributionSource();
77     // TODO b/182392769: use attribution source util
78     mMmapClient.attributionSource.uid = VALUE_OR_FATAL(
79         legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
80     mMmapClient.attributionSource.pid = VALUE_OR_FATAL(
81         legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
82 
83     audio_format_t audioFormat = getFormat();
84 
85     result = openWithFormat(audioFormat);
86     if (result == AAUDIO_OK) return result;
87 
88     if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_FLOAT) {
89         ALOGD("%s() FLOAT failed, perhaps due to format. Try again with 32_BIT", __func__);
90         audioFormat = AUDIO_FORMAT_PCM_32_BIT;
91         result = openWithFormat(audioFormat);
92     }
93     if (result == AAUDIO_OK) return result;
94 
95     if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_32_BIT) {
96         ALOGD("%s() 32_BIT failed, perhaps due to format. Try again with 24_BIT_PACKED", __func__);
97         audioFormat = AUDIO_FORMAT_PCM_24_BIT_PACKED;
98         result = openWithFormat(audioFormat);
99     }
100     if (result == AAUDIO_OK) return result;
101 
102     // TODO The HAL and AudioFlinger should be recommending a format if the open fails.
103     //      But that recommendation is not propagating back from the HAL.
104     //      So for now just try something very likely to work.
105     if (result == AAUDIO_ERROR_UNAVAILABLE && audioFormat == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
106         ALOGD("%s() 24_BIT failed, perhaps due to format. Try again with 16_BIT", __func__);
107         audioFormat = AUDIO_FORMAT_PCM_16_BIT;
108         result = openWithFormat(audioFormat);
109     }
110     return result;
111 }
112 
openWithFormat(audio_format_t audioFormat)113 aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(audio_format_t audioFormat) {
114     aaudio_result_t result = AAUDIO_OK;
115     audio_config_base_t config;
116     audio_port_handle_t deviceId;
117 
118     const audio_attributes_t attributes = getAudioAttributesFrom(this);
119 
120     deviceId = mRequestedDeviceId;
121 
122     // Fill in config
123     config.format = audioFormat;
124 
125     int32_t aaudioSampleRate = getSampleRate();
126     if (aaudioSampleRate == AAUDIO_UNSPECIFIED) {
127         aaudioSampleRate = AAUDIO_SAMPLE_RATE_DEFAULT;
128     }
129     config.sample_rate = aaudioSampleRate;
130 
131     const aaudio_direction_t direction = getDirection();
132 
133     config.channel_mask = AAudio_getChannelMaskForOpen(
134             getChannelMask(), getSamplesPerFrame(), direction == AAUDIO_DIRECTION_INPUT);
135 
136     if (direction == AAUDIO_DIRECTION_OUTPUT) {
137         mHardwareTimeOffsetNanos = OUTPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at DAC later
138 
139     } else if (direction == AAUDIO_DIRECTION_INPUT) {
140         mHardwareTimeOffsetNanos = INPUT_ESTIMATED_HARDWARE_OFFSET_NANOS; // frames at ADC earlier
141 
142     } else {
143         ALOGE("%s() invalid direction = %d", __func__, direction);
144         return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
145     }
146 
147     MmapStreamInterface::stream_direction_t streamDirection =
148             (direction == AAUDIO_DIRECTION_OUTPUT)
149             ? MmapStreamInterface::DIRECTION_OUTPUT
150             : MmapStreamInterface::DIRECTION_INPUT;
151 
152     aaudio_session_id_t requestedSessionId = getSessionId();
153     audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
154 
155     // Open HAL stream. Set mMmapStream
156     ALOGD("%s trying to open MMAP stream with format=%#x, "
157           "sample_rate=%u, channel_mask=%#x, device=%d",
158           __func__, config.format, config.sample_rate,
159           config.channel_mask, deviceId);
160     status_t status = MmapStreamInterface::openMmapStream(streamDirection,
161                                                           &attributes,
162                                                           &config,
163                                                           mMmapClient,
164                                                           &deviceId,
165                                                           &sessionId,
166                                                           this, // callback
167                                                           mMmapStream,
168                                                           &mPortHandle);
169     ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n",
170           __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle);
171     if (status != OK) {
172         // This can happen if the resource is busy or the config does
173         // not match the hardware.
174         ALOGD("%s() - openMmapStream() returned status %d",  __func__, status);
175         return AAUDIO_ERROR_UNAVAILABLE;
176     }
177 
178     if (deviceId == AAUDIO_UNSPECIFIED) {
179         ALOGW("%s() - openMmapStream() failed to set deviceId", __func__);
180     }
181     setDeviceId(deviceId);
182 
183     if (sessionId == AUDIO_SESSION_ALLOCATE) {
184         ALOGW("%s() - openMmapStream() failed to set sessionId", __func__);
185     }
186 
187     aaudio_session_id_t actualSessionId =
188             (requestedSessionId == AAUDIO_SESSION_ID_NONE)
189             ? AAUDIO_SESSION_ID_NONE
190             : (aaudio_session_id_t) sessionId;
191     setSessionId(actualSessionId);
192 
193     ALOGD("%s(format = 0x%X) deviceId = %d, sessionId = %d",
194           __func__, audioFormat, getDeviceId(), getSessionId());
195 
196     // Create MMAP/NOIRQ buffer.
197     result = createMmapBuffer(&mAudioDataFileDescriptor);
198     if (result != AAUDIO_OK) {
199         goto error;
200     }
201 
202     // Get information about the stream and pass it back to the caller.
203     setChannelMask(AAudioConvert_androidToAAudioChannelMask(
204             config.channel_mask, getDirection() == AAUDIO_DIRECTION_INPUT,
205             AAudio_isChannelIndexMask(config.channel_mask)));
206 
207     setFormat(config.format);
208     setSampleRate(config.sample_rate);
209 
210     // If the position is not updated while the timestamp is updated for more than a certain amount,
211     // the timestamp reported from the HAL may not be accurate. Here, a timestamp grace period is
212     // set as 5 burst size. We may want to update this value if there is any report from OEMs saying
213     // that is too short.
214     static constexpr int kTimestampGraceBurstCount = 5;
215     mTimestampGracePeriodMs = ((int64_t) kTimestampGraceBurstCount * mFramesPerBurst
216             * AAUDIO_MILLIS_PER_SECOND) / getSampleRate();
217 
218     ALOGD("%s() got rate = %d, channels = %d channelMask = %#x, deviceId = %d, capacity = %d\n",
219           __func__, getSampleRate(), getSamplesPerFrame(), getChannelMask(),
220           deviceId, getBufferCapacity());
221 
222     ALOGD("%s() got format = 0x%X = %s, frame size = %d, burst size = %d",
223           __func__, getFormat(), audio_format_to_string(getFormat()),
224           calculateBytesPerFrame(), mFramesPerBurst);
225 
226     return result;
227 
228 error:
229     close();
230     // restore original requests
231     setDeviceId(mRequestedDeviceId);
232     setSessionId(requestedSessionId);
233     return result;
234 }
235 
close()236 void AAudioServiceEndpointMMAP::close() {
237     if (mMmapStream != nullptr) {
238         // Needs to be explicitly cleared or CTS will fail but it is not clear why.
239         mMmapStream.clear();
240         // Apparently the above close is asynchronous. An attempt to open a new device
241         // right after a close can fail. Also some callbacks may still be in flight!
242         // FIXME Make closing synchronous.
243         AudioClock::sleepForNanos(100 * AAUDIO_NANOS_PER_MILLISECOND);
244     }
245 }
246 
startStream(sp<AAudioServiceStreamBase> stream,audio_port_handle_t * clientHandle __unused)247 aaudio_result_t AAudioServiceEndpointMMAP::startStream(sp<AAudioServiceStreamBase> stream,
248                                                    audio_port_handle_t *clientHandle __unused) {
249     // Start the client on behalf of the AAudio service.
250     // Use the port handle that was provided by openMmapStream().
251     audio_port_handle_t tempHandle = mPortHandle;
252     audio_attributes_t attr = {};
253     if (stream != nullptr) {
254         attr = getAudioAttributesFrom(stream.get());
255     }
256     aaudio_result_t result = startClient(
257             mMmapClient, stream == nullptr ? nullptr : &attr, &tempHandle);
258     // When AudioFlinger is passed a valid port handle then it should not change it.
259     LOG_ALWAYS_FATAL_IF(tempHandle != mPortHandle,
260                         "%s() port handle not expected to change from %d to %d",
261                         __func__, mPortHandle, tempHandle);
262     ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
263     return result;
264 }
265 
stopStream(sp<AAudioServiceStreamBase> stream,audio_port_handle_t clientHandle __unused)266 aaudio_result_t AAudioServiceEndpointMMAP::stopStream(sp<AAudioServiceStreamBase> stream,
267                                                   audio_port_handle_t clientHandle __unused) {
268     mFramesTransferred.reset32();
269 
270     // Round 64-bit counter up to a multiple of the buffer capacity.
271     // This is required because the 64-bit counter is used as an index
272     // into a circular buffer and the actual HW position is reset to zero
273     // when the stream is stopped.
274     mFramesTransferred.roundUp64(getBufferCapacity());
275 
276     // Use the port handle that was provided by openMmapStream().
277     ALOGV("%s() mPortHandle = %d", __func__, mPortHandle);
278     return stopClient(mPortHandle);
279 }
280 
startClient(const android::AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * clientHandle)281 aaudio_result_t AAudioServiceEndpointMMAP::startClient(const android::AudioClient& client,
282                                                        const audio_attributes_t *attr,
283                                                        audio_port_handle_t *clientHandle) {
284     if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
285     status_t status = mMmapStream->start(client, attr, clientHandle);
286     return AAudioConvert_androidToAAudioResult(status);
287 }
288 
stopClient(audio_port_handle_t clientHandle)289 aaudio_result_t AAudioServiceEndpointMMAP::stopClient(audio_port_handle_t clientHandle) {
290     if (mMmapStream == nullptr) return AAUDIO_ERROR_NULL;
291     aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->stop(clientHandle));
292     return result;
293 }
294 
standby()295 aaudio_result_t AAudioServiceEndpointMMAP::standby() {
296     if (mMmapStream == nullptr) {
297         return AAUDIO_ERROR_NULL;
298     }
299     aaudio_result_t result = AAudioConvert_androidToAAudioResult(mMmapStream->standby());
300     return result;
301 }
302 
exitStandby(AudioEndpointParcelable * parcelable)303 aaudio_result_t AAudioServiceEndpointMMAP::exitStandby(AudioEndpointParcelable* parcelable) {
304     if (mMmapStream == nullptr) {
305         return AAUDIO_ERROR_NULL;
306     }
307     mAudioDataFileDescriptor.reset();
308     aaudio_result_t result = createMmapBuffer(&mAudioDataFileDescriptor);
309     if (result == AAUDIO_OK) {
310         int32_t bytesPerFrame = calculateBytesPerFrame();
311         int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
312         int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
313         parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
314         parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
315         parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
316         parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
317     }
318     return result;
319 }
320 
321 // Get free-running DSP or DMA hardware position from the HAL.
getFreeRunningPosition(int64_t * positionFrames,int64_t * timeNanos)322 aaudio_result_t AAudioServiceEndpointMMAP::getFreeRunningPosition(int64_t *positionFrames,
323                                                                 int64_t *timeNanos) {
324     struct audio_mmap_position position;
325     if (mMmapStream == nullptr) {
326         return AAUDIO_ERROR_NULL;
327     }
328     status_t status = mMmapStream->getMmapPosition(&position);
329     ALOGV("%s() status= %d, pos = %d, nanos = %lld\n",
330           __func__, status, position.position_frames, (long long) position.time_nanoseconds);
331     aaudio_result_t result = AAudioConvert_androidToAAudioResult(status);
332     if (result == AAUDIO_ERROR_UNAVAILABLE) {
333         ALOGW("%s(): getMmapPosition() has no position data available", __func__);
334     } else if (result != AAUDIO_OK) {
335         ALOGE("%s(): getMmapPosition() returned status %d", __func__, status);
336     } else {
337         // Convert 32-bit position to 64-bit position.
338         mFramesTransferred.update32(position.position_frames);
339         *positionFrames = mFramesTransferred.get();
340         *timeNanos = position.time_nanoseconds;
341     }
342     return result;
343 }
344 
getTimestamp(int64_t * positionFrames,int64_t * timeNanos)345 aaudio_result_t AAudioServiceEndpointMMAP::getTimestamp(int64_t *positionFrames,
346                                                     int64_t *timeNanos) {
347     return 0; // TODO
348 }
349 
350 // This is called by onTearDown() in a separate thread to avoid deadlocks.
handleTearDownAsync(audio_port_handle_t portHandle)351 void AAudioServiceEndpointMMAP::handleTearDownAsync(audio_port_handle_t portHandle) {
352     // Are we tearing down the EXCLUSIVE MMAP stream?
353     if (isStreamRegistered(portHandle)) {
354         ALOGD("%s(%d) tearing down this entire MMAP endpoint", __func__, portHandle);
355         disconnectRegisteredStreams();
356     } else {
357         // Must be a SHARED stream?
358         ALOGD("%s(%d) disconnect a specific stream", __func__, portHandle);
359         aaudio_result_t result = mAAudioService.disconnectStreamByPortHandle(portHandle);
360         ALOGD("%s(%d) disconnectStreamByPortHandle returned %d", __func__, portHandle, result);
361     }
362 };
363 
364 // This is called by AudioFlinger when it wants to destroy a stream.
onTearDown(audio_port_handle_t portHandle)365 void AAudioServiceEndpointMMAP::onTearDown(audio_port_handle_t portHandle) {
366     ALOGD("%s(portHandle = %d) called", __func__, portHandle);
367     android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
368     std::thread asyncTask([holdEndpoint, portHandle]() {
369         holdEndpoint->handleTearDownAsync(portHandle);
370     });
371     asyncTask.detach();
372 }
373 
onVolumeChanged(audio_channel_mask_t channels,android::Vector<float> values)374 void AAudioServiceEndpointMMAP::onVolumeChanged(audio_channel_mask_t channels,
375                                               android::Vector<float> values) {
376     // TODO Do we really need a different volume for each channel?
377     // We get called with an array filled with a single value!
378     float volume = values[0];
379     ALOGD("%s() volume[0] = %f", __func__, volume);
380     std::lock_guard<std::mutex> lock(mLockStreams);
381     for(const auto& stream : mRegisteredStreams) {
382         stream->onVolumeChanged(volume);
383     }
384 };
385 
onRoutingChanged(audio_port_handle_t portHandle)386 void AAudioServiceEndpointMMAP::onRoutingChanged(audio_port_handle_t portHandle) {
387     const int32_t deviceId = static_cast<int32_t>(portHandle);
388     ALOGD("%s() called with dev %d, old = %d", __func__, deviceId, getDeviceId());
389     if (getDeviceId() != deviceId) {
390         if (getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
391             android::sp<AAudioServiceEndpointMMAP> holdEndpoint(this);
392             std::thread asyncTask([holdEndpoint, deviceId]() {
393                 ALOGD("onRoutingChanged() asyncTask launched");
394                 holdEndpoint->disconnectRegisteredStreams();
395                 holdEndpoint->setDeviceId(deviceId);
396             });
397             asyncTask.detach();
398         } else {
399             setDeviceId(deviceId);
400         }
401     }
402 };
403 
404 /**
405  * Get an immutable description of the data queue from the HAL.
406  */
getDownDataDescription(AudioEndpointParcelable * parcelable)407 aaudio_result_t AAudioServiceEndpointMMAP::getDownDataDescription(
408         AudioEndpointParcelable* parcelable)
409 {
410     // Gather information on the data queue based on HAL info.
411     int32_t bytesPerFrame = calculateBytesPerFrame();
412     int32_t capacityInBytes = getBufferCapacity() * bytesPerFrame;
413     int fdIndex = parcelable->addFileDescriptor(mAudioDataFileDescriptor, capacityInBytes);
414     parcelable->mDownDataQueueParcelable.setupMemory(fdIndex, 0, capacityInBytes);
415     parcelable->mDownDataQueueParcelable.setBytesPerFrame(bytesPerFrame);
416     parcelable->mDownDataQueueParcelable.setFramesPerBurst(mFramesPerBurst);
417     parcelable->mDownDataQueueParcelable.setCapacityInFrames(getBufferCapacity());
418     return AAUDIO_OK;
419 }
420 
getExternalPosition(uint64_t * positionFrames,int64_t * timeNanos)421 aaudio_result_t AAudioServiceEndpointMMAP::getExternalPosition(uint64_t *positionFrames,
422                                                                int64_t *timeNanos)
423 {
424     if (mHalExternalPositionStatus != AAUDIO_OK) {
425         return mHalExternalPositionStatus;
426     }
427     uint64_t tempPositionFrames;
428     int64_t tempTimeNanos;
429     status_t status = mMmapStream->getExternalPosition(&tempPositionFrames, &tempTimeNanos);
430     if (status != OK) {
431         // getExternalPosition reports error. The HAL may not support the API. Cache the result
432         // so that the call will not go to the HAL next time.
433         mHalExternalPositionStatus = AAudioConvert_androidToAAudioResult(status);
434         return mHalExternalPositionStatus;
435     }
436 
437     // If the HAL keeps reporting the same position or timestamp, the HAL may be having some issues
438     // to report correct external position. In that case, we will not trust the values reported from
439     // the HAL. Ideally, we may want to stop querying external position if the HAL cannot report
440     // correct position within a period. But it may not be a good idea to get system time too often.
441     // In that case, a maximum number of frozen external position is defined so that if the
442     // count of the same timestamp or position is reported by the HAL continuously, the values from
443     // the HAL will no longer be trusted.
444     static constexpr int kMaxFrozenCount = 20;
445     // If the HAL version is less than 7.0, the getPresentationPosition is an optional API.
446     // If the HAL version is 7.0 or later, the getPresentationPosition is a mandatory API.
447     // In that case, even the returned status is NO_ERROR, it doesn't indicate the returned
448     // position is a valid one. Do a simple validation, which is checking if the position is
449     // forward within half a second or not, here so that this function can return error if
450     // the validation fails. Note that we don't only apply this validation logic to HAL API
451     // less than 7.0. The reason is that there is a chance the HAL is not reporting the
452     // timestamp and position correctly.
453     if (mLastPositionFrames > tempPositionFrames) {
454         // If the position is going backwards, there must be something wrong with the HAL.
455         // In that case, we do not trust the values reported by the HAL.
456         ALOGW("%s position is going backwards, last position(%jd) current position(%jd)",
457               __func__, mLastPositionFrames, tempPositionFrames);
458         mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
459         return mHalExternalPositionStatus;
460     } else if (mLastPositionFrames == tempPositionFrames) {
461         if (tempTimeNanos - mTimestampNanosForLastPosition >
462                 AAUDIO_NANOS_PER_MILLISECOND * mTimestampGracePeriodMs) {
463             ALOGW("%s, the reported position is not changed within %d msec. "
464                   "Set the external position as not supported", __func__, mTimestampGracePeriodMs);
465             mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
466             return mHalExternalPositionStatus;
467         }
468         mFrozenPositionCount++;
469     } else {
470         mFrozenPositionCount = 0;
471     }
472 
473     if (mTimestampNanosForLastPosition > tempTimeNanos) {
474         // If the timestamp is going backwards, there must be something wrong with the HAL.
475         // In that case, we do not trust the values reported by the HAL.
476         ALOGW("%s timestamp is going backwards, last timestamp(%jd), current timestamp(%jd)",
477               __func__, mTimestampNanosForLastPosition, tempTimeNanos);
478         mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
479         return mHalExternalPositionStatus;
480     } else if (mTimestampNanosForLastPosition == tempTimeNanos) {
481         mFrozenTimestampCount++;
482     } else {
483         mFrozenTimestampCount = 0;
484     }
485 
486     if (mFrozenTimestampCount + mFrozenPositionCount > kMaxFrozenCount) {
487         ALOGW("%s too many frozen external position from HAL.", __func__);
488         mHalExternalPositionStatus = AAUDIO_ERROR_INTERNAL;
489         return mHalExternalPositionStatus;
490     }
491 
492     mLastPositionFrames = tempPositionFrames;
493     mTimestampNanosForLastPosition = tempTimeNanos;
494 
495     // Only update the timestamp and position when they looks valid.
496     *positionFrames = tempPositionFrames;
497     *timeNanos = tempTimeNanos;
498     return mHalExternalPositionStatus;
499 }
500 
createMmapBuffer(android::base::unique_fd * fileDescriptor)501 aaudio_result_t AAudioServiceEndpointMMAP::createMmapBuffer(
502         android::base::unique_fd* fileDescriptor)
503 {
504     memset(&mMmapBufferinfo, 0, sizeof(struct audio_mmap_buffer_info));
505     int32_t minSizeFrames = getBufferCapacity();
506     if (minSizeFrames <= 0) { // zero will get rejected
507         minSizeFrames = AAUDIO_BUFFER_CAPACITY_MIN;
508     }
509     status_t status = mMmapStream->createMmapBuffer(minSizeFrames, &mMmapBufferinfo);
510     bool isBufferShareable = mMmapBufferinfo.flags & AUDIO_MMAP_APPLICATION_SHAREABLE;
511     if (status != OK) {
512         ALOGE("%s() - createMmapBuffer() failed with status %d %s",
513               __func__, status, strerror(-status));
514         return AAUDIO_ERROR_UNAVAILABLE;
515     } else {
516         ALOGD("%s() createMmapBuffer() buffer_size = %d fr, burst_size %d fr"
517                       ", Sharable FD: %s",
518               __func__,
519               mMmapBufferinfo.buffer_size_frames,
520               mMmapBufferinfo.burst_size_frames,
521               isBufferShareable ? "Yes" : "No");
522     }
523 
524     setBufferCapacity(mMmapBufferinfo.buffer_size_frames);
525     if (!isBufferShareable) {
526         // Exclusive mode can only be used by the service because the FD cannot be shared.
527         int32_t audioServiceUid =
528             VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
529         if ((mMmapClient.attributionSource.uid != audioServiceUid) &&
530             getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) {
531             ALOGW("%s() - exclusive FD cannot be used by client", __func__);
532             return AAUDIO_ERROR_UNAVAILABLE;
533         }
534     }
535 
536     // AAudio creates a copy of this FD and retains ownership of the copy.
537     // Assume that AudioFlinger will close the original shared_memory_fd.
538     fileDescriptor->reset(dup(mMmapBufferinfo.shared_memory_fd));
539     if (fileDescriptor->get() == -1) {
540         ALOGE("%s() - could not dup shared_memory_fd", __func__);
541         return AAUDIO_ERROR_INTERNAL;
542     }
543 
544     // Call to HAL to make sure the transport FD was able to be closed by binder.
545     // This is a tricky workaround for a problem in Binder.
546     // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code.
547     struct audio_mmap_position position;
548     mMmapStream->getMmapPosition(&position);
549 
550     mFramesPerBurst = mMmapBufferinfo.burst_size_frames;
551 
552     return AAUDIO_OK;
553 }
554