1 /*
2 **
3 ** Copyright 2007, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 //#define LOG_NDEBUG 0
19 #define LOG_TAG "AudioTrack"
20 
21 #include <inttypes.h>
22 #include <math.h>
23 #include <sys/resource.h>
24 
25 #include <android-base/macros.h>
26 #include <audio_utils/clock.h>
27 #include <audio_utils/primitives.h>
28 #include <binder/IPCThreadState.h>
29 #include <media/AudioTrack.h>
30 #include <utils/Log.h>
31 #include <private/media/AudioTrackShared.h>
32 #include <processgroup/sched_policy.h>
33 #include <media/IAudioFlinger.h>
34 #include <media/IAudioPolicyService.h>
35 #include <media/AudioParameter.h>
36 #include <media/AudioResamplerPublic.h>
37 #include <media/AudioSystem.h>
38 #include <media/MediaMetricsItem.h>
39 #include <media/TypeConverter.h>
40 
41 #define WAIT_PERIOD_MS                  10
42 #define WAIT_STREAM_END_TIMEOUT_SEC     120
43 static const int kMaxLoopCountNotifications = 32;
44 
45 namespace android {
46 // ---------------------------------------------------------------------------
47 
48 using media::VolumeShaper;
49 
50 // TODO: Move to a separate .h
51 
52 template <typename T>
min(const T & x,const T & y)53 static inline const T &min(const T &x, const T &y) {
54     return x < y ? x : y;
55 }
56 
57 template <typename T>
max(const T & x,const T & y)58 static inline const T &max(const T &x, const T &y) {
59     return x > y ? x : y;
60 }
61 
framesToNanoseconds(ssize_t frames,uint32_t sampleRate,float speed)62 static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
63 {
64     return ((double)frames * 1000000000) / ((double)sampleRate * speed);
65 }
66 
convertTimespecToUs(const struct timespec & tv)67 static int64_t convertTimespecToUs(const struct timespec &tv)
68 {
69     return tv.tv_sec * 1000000LL + tv.tv_nsec / 1000;
70 }
71 
72 // TODO move to audio_utils.
convertNsToTimespec(int64_t ns)73 static inline struct timespec convertNsToTimespec(int64_t ns) {
74     struct timespec tv;
75     tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
76     tv.tv_nsec = static_cast<int64_t>(ns % NANOS_PER_SECOND);
77     return tv;
78 }
79 
80 // current monotonic time in microseconds.
getNowUs()81 static int64_t getNowUs()
82 {
83     struct timespec tv;
84     (void) clock_gettime(CLOCK_MONOTONIC, &tv);
85     return convertTimespecToUs(tv);
86 }
87 
88 // FIXME: we don't use the pitch setting in the time stretcher (not working);
89 // instead we emulate it using our sample rate converter.
90 static const bool kFixPitch = true; // enable pitch fix
adjustSampleRate(uint32_t sampleRate,float pitch)91 static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
92 {
93     return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
94 }
95 
adjustSpeed(float speed,float pitch)96 static inline float adjustSpeed(float speed, float pitch)
97 {
98     return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
99 }
100 
adjustPitch(float pitch)101 static inline float adjustPitch(float pitch)
102 {
103     return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
104 }
105 
106 // static
getMinFrameCount(size_t * frameCount,audio_stream_type_t streamType,uint32_t sampleRate)107 status_t AudioTrack::getMinFrameCount(
108         size_t* frameCount,
109         audio_stream_type_t streamType,
110         uint32_t sampleRate)
111 {
112     if (frameCount == NULL) {
113         return BAD_VALUE;
114     }
115 
116     // FIXME handle in server, like createTrack_l(), possible missing info:
117     //          audio_io_handle_t output
118     //          audio_format_t format
119     //          audio_channel_mask_t channelMask
120     //          audio_output_flags_t flags (FAST)
121     uint32_t afSampleRate;
122     status_t status;
123     status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
124     if (status != NO_ERROR) {
125         ALOGE("%s(): Unable to query output sample rate for stream type %d; status %d",
126                 __func__, streamType, status);
127         return status;
128     }
129     size_t afFrameCount;
130     status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
131     if (status != NO_ERROR) {
132         ALOGE("%s(): Unable to query output frame count for stream type %d; status %d",
133                 __func__, streamType, status);
134         return status;
135     }
136     uint32_t afLatency;
137     status = AudioSystem::getOutputLatency(&afLatency, streamType);
138     if (status != NO_ERROR) {
139         ALOGE("%s(): Unable to query output latency for stream type %d; status %d",
140                 __func__, streamType, status);
141         return status;
142     }
143 
144     // When called from createTrack, speed is 1.0f (normal speed).
145     // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
146     *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
147                                               sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
148 
149     // The formula above should always produce a non-zero value under normal circumstances:
150     // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
151     // Return error in the unlikely event that it does not, as that's part of the API contract.
152     if (*frameCount == 0) {
153         ALOGE("%s(): failed for streamType %d, sampleRate %u",
154                 __func__, streamType, sampleRate);
155         return BAD_VALUE;
156     }
157     ALOGV("%s(): getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
158             __func__, *frameCount, afFrameCount, afSampleRate, afLatency);
159     return NO_ERROR;
160 }
161 
162 // static
isDirectOutputSupported(const audio_config_base_t & config,const audio_attributes_t & attributes)163 bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config,
164                                          const audio_attributes_t& attributes) {
165     ALOGV("%s()", __FUNCTION__);
166     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
167     if (aps == 0) return false;
168     return aps->isDirectOutputSupported(config, attributes);
169 }
170 
171 // ---------------------------------------------------------------------------
172 
gather(const AudioTrack * track)173 void AudioTrack::MediaMetrics::gather(const AudioTrack *track)
174 {
175     // only if we're in a good state...
176     // XXX: shall we gather alternative info if failing?
177     const status_t lstatus = track->initCheck();
178     if (lstatus != NO_ERROR) {
179         ALOGD("%s(): no metrics gathered, track status=%d", __func__, (int) lstatus);
180         return;
181     }
182 
183 #define MM_PREFIX "android.media.audiotrack." // avoid cut-n-paste errors.
184 
185     // Java API 28 entries, do not change.
186     mMetricsItem->setCString(MM_PREFIX "streamtype", toString(track->streamType()).c_str());
187     mMetricsItem->setCString(MM_PREFIX "type",
188             toString(track->mAttributes.content_type).c_str());
189     mMetricsItem->setCString(MM_PREFIX "usage", toString(track->mAttributes.usage).c_str());
190 
191     // Non-API entries, these can change due to a Java string mistake.
192     mMetricsItem->setInt32(MM_PREFIX "sampleRate", (int32_t)track->mSampleRate);
193     mMetricsItem->setInt64(MM_PREFIX "channelMask", (int64_t)track->mChannelMask);
194     // Non-API entries, these can change.
195     mMetricsItem->setInt32(MM_PREFIX "portId", (int32_t)track->mPortId);
196     mMetricsItem->setCString(MM_PREFIX "encoding", toString(track->mFormat).c_str());
197     mMetricsItem->setInt32(MM_PREFIX "frameCount", (int32_t)track->mFrameCount);
198     mMetricsItem->setCString(MM_PREFIX "attributes", toString(track->mAttributes).c_str());
199 }
200 
201 // hand the user a snapshot of the metrics.
getMetrics(mediametrics::Item * & item)202 status_t AudioTrack::getMetrics(mediametrics::Item * &item)
203 {
204     mMediaMetrics.gather(this);
205     mediametrics::Item *tmp = mMediaMetrics.dup();
206     if (tmp == nullptr) {
207         return BAD_VALUE;
208     }
209     item = tmp;
210     return NO_ERROR;
211 }
212 
AudioTrack()213 AudioTrack::AudioTrack()
214     : mStatus(NO_INIT),
215       mState(STATE_STOPPED),
216       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
217       mPreviousSchedulingGroup(SP_DEFAULT),
218       mPausedPosition(0),
219       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
220       mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
221       mAudioTrackCallback(new AudioTrackCallback())
222 {
223     mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
224     mAttributes.usage = AUDIO_USAGE_UNKNOWN;
225     mAttributes.flags = 0x0;
226     strcpy(mAttributes.tags, "");
227 }
228 
AudioTrack(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,uid_t uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed,audio_port_handle_t selectedDeviceId)229 AudioTrack::AudioTrack(
230         audio_stream_type_t streamType,
231         uint32_t sampleRate,
232         audio_format_t format,
233         audio_channel_mask_t channelMask,
234         size_t frameCount,
235         audio_output_flags_t flags,
236         callback_t cbf,
237         void* user,
238         int32_t notificationFrames,
239         audio_session_t sessionId,
240         transfer_type transferType,
241         const audio_offload_info_t *offloadInfo,
242         uid_t uid,
243         pid_t pid,
244         const audio_attributes_t* pAttributes,
245         bool doNotReconnect,
246         float maxRequiredSpeed,
247         audio_port_handle_t selectedDeviceId)
248     : mStatus(NO_INIT),
249       mState(STATE_STOPPED),
250       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
251       mPreviousSchedulingGroup(SP_DEFAULT),
252       mPausedPosition(0),
253       mAudioTrackCallback(new AudioTrackCallback())
254 {
255     mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
256 
257     (void)set(streamType, sampleRate, format, channelMask,
258             frameCount, flags, cbf, user, notificationFrames,
259             0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
260             offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
261 }
262 
AudioTrack(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,const sp<IMemory> & sharedBuffer,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,uid_t uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed)263 AudioTrack::AudioTrack(
264         audio_stream_type_t streamType,
265         uint32_t sampleRate,
266         audio_format_t format,
267         audio_channel_mask_t channelMask,
268         const sp<IMemory>& sharedBuffer,
269         audio_output_flags_t flags,
270         callback_t cbf,
271         void* user,
272         int32_t notificationFrames,
273         audio_session_t sessionId,
274         transfer_type transferType,
275         const audio_offload_info_t *offloadInfo,
276         uid_t uid,
277         pid_t pid,
278         const audio_attributes_t* pAttributes,
279         bool doNotReconnect,
280         float maxRequiredSpeed)
281     : mStatus(NO_INIT),
282       mState(STATE_STOPPED),
283       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
284       mPreviousSchedulingGroup(SP_DEFAULT),
285       mPausedPosition(0),
286       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
287       mAudioTrackCallback(new AudioTrackCallback())
288 {
289     mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
290 
291     (void)set(streamType, sampleRate, format, channelMask,
292             0 /*frameCount*/, flags, cbf, user, notificationFrames,
293             sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
294             uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
295 }
296 
~AudioTrack()297 AudioTrack::~AudioTrack()
298 {
299     // pull together the numbers, before we clean up our structures
300     mMediaMetrics.gather(this);
301 
302     mediametrics::LogItem(mMetricsId)
303         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
304         .set(AMEDIAMETRICS_PROP_CALLERNAME,
305                 mCallerName.empty()
306                 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
307                 : mCallerName.c_str())
308         .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
309         .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)mStatus)
310         .record();
311 
312     if (mStatus == NO_ERROR) {
313         // Make sure that callback function exits in the case where
314         // it is looping on buffer full condition in obtainBuffer().
315         // Otherwise the callback thread will never exit.
316         stop();
317         if (mAudioTrackThread != 0) {
318             mProxy->interrupt();
319             mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
320             mAudioTrackThread->requestExitAndWait();
321             mAudioTrackThread.clear();
322         }
323         // No lock here: worst case we remove a NULL callback which will be a nop
324         if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
325             AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
326         }
327         IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
328         mAudioTrack.clear();
329         mCblkMemory.clear();
330         mSharedBuffer.clear();
331         IPCThreadState::self()->flushCommands();
332         ALOGV("%s(%d), releasing session id %d from %d on behalf of %d",
333                 __func__, mPortId,
334                 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
335         AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
336     }
337 }
338 
set(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,const sp<IMemory> & sharedBuffer,bool threadCanCallJava,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,uid_t uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed,audio_port_handle_t selectedDeviceId)339 status_t AudioTrack::set(
340         audio_stream_type_t streamType,
341         uint32_t sampleRate,
342         audio_format_t format,
343         audio_channel_mask_t channelMask,
344         size_t frameCount,
345         audio_output_flags_t flags,
346         callback_t cbf,
347         void* user,
348         int32_t notificationFrames,
349         const sp<IMemory>& sharedBuffer,
350         bool threadCanCallJava,
351         audio_session_t sessionId,
352         transfer_type transferType,
353         const audio_offload_info_t *offloadInfo,
354         uid_t uid,
355         pid_t pid,
356         const audio_attributes_t* pAttributes,
357         bool doNotReconnect,
358         float maxRequiredSpeed,
359         audio_port_handle_t selectedDeviceId)
360 {
361     status_t status;
362     uint32_t channelCount;
363     pid_t callingPid;
364     pid_t myPid;
365 
366     // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set.
367     ALOGV("%s(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
368           "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
369           __func__,
370           streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
371           sessionId, transferType, uid, pid);
372 
373     mThreadCanCallJava = threadCanCallJava;
374     mSelectedDeviceId = selectedDeviceId;
375     mSessionId = sessionId;
376 
377     switch (transferType) {
378     case TRANSFER_DEFAULT:
379         if (sharedBuffer != 0) {
380             transferType = TRANSFER_SHARED;
381         } else if (cbf == NULL || threadCanCallJava) {
382             transferType = TRANSFER_SYNC;
383         } else {
384             transferType = TRANSFER_CALLBACK;
385         }
386         break;
387     case TRANSFER_CALLBACK:
388     case TRANSFER_SYNC_NOTIF_CALLBACK:
389         if (cbf == NULL || sharedBuffer != 0) {
390             ALOGE("%s(): Transfer type %s but cbf == NULL || sharedBuffer != 0",
391                     convertTransferToText(transferType), __func__);
392             status = BAD_VALUE;
393             goto exit;
394         }
395         break;
396     case TRANSFER_OBTAIN:
397     case TRANSFER_SYNC:
398         if (sharedBuffer != 0) {
399             ALOGE("%s(): Transfer type TRANSFER_OBTAIN but sharedBuffer != 0", __func__);
400             status = BAD_VALUE;
401             goto exit;
402         }
403         break;
404     case TRANSFER_SHARED:
405         if (sharedBuffer == 0) {
406             ALOGE("%s(): Transfer type TRANSFER_SHARED but sharedBuffer == 0", __func__);
407             status = BAD_VALUE;
408             goto exit;
409         }
410         break;
411     default:
412         ALOGE("%s(): Invalid transfer type %d",
413                 __func__, transferType);
414         status = BAD_VALUE;
415         goto exit;
416     }
417     mSharedBuffer = sharedBuffer;
418     mTransfer = transferType;
419     mDoNotReconnect = doNotReconnect;
420 
421     ALOGV_IF(sharedBuffer != 0, "%s(): sharedBuffer: %p, size: %zu",
422             __func__, sharedBuffer->unsecurePointer(), sharedBuffer->size());
423 
424     ALOGV("%s(): streamType %d frameCount %zu flags %04x",
425             __func__, streamType, frameCount, flags);
426 
427     // invariant that mAudioTrack != 0 is true only after set() returns successfully
428     if (mAudioTrack != 0) {
429         ALOGE("%s(): Track already in use", __func__);
430         status = INVALID_OPERATION;
431         goto exit;
432     }
433 
434     // handle default values first.
435     if (streamType == AUDIO_STREAM_DEFAULT) {
436         streamType = AUDIO_STREAM_MUSIC;
437     }
438     if (pAttributes == NULL) {
439         if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
440             ALOGE("%s(): Invalid stream type %d", __func__, streamType);
441             status = BAD_VALUE;
442             goto exit;
443         }
444         mStreamType = streamType;
445 
446     } else {
447         // stream type shouldn't be looked at, this track has audio attributes
448         memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
449         ALOGV("%s(): Building AudioTrack with attributes:"
450                 " usage=%d content=%d flags=0x%x tags=[%s]",
451                 __func__,
452                  mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
453         mStreamType = AUDIO_STREAM_DEFAULT;
454         audio_flags_to_audio_output_flags(mAttributes.flags, &flags);
455     }
456 
457     // these below should probably come from the audioFlinger too...
458     if (format == AUDIO_FORMAT_DEFAULT) {
459         format = AUDIO_FORMAT_PCM_16_BIT;
460     } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
461         mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
462     }
463 
464     // validate parameters
465     if (!audio_is_valid_format(format)) {
466         ALOGE("%s(): Invalid format %#x", __func__, format);
467         status = BAD_VALUE;
468         goto exit;
469     }
470     mFormat = format;
471 
472     if (!audio_is_output_channel(channelMask)) {
473         ALOGE("%s(): Invalid channel mask %#x",  __func__, channelMask);
474         status = BAD_VALUE;
475         goto exit;
476     }
477     mChannelMask = channelMask;
478     channelCount = audio_channel_count_from_out_mask(channelMask);
479     mChannelCount = channelCount;
480 
481     // force direct flag if format is not linear PCM
482     // or offload was requested
483     if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
484             || !audio_is_linear_pcm(format)) {
485         ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
486                     ? "%s(): Offload request, forcing to Direct Output"
487                     : "%s(): Not linear PCM, forcing to Direct Output",
488                     __func__);
489         flags = (audio_output_flags_t)
490                 // FIXME why can't we allow direct AND fast?
491                 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
492     }
493 
494     // force direct flag if HW A/V sync requested
495     if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
496         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
497     }
498 
499     if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
500         if (audio_has_proportional_frames(format)) {
501             mFrameSize = channelCount * audio_bytes_per_sample(format);
502         } else {
503             mFrameSize = sizeof(uint8_t);
504         }
505     } else {
506         ALOG_ASSERT(audio_has_proportional_frames(format));
507         mFrameSize = channelCount * audio_bytes_per_sample(format);
508         // createTrack will return an error if PCM format is not supported by server,
509         // so no need to check for specific PCM formats here
510     }
511 
512     // sampling rate must be specified for direct outputs
513     if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
514         status = BAD_VALUE;
515         goto exit;
516     }
517     mSampleRate = sampleRate;
518     mOriginalSampleRate = sampleRate;
519     mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
520     // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
521     mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
522 
523     // Make copy of input parameter offloadInfo so that in the future:
524     //  (a) createTrack_l doesn't need it as an input parameter
525     //  (b) we can support re-creation of offloaded tracks
526     if (offloadInfo != NULL) {
527         mOffloadInfoCopy = *offloadInfo;
528         mOffloadInfo = &mOffloadInfoCopy;
529     } else {
530         mOffloadInfo = NULL;
531         memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
532     }
533 
534     mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
535     mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
536     mSendLevel = 0.0f;
537     // mFrameCount is initialized in createTrack_l
538     mReqFrameCount = frameCount;
539     if (notificationFrames >= 0) {
540         mNotificationFramesReq = notificationFrames;
541         mNotificationsPerBufferReq = 0;
542     } else {
543         if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
544             ALOGE("%s(): notificationFrames=%d not permitted for non-fast track",
545                     __func__, notificationFrames);
546             status = BAD_VALUE;
547             goto exit;
548         }
549         if (frameCount > 0) {
550             ALOGE("%s(): notificationFrames=%d not permitted with non-zero frameCount=%zu",
551                     __func__, notificationFrames, frameCount);
552             status = BAD_VALUE;
553             goto exit;
554         }
555         mNotificationFramesReq = 0;
556         const uint32_t minNotificationsPerBuffer = 1;
557         const uint32_t maxNotificationsPerBuffer = 8;
558         mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
559                 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
560         ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
561                 "%s(): notificationFrames=%d clamped to the range -%u to -%u",
562                 __func__,
563                 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
564     }
565     mNotificationFramesAct = 0;
566     callingPid = IPCThreadState::self()->getCallingPid();
567     myPid = getpid();
568     if (uid == AUDIO_UID_INVALID || (callingPid != myPid)) {
569         mClientUid = IPCThreadState::self()->getCallingUid();
570     } else {
571         mClientUid = uid;
572     }
573     if (pid == -1 || (callingPid != myPid)) {
574         mClientPid = callingPid;
575     } else {
576         mClientPid = pid;
577     }
578     mAuxEffectId = 0;
579     mOrigFlags = mFlags = flags;
580     mCbf = cbf;
581 
582     if (cbf != NULL) {
583         mAudioTrackThread = new AudioTrackThread(*this);
584         mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
585         // thread begins in paused state, and will not reference us until start()
586     }
587 
588     // create the IAudioTrack
589     {
590         AutoMutex lock(mLock);
591         status = createTrack_l();
592     }
593     if (status != NO_ERROR) {
594         if (mAudioTrackThread != 0) {
595             mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
596             mAudioTrackThread->requestExitAndWait();
597             mAudioTrackThread.clear();
598         }
599         goto exit;
600     }
601 
602     mUserData = user;
603     mLoopCount = 0;
604     mLoopStart = 0;
605     mLoopEnd = 0;
606     mLoopCountNotified = 0;
607     mMarkerPosition = 0;
608     mMarkerReached = false;
609     mNewPosition = 0;
610     mUpdatePeriod = 0;
611     mPosition = 0;
612     mReleased = 0;
613     mStartNs = 0;
614     mStartFromZeroUs = 0;
615     AudioSystem::acquireAudioSessionId(mSessionId, mClientPid, mClientUid);
616     mSequence = 1;
617     mObservedSequence = mSequence;
618     mInUnderrun = false;
619     mPreviousTimestampValid = false;
620     mTimestampStartupGlitchReported = false;
621     mTimestampRetrogradePositionReported = false;
622     mTimestampRetrogradeTimeReported = false;
623     mTimestampStallReported = false;
624     mTimestampStaleTimeReported = false;
625     mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
626     mStartTs.mPosition = 0;
627     mUnderrunCountOffset = 0;
628     mFramesWritten = 0;
629     mFramesWrittenServerOffset = 0;
630     mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
631     mVolumeHandler = new media::VolumeHandler();
632 
633 exit:
634     mStatus = status;
635     return status;
636 }
637 
638 // -------------------------------------------------------------------------
639 
start()640 status_t AudioTrack::start()
641 {
642     AutoMutex lock(mLock);
643 
644     if (mState == STATE_ACTIVE) {
645         return INVALID_OPERATION;
646     }
647 
648     ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
649 
650     // Defer logging here due to OpenSL ES repeated start calls.
651     // TODO(b/154868033) after fix, restore this logging back to the beginning of start().
652     const int64_t beginNs = systemTime();
653     status_t status = NO_ERROR; // logged: make sure to set this before returning.
654     mediametrics::Defer defer([&] {
655         mediametrics::LogItem(mMetricsId)
656             .set(AMEDIAMETRICS_PROP_CALLERNAME,
657                     mCallerName.empty()
658                     ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
659                     : mCallerName.c_str())
660             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
661             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
662             .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
663             .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
664             .record(); });
665 
666 
667     mInUnderrun = true;
668 
669     State previousState = mState;
670     if (previousState == STATE_PAUSED_STOPPING) {
671         mState = STATE_STOPPING;
672     } else {
673         mState = STATE_ACTIVE;
674     }
675     (void) updateAndGetPosition_l();
676 
677     // save start timestamp
678     if (isOffloadedOrDirect_l()) {
679         if (getTimestamp_l(mStartTs) != OK) {
680             mStartTs.mPosition = 0;
681         }
682     } else {
683         if (getTimestamp_l(&mStartEts) != OK) {
684             mStartEts.clear();
685         }
686     }
687     mStartNs = systemTime(); // save this for timestamp adjustment after starting.
688     if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
689         // reset current position as seen by client to 0
690         mPosition = 0;
691         mPreviousTimestampValid = false;
692         mTimestampStartupGlitchReported = false;
693         mTimestampRetrogradePositionReported = false;
694         mTimestampRetrogradeTimeReported = false;
695         mTimestampStallReported = false;
696         mTimestampStaleTimeReported = false;
697         mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
698 
699         if (!isOffloadedOrDirect_l()
700                 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
701             // Server side has consumed something, but is it finished consuming?
702             // It is possible since flush and stop are asynchronous that the server
703             // is still active at this point.
704             ALOGV("%s(%d): server read:%lld  cumulative flushed:%lld  client written:%lld",
705                     __func__, mPortId,
706                     (long long)(mFramesWrittenServerOffset
707                             + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
708                     (long long)mStartEts.mFlushed,
709                     (long long)mFramesWritten);
710             // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
711             mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
712         }
713         mFramesWritten = 0;
714         mProxy->clearTimestamp(); // need new server push for valid timestamp
715         mMarkerReached = false;
716 
717         // For offloaded tracks, we don't know if the hardware counters are really zero here,
718         // since the flush is asynchronous and stop may not fully drain.
719         // We save the time when the track is started to later verify whether
720         // the counters are realistic (i.e. start from zero after this time).
721         mStartFromZeroUs = mStartNs / 1000;
722 
723         // force refresh of remaining frames by processAudioBuffer() as last
724         // write before stop could be partial.
725         mRefreshRemaining = true;
726 
727         // for static track, clear the old flags when starting from stopped state
728         if (mSharedBuffer != 0) {
729             android_atomic_and(
730             ~(CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
731             &mCblk->mFlags);
732         }
733     }
734     mNewPosition = mPosition + mUpdatePeriod;
735     int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
736 
737     if (!(flags & CBLK_INVALID)) {
738         status = mAudioTrack->start();
739         if (status == DEAD_OBJECT) {
740             flags |= CBLK_INVALID;
741         }
742     }
743     if (flags & CBLK_INVALID) {
744         status = restoreTrack_l("start");
745     }
746 
747     // resume or pause the callback thread as needed.
748     sp<AudioTrackThread> t = mAudioTrackThread;
749     if (status == NO_ERROR) {
750         if (t != 0) {
751             if (previousState == STATE_STOPPING) {
752                 mProxy->interrupt();
753             } else {
754                 t->resume();
755             }
756         } else {
757             mPreviousPriority = getpriority(PRIO_PROCESS, 0);
758             get_sched_policy(0, &mPreviousSchedulingGroup);
759             androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
760         }
761 
762         // Start our local VolumeHandler for restoration purposes.
763         mVolumeHandler->setStarted();
764     } else {
765         ALOGE("%s(%d): status %d", __func__, mPortId, status);
766         mState = previousState;
767         if (t != 0) {
768             if (previousState != STATE_STOPPING) {
769                 t->pause();
770             }
771         } else {
772             setpriority(PRIO_PROCESS, 0, mPreviousPriority);
773             set_sched_policy(0, mPreviousSchedulingGroup);
774         }
775     }
776 
777     return status;
778 }
779 
stop()780 void AudioTrack::stop()
781 {
782     const int64_t beginNs = systemTime();
783 
784     AutoMutex lock(mLock);
785     mediametrics::Defer defer([&]() {
786         mediametrics::LogItem(mMetricsId)
787             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
788             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
789             .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
790             .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
791             .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getUnderrunCount_l())
792             .record();
793     });
794 
795     ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
796 
797     if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
798         return;
799     }
800 
801     if (isOffloaded_l()) {
802         mState = STATE_STOPPING;
803     } else {
804         mState = STATE_STOPPED;
805         ALOGD_IF(mSharedBuffer == nullptr,
806                 "%s(%d): called with %u frames delivered", __func__, mPortId, mReleased.value());
807         mReleased = 0;
808     }
809 
810     mProxy->stop(); // notify server not to read beyond current client position until start().
811     mProxy->interrupt();
812     mAudioTrack->stop();
813 
814     // Note: legacy handling - stop does not clear playback marker
815     // and periodic update counter, but flush does for streaming tracks.
816 
817     if (mSharedBuffer != 0) {
818         // clear buffer position and loop count.
819         mStaticProxy->setBufferPositionAndLoop(0 /* position */,
820                 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
821     }
822 
823     sp<AudioTrackThread> t = mAudioTrackThread;
824     if (t != 0) {
825         if (!isOffloaded_l()) {
826             t->pause();
827         } else if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
828             // causes wake up of the playback thread, that will callback the client for
829             // EVENT_STREAM_END in processAudioBuffer()
830             t->wake();
831         }
832     } else {
833         setpriority(PRIO_PROCESS, 0, mPreviousPriority);
834         set_sched_policy(0, mPreviousSchedulingGroup);
835     }
836 }
837 
stopped() const838 bool AudioTrack::stopped() const
839 {
840     AutoMutex lock(mLock);
841     return mState != STATE_ACTIVE;
842 }
843 
flush()844 void AudioTrack::flush()
845 {
846     const int64_t beginNs = systemTime();
847     AutoMutex lock(mLock);
848     mediametrics::Defer defer([&]() {
849         mediametrics::LogItem(mMetricsId)
850             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
851             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
852             .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
853             .record(); });
854 
855     ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
856 
857     if (mSharedBuffer != 0) {
858         return;
859     }
860     if (mState == STATE_ACTIVE) {
861         return;
862     }
863     flush_l();
864 }
865 
flush_l()866 void AudioTrack::flush_l()
867 {
868     ALOG_ASSERT(mState != STATE_ACTIVE);
869 
870     // clear playback marker and periodic update counter
871     mMarkerPosition = 0;
872     mMarkerReached = false;
873     mUpdatePeriod = 0;
874     mRefreshRemaining = true;
875 
876     mState = STATE_FLUSHED;
877     mReleased = 0;
878     if (isOffloaded_l()) {
879         mProxy->interrupt();
880     }
881     mProxy->flush();
882     mAudioTrack->flush();
883 }
884 
pause()885 void AudioTrack::pause()
886 {
887     const int64_t beginNs = systemTime();
888     AutoMutex lock(mLock);
889     mediametrics::Defer defer([&]() {
890         mediametrics::LogItem(mMetricsId)
891             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
892             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
893             .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
894             .record(); });
895 
896     ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
897 
898     if (mState == STATE_ACTIVE) {
899         mState = STATE_PAUSED;
900     } else if (mState == STATE_STOPPING) {
901         mState = STATE_PAUSED_STOPPING;
902     } else {
903         return;
904     }
905     mProxy->interrupt();
906     mAudioTrack->pause();
907 
908     if (isOffloaded_l()) {
909         if (mOutput != AUDIO_IO_HANDLE_NONE) {
910             // An offload output can be re-used between two audio tracks having
911             // the same configuration. A timestamp query for a paused track
912             // while the other is running would return an incorrect time.
913             // To fix this, cache the playback position on a pause() and return
914             // this time when requested until the track is resumed.
915 
916             // OffloadThread sends HAL pause in its threadLoop. Time saved
917             // here can be slightly off.
918 
919             // TODO: check return code for getRenderPosition.
920 
921             uint32_t halFrames;
922             AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
923             ALOGV("%s(%d): for offload, cache current position %u",
924                     __func__, mPortId, mPausedPosition);
925         }
926     }
927 }
928 
setVolume(float left,float right)929 status_t AudioTrack::setVolume(float left, float right)
930 {
931     // This duplicates a test by AudioTrack JNI, but that is not the only caller
932     if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
933             isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
934         return BAD_VALUE;
935     }
936 
937     mediametrics::LogItem(mMetricsId)
938         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOLUME)
939         .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)left)
940         .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)right)
941         .record();
942 
943     AutoMutex lock(mLock);
944     mVolume[AUDIO_INTERLEAVE_LEFT] = left;
945     mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
946 
947     mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
948 
949     if (isOffloaded_l()) {
950         mAudioTrack->signal();
951     }
952     return NO_ERROR;
953 }
954 
setVolume(float volume)955 status_t AudioTrack::setVolume(float volume)
956 {
957     return setVolume(volume, volume);
958 }
959 
setAuxEffectSendLevel(float level)960 status_t AudioTrack::setAuxEffectSendLevel(float level)
961 {
962     // This duplicates a test by AudioTrack JNI, but that is not the only caller
963     if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
964         return BAD_VALUE;
965     }
966 
967     AutoMutex lock(mLock);
968     mSendLevel = level;
969     mProxy->setSendLevel(level);
970 
971     return NO_ERROR;
972 }
973 
getAuxEffectSendLevel(float * level) const974 void AudioTrack::getAuxEffectSendLevel(float* level) const
975 {
976     if (level != NULL) {
977         *level = mSendLevel;
978     }
979 }
980 
setSampleRate(uint32_t rate)981 status_t AudioTrack::setSampleRate(uint32_t rate)
982 {
983     AutoMutex lock(mLock);
984     ALOGV("%s(%d): prior state:%s rate:%u", __func__, mPortId, stateToString(mState), rate);
985 
986     if (rate == mSampleRate) {
987         return NO_ERROR;
988     }
989     if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)
990             || (mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL)) {
991         return INVALID_OPERATION;
992     }
993     if (mOutput == AUDIO_IO_HANDLE_NONE) {
994         return NO_INIT;
995     }
996     // NOTE: it is theoretically possible, but highly unlikely, that a device change
997     // could mean a previously allowed sampling rate is no longer allowed.
998     uint32_t afSamplingRate;
999     if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
1000         return NO_INIT;
1001     }
1002     // pitch is emulated by adjusting speed and sampleRate
1003     const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
1004     if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
1005         return BAD_VALUE;
1006     }
1007     // TODO: Should we also check if the buffer size is compatible?
1008 
1009     mSampleRate = rate;
1010     mProxy->setSampleRate(effectiveSampleRate);
1011 
1012     return NO_ERROR;
1013 }
1014 
getSampleRate() const1015 uint32_t AudioTrack::getSampleRate() const
1016 {
1017     AutoMutex lock(mLock);
1018 
1019     // sample rate can be updated during playback by the offloaded decoder so we need to
1020     // query the HAL and update if needed.
1021 // FIXME use Proxy return channel to update the rate from server and avoid polling here
1022     if (isOffloadedOrDirect_l()) {
1023         if (mOutput != AUDIO_IO_HANDLE_NONE) {
1024             uint32_t sampleRate = 0;
1025             status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
1026             if (status == NO_ERROR) {
1027                 mSampleRate = sampleRate;
1028             }
1029         }
1030     }
1031     return mSampleRate;
1032 }
1033 
getOriginalSampleRate() const1034 uint32_t AudioTrack::getOriginalSampleRate() const
1035 {
1036     return mOriginalSampleRate;
1037 }
1038 
setPlaybackRate(const AudioPlaybackRate & playbackRate)1039 status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
1040 {
1041     AutoMutex lock(mLock);
1042     if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
1043         return NO_ERROR;
1044     }
1045     if (isOffloadedOrDirect_l()) {
1046         return INVALID_OPERATION;
1047     }
1048     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1049         return INVALID_OPERATION;
1050     }
1051 
1052     ALOGV("%s(%d): mSampleRate:%u  mSpeed:%f  mPitch:%f",
1053             __func__, mPortId, mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
1054     // pitch is emulated by adjusting speed and sampleRate
1055     const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
1056     const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
1057     const float effectivePitch = adjustPitch(playbackRate.mPitch);
1058     AudioPlaybackRate playbackRateTemp = playbackRate;
1059     playbackRateTemp.mSpeed = effectiveSpeed;
1060     playbackRateTemp.mPitch = effectivePitch;
1061 
1062     ALOGV("%s(%d) (effective) mSampleRate:%u  mSpeed:%f  mPitch:%f",
1063             __func__, mPortId, effectiveRate, effectiveSpeed, effectivePitch);
1064 
1065     if (!isAudioPlaybackRateValid(playbackRateTemp)) {
1066         ALOGW("%s(%d) (%f, %f) failed (effective rate out of bounds)",
1067                 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1068         return BAD_VALUE;
1069     }
1070     // Check if the buffer size is compatible.
1071     if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
1072         ALOGW("%s(%d) (%f, %f) failed (buffer size)",
1073                 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1074         return BAD_VALUE;
1075     }
1076 
1077     // Check resampler ratios are within bounds
1078     if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
1079             (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
1080         ALOGW("%s(%d) (%f, %f) failed. Resample rate exceeds max accepted value",
1081                 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1082         return BAD_VALUE;
1083     }
1084 
1085     if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
1086         ALOGW("%s(%d) (%f, %f) failed. Resample rate below min accepted value",
1087                 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1088         return BAD_VALUE;
1089     }
1090     mPlaybackRate = playbackRate;
1091     //set effective rates
1092     mProxy->setPlaybackRate(playbackRateTemp);
1093     mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
1094 
1095     mediametrics::LogItem(mMetricsId)
1096         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYBACKPARAM)
1097         .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1098         .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1099         .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1100         .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1101                 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveRate)
1102         .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1103                 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)playbackRateTemp.mSpeed)
1104         .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1105                 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)playbackRateTemp.mPitch)
1106         .record();
1107 
1108     return NO_ERROR;
1109 }
1110 
getPlaybackRate() const1111 const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
1112 {
1113     AutoMutex lock(mLock);
1114     return mPlaybackRate;
1115 }
1116 
getBufferSizeInFrames()1117 ssize_t AudioTrack::getBufferSizeInFrames()
1118 {
1119     AutoMutex lock(mLock);
1120     if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1121         return NO_INIT;
1122     }
1123 
1124     return (ssize_t) mProxy->getBufferSizeInFrames();
1125 }
1126 
getBufferDurationInUs(int64_t * duration)1127 status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
1128 {
1129     if (duration == nullptr) {
1130         return BAD_VALUE;
1131     }
1132     AutoMutex lock(mLock);
1133     if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1134         return NO_INIT;
1135     }
1136     ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
1137     if (bufferSizeInFrames < 0) {
1138         return (status_t)bufferSizeInFrames;
1139     }
1140     *duration = (int64_t)((double)bufferSizeInFrames * 1000000
1141             / ((double)mSampleRate * mPlaybackRate.mSpeed));
1142     return NO_ERROR;
1143 }
1144 
setBufferSizeInFrames(size_t bufferSizeInFrames)1145 ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
1146 {
1147     AutoMutex lock(mLock);
1148     if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1149         return NO_INIT;
1150     }
1151     // Reject if timed track or compressed audio.
1152     if (!audio_is_linear_pcm(mFormat)) {
1153         return INVALID_OPERATION;
1154     }
1155 
1156     ssize_t originalBufferSize = mProxy->getBufferSizeInFrames();
1157     ssize_t finalBufferSize  = mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
1158     if (originalBufferSize != finalBufferSize) {
1159         android::mediametrics::LogItem(mMetricsId)
1160                 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETBUFFERSIZE)
1161                 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
1162                 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t)getUnderrunCount_l())
1163                 .record();
1164     }
1165     return finalBufferSize;
1166 }
1167 
setLoop(uint32_t loopStart,uint32_t loopEnd,int loopCount)1168 status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1169 {
1170     if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1171         return INVALID_OPERATION;
1172     }
1173 
1174     if (loopCount == 0) {
1175         ;
1176     } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1177             loopEnd - loopStart >= MIN_LOOP) {
1178         ;
1179     } else {
1180         return BAD_VALUE;
1181     }
1182 
1183     AutoMutex lock(mLock);
1184     // See setPosition() regarding setting parameters such as loop points or position while active
1185     if (mState == STATE_ACTIVE) {
1186         return INVALID_OPERATION;
1187     }
1188     setLoop_l(loopStart, loopEnd, loopCount);
1189     return NO_ERROR;
1190 }
1191 
setLoop_l(uint32_t loopStart,uint32_t loopEnd,int loopCount)1192 void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1193 {
1194     // We do not update the periodic notification point.
1195     // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1196     mLoopCount = loopCount;
1197     mLoopEnd = loopEnd;
1198     mLoopStart = loopStart;
1199     mLoopCountNotified = loopCount;
1200     mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
1201 
1202     // Waking the AudioTrackThread is not needed as this cannot be called when active.
1203 }
1204 
setMarkerPosition(uint32_t marker)1205 status_t AudioTrack::setMarkerPosition(uint32_t marker)
1206 {
1207     // The only purpose of setting marker position is to get a callback
1208     if (mCbf == NULL || isOffloadedOrDirect()) {
1209         return INVALID_OPERATION;
1210     }
1211 
1212     AutoMutex lock(mLock);
1213     mMarkerPosition = marker;
1214     mMarkerReached = false;
1215 
1216     sp<AudioTrackThread> t = mAudioTrackThread;
1217     if (t != 0) {
1218         t->wake();
1219     }
1220     return NO_ERROR;
1221 }
1222 
getMarkerPosition(uint32_t * marker) const1223 status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
1224 {
1225     if (isOffloadedOrDirect()) {
1226         return INVALID_OPERATION;
1227     }
1228     if (marker == NULL) {
1229         return BAD_VALUE;
1230     }
1231 
1232     AutoMutex lock(mLock);
1233     mMarkerPosition.getValue(marker);
1234 
1235     return NO_ERROR;
1236 }
1237 
setPositionUpdatePeriod(uint32_t updatePeriod)1238 status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1239 {
1240     // The only purpose of setting position update period is to get a callback
1241     if (mCbf == NULL || isOffloadedOrDirect()) {
1242         return INVALID_OPERATION;
1243     }
1244 
1245     AutoMutex lock(mLock);
1246     mNewPosition = updateAndGetPosition_l() + updatePeriod;
1247     mUpdatePeriod = updatePeriod;
1248 
1249     sp<AudioTrackThread> t = mAudioTrackThread;
1250     if (t != 0) {
1251         t->wake();
1252     }
1253     return NO_ERROR;
1254 }
1255 
getPositionUpdatePeriod(uint32_t * updatePeriod) const1256 status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
1257 {
1258     if (isOffloadedOrDirect()) {
1259         return INVALID_OPERATION;
1260     }
1261     if (updatePeriod == NULL) {
1262         return BAD_VALUE;
1263     }
1264 
1265     AutoMutex lock(mLock);
1266     *updatePeriod = mUpdatePeriod;
1267 
1268     return NO_ERROR;
1269 }
1270 
setPosition(uint32_t position)1271 status_t AudioTrack::setPosition(uint32_t position)
1272 {
1273     if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1274         return INVALID_OPERATION;
1275     }
1276     if (position > mFrameCount) {
1277         return BAD_VALUE;
1278     }
1279 
1280     AutoMutex lock(mLock);
1281     // Currently we require that the player is inactive before setting parameters such as position
1282     // or loop points.  Otherwise, there could be a race condition: the application could read the
1283     // current position, compute a new position or loop parameters, and then set that position or
1284     // loop parameters but it would do the "wrong" thing since the position has continued to advance
1285     // in the mean time.  If we ever provide a sequencer in server, we could allow a way for the app
1286     // to specify how it wants to handle such scenarios.
1287     if (mState == STATE_ACTIVE) {
1288         return INVALID_OPERATION;
1289     }
1290     // After setting the position, use full update period before notification.
1291     mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1292     mStaticProxy->setBufferPosition(position);
1293 
1294     // Waking the AudioTrackThread is not needed as this cannot be called when active.
1295     return NO_ERROR;
1296 }
1297 
getPosition(uint32_t * position)1298 status_t AudioTrack::getPosition(uint32_t *position)
1299 {
1300     if (position == NULL) {
1301         return BAD_VALUE;
1302     }
1303 
1304     AutoMutex lock(mLock);
1305     // FIXME: offloaded and direct tracks call into the HAL for render positions
1306     // for compressed/synced data; however, we use proxy position for pure linear pcm data
1307     // as we do not know the capability of the HAL for pcm position support and standby.
1308     // There may be some latency differences between the HAL position and the proxy position.
1309     if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
1310         uint32_t dspFrames = 0;
1311 
1312         if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
1313             ALOGV("%s(%d): called in paused state, return cached position %u",
1314                 __func__, mPortId, mPausedPosition);
1315             *position = mPausedPosition;
1316             return NO_ERROR;
1317         }
1318 
1319         if (mOutput != AUDIO_IO_HANDLE_NONE) {
1320             uint32_t halFrames; // actually unused
1321             (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1322             // FIXME: on getRenderPosition() error, we return OK with frame position 0.
1323         }
1324         // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1325         // due to hardware latency. We leave this behavior for now.
1326         *position = dspFrames;
1327     } else {
1328         if (mCblk->mFlags & CBLK_INVALID) {
1329             (void) restoreTrack_l("getPosition");
1330             // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1331             // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
1332         }
1333 
1334         // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
1335         *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
1336                 0 : updateAndGetPosition_l().value();
1337     }
1338     return NO_ERROR;
1339 }
1340 
getBufferPosition(uint32_t * position)1341 status_t AudioTrack::getBufferPosition(uint32_t *position)
1342 {
1343     if (mSharedBuffer == 0) {
1344         return INVALID_OPERATION;
1345     }
1346     if (position == NULL) {
1347         return BAD_VALUE;
1348     }
1349 
1350     AutoMutex lock(mLock);
1351     *position = mStaticProxy->getBufferPosition();
1352     return NO_ERROR;
1353 }
1354 
reload()1355 status_t AudioTrack::reload()
1356 {
1357     if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1358         return INVALID_OPERATION;
1359     }
1360 
1361     AutoMutex lock(mLock);
1362     // See setPosition() regarding setting parameters such as loop points or position while active
1363     if (mState == STATE_ACTIVE) {
1364         return INVALID_OPERATION;
1365     }
1366     mNewPosition = mUpdatePeriod;
1367     (void) updateAndGetPosition_l();
1368     mPosition = 0;
1369     mPreviousTimestampValid = false;
1370 #if 0
1371     // The documentation is not clear on the behavior of reload() and the restoration
1372     // of loop count. Historically we have not restored loop count, start, end,
1373     // but it makes sense if one desires to repeat playing a particular sound.
1374     if (mLoopCount != 0) {
1375         mLoopCountNotified = mLoopCount;
1376         mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1377     }
1378 #endif
1379     mStaticProxy->setBufferPosition(0);
1380     return NO_ERROR;
1381 }
1382 
getOutput() const1383 audio_io_handle_t AudioTrack::getOutput() const
1384 {
1385     AutoMutex lock(mLock);
1386     return mOutput;
1387 }
1388 
setOutputDevice(audio_port_handle_t deviceId)1389 status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1390     AutoMutex lock(mLock);
1391     if (mSelectedDeviceId != deviceId) {
1392         mSelectedDeviceId = deviceId;
1393         if (mStatus == NO_ERROR) {
1394             android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
1395             mProxy->interrupt();
1396         }
1397     }
1398     return NO_ERROR;
1399 }
1400 
getOutputDevice()1401 audio_port_handle_t AudioTrack::getOutputDevice() {
1402     AutoMutex lock(mLock);
1403     return mSelectedDeviceId;
1404 }
1405 
1406 // must be called with mLock held
updateRoutedDeviceId_l()1407 void AudioTrack::updateRoutedDeviceId_l()
1408 {
1409     // if the track is inactive, do not update actual device as the output stream maybe routed
1410     // to a device not relevant to this client because of other active use cases.
1411     if (mState != STATE_ACTIVE) {
1412         return;
1413     }
1414     if (mOutput != AUDIO_IO_HANDLE_NONE) {
1415         audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1416         if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1417             mRoutedDeviceId = deviceId;
1418         }
1419     }
1420 }
1421 
getRoutedDeviceId()1422 audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1423     AutoMutex lock(mLock);
1424     updateRoutedDeviceId_l();
1425     return mRoutedDeviceId;
1426 }
1427 
attachAuxEffect(int effectId)1428 status_t AudioTrack::attachAuxEffect(int effectId)
1429 {
1430     AutoMutex lock(mLock);
1431     status_t status = mAudioTrack->attachAuxEffect(effectId);
1432     if (status == NO_ERROR) {
1433         mAuxEffectId = effectId;
1434     }
1435     return status;
1436 }
1437 
streamType() const1438 audio_stream_type_t AudioTrack::streamType() const
1439 {
1440     if (mStreamType == AUDIO_STREAM_DEFAULT) {
1441         return AudioSystem::attributesToStreamType(mAttributes);
1442     }
1443     return mStreamType;
1444 }
1445 
latency()1446 uint32_t AudioTrack::latency()
1447 {
1448     AutoMutex lock(mLock);
1449     updateLatency_l();
1450     return mLatency;
1451 }
1452 
1453 // -------------------------------------------------------------------------
1454 
1455 // must be called with mLock held
updateLatency_l()1456 void AudioTrack::updateLatency_l()
1457 {
1458     status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1459     if (status != NO_ERROR) {
1460         ALOGW("%s(%d): getLatency(%d) failed status %d", __func__, mPortId, mOutput, status);
1461     } else {
1462         // FIXME don't believe this lie
1463         mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1464     }
1465 }
1466 
1467 // TODO Move this macro to a common header file for enum to string conversion in audio framework.
1468 #define MEDIA_CASE_ENUM(name) case name: return #name
convertTransferToText(transfer_type transferType)1469 const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1470     switch (transferType) {
1471         MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1472         MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1473         MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1474         MEDIA_CASE_ENUM(TRANSFER_SYNC);
1475         MEDIA_CASE_ENUM(TRANSFER_SHARED);
1476         MEDIA_CASE_ENUM(TRANSFER_SYNC_NOTIF_CALLBACK);
1477         default:
1478             return "UNRECOGNIZED";
1479     }
1480 }
1481 
createTrack_l()1482 status_t AudioTrack::createTrack_l()
1483 {
1484     status_t status;
1485     bool callbackAdded = false;
1486 
1487     const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1488     if (audioFlinger == 0) {
1489         ALOGE("%s(%d): Could not get audioflinger",
1490                 __func__, mPortId);
1491         status = NO_INIT;
1492         goto exit;
1493     }
1494 
1495     {
1496     // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1497     // After fast request is denied, we will request again if IAudioTrack is re-created.
1498     // Client can only express a preference for FAST.  Server will perform additional tests.
1499     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1500         // either of these use cases:
1501         // use case 1: shared buffer
1502         bool sharedBuffer = mSharedBuffer != 0;
1503         bool transferAllowed =
1504             // use case 2: callback transfer mode
1505             (mTransfer == TRANSFER_CALLBACK) ||
1506             // use case 3: obtain/release mode
1507             (mTransfer == TRANSFER_OBTAIN) ||
1508             // use case 4: synchronous write
1509             ((mTransfer == TRANSFER_SYNC || mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK)
1510                     && mThreadCanCallJava);
1511 
1512         bool fastAllowed = sharedBuffer || transferAllowed;
1513         if (!fastAllowed) {
1514             ALOGW("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by client,"
1515                   " not shared buffer and transfer = %s",
1516                   __func__, mPortId,
1517                   convertTransferToText(mTransfer));
1518             mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1519         }
1520     }
1521 
1522     IAudioFlinger::CreateTrackInput input;
1523     if (mStreamType != AUDIO_STREAM_DEFAULT) {
1524         input.attr = AudioSystem::streamTypeToAttributes(mStreamType);
1525     } else {
1526         input.attr = mAttributes;
1527     }
1528     input.config = AUDIO_CONFIG_INITIALIZER;
1529     input.config.sample_rate = mSampleRate;
1530     input.config.channel_mask = mChannelMask;
1531     input.config.format = mFormat;
1532     input.config.offload_info = mOffloadInfoCopy;
1533     input.clientInfo.clientUid = mClientUid;
1534     input.clientInfo.clientPid = mClientPid;
1535     input.clientInfo.clientTid = -1;
1536     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1537         // It is currently meaningless to request SCHED_FIFO for a Java thread.  Even if the
1538         // application-level code follows all non-blocking design rules, the language runtime
1539         // doesn't also follow those rules, so the thread will not benefit overall.
1540         if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
1541             input.clientInfo.clientTid = mAudioTrackThread->getTid();
1542         }
1543     }
1544     input.sharedBuffer = mSharedBuffer;
1545     input.notificationsPerBuffer = mNotificationsPerBufferReq;
1546     input.speed = 1.0;
1547     if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1548             (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1549         input.speed  = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1550                         max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1551     }
1552     input.flags = mFlags;
1553     input.frameCount = mReqFrameCount;
1554     input.notificationFrameCount = mNotificationFramesReq;
1555     input.selectedDeviceId = mSelectedDeviceId;
1556     input.sessionId = mSessionId;
1557     input.audioTrackCallback = mAudioTrackCallback;
1558 
1559     IAudioFlinger::CreateTrackOutput output;
1560 
1561     sp<IAudioTrack> track = audioFlinger->createTrack(input,
1562                                                       output,
1563                                                       &status);
1564 
1565     if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1566         ALOGE("%s(%d): AudioFlinger could not create track, status: %d output %d",
1567                 __func__, mPortId, status, output.outputId);
1568         if (status == NO_ERROR) {
1569             status = NO_INIT;
1570         }
1571         goto exit;
1572     }
1573     ALOG_ASSERT(track != 0);
1574 
1575     mFrameCount = output.frameCount;
1576     mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1577     mRoutedDeviceId = output.selectedDeviceId;
1578     mSessionId = output.sessionId;
1579 
1580     mSampleRate = output.sampleRate;
1581     if (mOriginalSampleRate == 0) {
1582         mOriginalSampleRate = mSampleRate;
1583     }
1584 
1585     mAfFrameCount = output.afFrameCount;
1586     mAfSampleRate = output.afSampleRate;
1587     mAfLatency = output.afLatencyMs;
1588 
1589     mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1590 
1591     // AudioFlinger now owns the reference to the I/O handle,
1592     // so we are no longer responsible for releasing it.
1593 
1594     // FIXME compare to AudioRecord
1595     sp<IMemory> iMem = track->getCblk();
1596     if (iMem == 0) {
1597         ALOGE("%s(%d): Could not get control block", __func__, mPortId);
1598         status = NO_INIT;
1599         goto exit;
1600     }
1601     // TODO: Using unsecurePointer() has some associated security pitfalls
1602     //       (see declaration for details).
1603     //       Either document why it is safe in this case or address the
1604     //       issue (e.g. by copying).
1605     void *iMemPointer = iMem->unsecurePointer();
1606     if (iMemPointer == NULL) {
1607         ALOGE("%s(%d): Could not get control block pointer", __func__, mPortId);
1608         status = NO_INIT;
1609         goto exit;
1610     }
1611     // invariant that mAudioTrack != 0 is true only after set() returns successfully
1612     if (mAudioTrack != 0) {
1613         IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
1614         mDeathNotifier.clear();
1615     }
1616     mAudioTrack = track;
1617     mCblkMemory = iMem;
1618     IPCThreadState::self()->flushCommands();
1619 
1620     audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
1621     mCblk = cblk;
1622 
1623     mAwaitBoost = false;
1624     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1625         if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
1626             ALOGI("%s(%d): AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
1627                   __func__, mPortId, mReqFrameCount, mFrameCount);
1628             if (!mThreadCanCallJava) {
1629                 mAwaitBoost = true;
1630             }
1631         } else {
1632             ALOGD("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu",
1633                   __func__, mPortId, mReqFrameCount, mFrameCount);
1634         }
1635     }
1636     mFlags = output.flags;
1637 
1638     //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
1639     if (mDeviceCallback != 0) {
1640         if (mOutput != AUDIO_IO_HANDLE_NONE) {
1641             AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
1642         }
1643         AudioSystem::addAudioDeviceCallback(this, output.outputId, output.portId);
1644         callbackAdded = true;
1645     }
1646 
1647     mPortId = output.portId;
1648     // We retain a copy of the I/O handle, but don't own the reference
1649     mOutput = output.outputId;
1650     mRefreshRemaining = true;
1651 
1652     // Starting address of buffers in shared memory.  If there is a shared buffer, buffers
1653     // is the value of pointer() for the shared buffer, otherwise buffers points
1654     // immediately after the control block.  This address is for the mapping within client
1655     // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
1656     void* buffers;
1657     if (mSharedBuffer == 0) {
1658         buffers = cblk + 1;
1659     } else {
1660         // TODO: Using unsecurePointer() has some associated security pitfalls
1661         //       (see declaration for details).
1662         //       Either document why it is safe in this case or address the
1663         //       issue (e.g. by copying).
1664         buffers = mSharedBuffer->unsecurePointer();
1665         if (buffers == NULL) {
1666             ALOGE("%s(%d): Could not get buffer pointer", __func__, mPortId);
1667             status = NO_INIT;
1668             goto exit;
1669         }
1670     }
1671 
1672     mAudioTrack->attachAuxEffect(mAuxEffectId);
1673 
1674     // If IAudioTrack is re-created, don't let the requested frameCount
1675     // decrease.  This can confuse clients that cache frameCount().
1676     if (mFrameCount > mReqFrameCount) {
1677         mReqFrameCount = mFrameCount;
1678     }
1679 
1680     // reset server position to 0 as we have new cblk.
1681     mServer = 0;
1682 
1683     // update proxy
1684     if (mSharedBuffer == 0) {
1685         mStaticProxy.clear();
1686         mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
1687     } else {
1688         mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
1689         mProxy = mStaticProxy;
1690     }
1691 
1692     mProxy->setVolumeLR(gain_minifloat_pack(
1693             gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1694             gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1695 
1696     mProxy->setSendLevel(mSendLevel);
1697     const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1698     const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1699     const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
1700     mProxy->setSampleRate(effectiveSampleRate);
1701 
1702     AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1703     playbackRateTemp.mSpeed = effectiveSpeed;
1704     playbackRateTemp.mPitch = effectivePitch;
1705     mProxy->setPlaybackRate(playbackRateTemp);
1706     mProxy->setMinimum(mNotificationFramesAct);
1707 
1708     mDeathNotifier = new DeathNotifier(this);
1709     IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
1710 
1711     // This is the first log sent from the AudioTrack client.
1712     // The creation of the audio track by AudioFlinger (in the code above)
1713     // is the first log of the AudioTrack and must be present before
1714     // any AudioTrack client logs will be accepted.
1715 
1716     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(mPortId);
1717     mediametrics::LogItem(mMetricsId)
1718         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
1719         // the following are immutable
1720         .set(AMEDIAMETRICS_PROP_FLAGS, toString(mFlags).c_str())
1721         .set(AMEDIAMETRICS_PROP_ORIGINALFLAGS, toString(mOrigFlags).c_str())
1722         .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)mSessionId)
1723         .set(AMEDIAMETRICS_PROP_TRACKID, mPortId) // dup from key
1724         .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(mAttributes.content_type).c_str())
1725         .set(AMEDIAMETRICS_PROP_USAGE, toString(mAttributes.usage).c_str())
1726         .set(AMEDIAMETRICS_PROP_THREADID, (int32_t)output.outputId)
1727         .set(AMEDIAMETRICS_PROP_SELECTEDDEVICEID, (int32_t)mSelectedDeviceId)
1728         .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)mRoutedDeviceId)
1729         .set(AMEDIAMETRICS_PROP_ENCODING, toString(mFormat).c_str())
1730         .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
1731         .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
1732         // the following are NOT immutable
1733         .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)mVolume[AUDIO_INTERLEAVE_LEFT])
1734         .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)mVolume[AUDIO_INTERLEAVE_RIGHT])
1735         .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
1736         .set(AMEDIAMETRICS_PROP_AUXEFFECTID, (int32_t)mAuxEffectId)
1737         .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1738         .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1739         .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1740         .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1741                 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveSampleRate)
1742         .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1743                 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)effectiveSpeed)
1744         .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1745                 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)effectivePitch)
1746         .record();
1747 
1748     // mSendLevel
1749     // mReqFrameCount?
1750     // mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq
1751     // mLatency, mAfLatency, mAfFrameCount, mAfSampleRate
1752 
1753     }
1754 
1755 exit:
1756     if (status != NO_ERROR && callbackAdded) {
1757         // note: mOutput is always valid is callbackAdded is true
1758         AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
1759     }
1760 
1761     mStatus = status;
1762 
1763     // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
1764     return status;
1765 }
1766 
obtainBuffer(Buffer * audioBuffer,int32_t waitCount,size_t * nonContig)1767 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
1768 {
1769     if (audioBuffer == NULL) {
1770         if (nonContig != NULL) {
1771             *nonContig = 0;
1772         }
1773         return BAD_VALUE;
1774     }
1775     if (mTransfer != TRANSFER_OBTAIN) {
1776         audioBuffer->frameCount = 0;
1777         audioBuffer->size = 0;
1778         audioBuffer->raw = NULL;
1779         if (nonContig != NULL) {
1780             *nonContig = 0;
1781         }
1782         return INVALID_OPERATION;
1783     }
1784 
1785     const struct timespec *requested;
1786     struct timespec timeout;
1787     if (waitCount == -1) {
1788         requested = &ClientProxy::kForever;
1789     } else if (waitCount == 0) {
1790         requested = &ClientProxy::kNonBlocking;
1791     } else if (waitCount > 0) {
1792         time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
1793         timeout.tv_sec = ms / 1000;
1794         timeout.tv_nsec = (ms % 1000) * 1000000;
1795         requested = &timeout;
1796     } else {
1797         ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
1798         requested = NULL;
1799     }
1800     return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
1801 }
1802 
obtainBuffer(Buffer * audioBuffer,const struct timespec * requested,struct timespec * elapsed,size_t * nonContig)1803 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1804         struct timespec *elapsed, size_t *nonContig)
1805 {
1806     // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1807     uint32_t oldSequence = 0;
1808 
1809     Proxy::Buffer buffer;
1810     status_t status = NO_ERROR;
1811 
1812     static const int32_t kMaxTries = 5;
1813     int32_t tryCounter = kMaxTries;
1814 
1815     do {
1816         // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1817         // keep them from going away if another thread re-creates the track during obtainBuffer()
1818         sp<AudioTrackClientProxy> proxy;
1819         sp<IMemory> iMem;
1820 
1821         {   // start of lock scope
1822             AutoMutex lock(mLock);
1823 
1824             uint32_t newSequence = mSequence;
1825             // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1826             if (status == DEAD_OBJECT) {
1827                 // re-create track, unless someone else has already done so
1828                 if (newSequence == oldSequence) {
1829                     status = restoreTrack_l("obtainBuffer");
1830                     if (status != NO_ERROR) {
1831                         buffer.mFrameCount = 0;
1832                         buffer.mRaw = NULL;
1833                         buffer.mNonContig = 0;
1834                         break;
1835                     }
1836                 }
1837             }
1838             oldSequence = newSequence;
1839 
1840             if (status == NOT_ENOUGH_DATA) {
1841                 restartIfDisabled();
1842             }
1843 
1844             // Keep the extra references
1845             proxy = mProxy;
1846             iMem = mCblkMemory;
1847 
1848             if (mState == STATE_STOPPING) {
1849                 status = -EINTR;
1850                 buffer.mFrameCount = 0;
1851                 buffer.mRaw = NULL;
1852                 buffer.mNonContig = 0;
1853                 break;
1854             }
1855 
1856             // Non-blocking if track is stopped or paused
1857             if (mState != STATE_ACTIVE) {
1858                 requested = &ClientProxy::kNonBlocking;
1859             }
1860 
1861         }   // end of lock scope
1862 
1863         buffer.mFrameCount = audioBuffer->frameCount;
1864         // FIXME starts the requested timeout and elapsed over from scratch
1865         status = proxy->obtainBuffer(&buffer, requested, elapsed);
1866     } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
1867 
1868     audioBuffer->frameCount = buffer.mFrameCount;
1869     audioBuffer->size = buffer.mFrameCount * mFrameSize;
1870     audioBuffer->raw = buffer.mRaw;
1871     audioBuffer->sequence = oldSequence;
1872     if (nonContig != NULL) {
1873         *nonContig = buffer.mNonContig;
1874     }
1875     return status;
1876 }
1877 
releaseBuffer(const Buffer * audioBuffer)1878 void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
1879 {
1880     // FIXME add error checking on mode, by adding an internal version
1881     if (mTransfer == TRANSFER_SHARED) {
1882         return;
1883     }
1884 
1885     size_t stepCount = audioBuffer->size / mFrameSize;
1886     if (stepCount == 0) {
1887         return;
1888     }
1889 
1890     Proxy::Buffer buffer;
1891     buffer.mFrameCount = stepCount;
1892     buffer.mRaw = audioBuffer->raw;
1893 
1894     AutoMutex lock(mLock);
1895     if (audioBuffer->sequence != mSequence) {
1896         // This Buffer came from a different IAudioTrack instance, so ignore the releaseBuffer
1897         ALOGD("%s is no-op due to IAudioTrack sequence mismatch %u != %u",
1898                 __func__, audioBuffer->sequence, mSequence);
1899         return;
1900     }
1901     mReleased += stepCount;
1902     mInUnderrun = false;
1903     mProxy->releaseBuffer(&buffer);
1904 
1905     // restart track if it was disabled by audioflinger due to previous underrun
1906     restartIfDisabled();
1907 }
1908 
restartIfDisabled()1909 void AudioTrack::restartIfDisabled()
1910 {
1911     int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1912     if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
1913         ALOGW("%s(%d): releaseBuffer() track %p disabled due to previous underrun, restarting",
1914                 __func__, mPortId, this);
1915         // FIXME ignoring status
1916         mAudioTrack->start();
1917     }
1918 }
1919 
1920 // -------------------------------------------------------------------------
1921 
write(const void * buffer,size_t userSize,bool blocking)1922 ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
1923 {
1924     if (mTransfer != TRANSFER_SYNC && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
1925         return INVALID_OPERATION;
1926     }
1927 
1928     if (isDirect()) {
1929         AutoMutex lock(mLock);
1930         int32_t flags = android_atomic_and(
1931                             ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1932                             &mCblk->mFlags);
1933         if (flags & CBLK_INVALID) {
1934             return DEAD_OBJECT;
1935         }
1936     }
1937 
1938     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
1939         // Sanity-check: user is most-likely passing an error code, and it would
1940         // make the return value ambiguous (actualSize vs error).
1941         ALOGE("%s(%d): AudioTrack::write(buffer=%p, size=%zu (%zd)",
1942                 __func__, mPortId, buffer, userSize, userSize);
1943         return BAD_VALUE;
1944     }
1945 
1946     size_t written = 0;
1947     Buffer audioBuffer;
1948 
1949     while (userSize >= mFrameSize) {
1950         audioBuffer.frameCount = userSize / mFrameSize;
1951 
1952         status_t err = obtainBuffer(&audioBuffer,
1953                 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
1954         if (err < 0) {
1955             if (written > 0) {
1956                 break;
1957             }
1958             if (err == TIMED_OUT || err == -EINTR) {
1959                 err = WOULD_BLOCK;
1960             }
1961             return ssize_t(err);
1962         }
1963 
1964         size_t toWrite = audioBuffer.size;
1965         memcpy(audioBuffer.i8, buffer, toWrite);
1966         buffer = ((const char *) buffer) + toWrite;
1967         userSize -= toWrite;
1968         written += toWrite;
1969 
1970         releaseBuffer(&audioBuffer);
1971     }
1972 
1973     if (written > 0) {
1974         mFramesWritten += written / mFrameSize;
1975 
1976         if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
1977             const sp<AudioTrackThread> t = mAudioTrackThread;
1978             if (t != 0) {
1979                 // causes wake up of the playback thread, that will callback the client for
1980                 // more data (with EVENT_CAN_WRITE_MORE_DATA) in processAudioBuffer()
1981                 t->wake();
1982             }
1983         }
1984     }
1985 
1986     return written;
1987 }
1988 
1989 // -------------------------------------------------------------------------
1990 
processAudioBuffer()1991 nsecs_t AudioTrack::processAudioBuffer()
1992 {
1993     // Currently the AudioTrack thread is not created if there are no callbacks.
1994     // Would it ever make sense to run the thread, even without callbacks?
1995     // If so, then replace this by checks at each use for mCbf != NULL.
1996     LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1997 
1998     mLock.lock();
1999     if (mAwaitBoost) {
2000         mAwaitBoost = false;
2001         mLock.unlock();
2002         static const int32_t kMaxTries = 5;
2003         int32_t tryCounter = kMaxTries;
2004         uint32_t pollUs = 10000;
2005         do {
2006             int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
2007             if (policy == SCHED_FIFO || policy == SCHED_RR) {
2008                 break;
2009             }
2010             usleep(pollUs);
2011             pollUs <<= 1;
2012         } while (tryCounter-- > 0);
2013         if (tryCounter < 0) {
2014             ALOGE("%s(%d): did not receive expected priority boost on time",
2015                     __func__, mPortId);
2016         }
2017         // Run again immediately
2018         return 0;
2019     }
2020 
2021     // Can only reference mCblk while locked
2022     int32_t flags = android_atomic_and(
2023         ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
2024 
2025     // Check for track invalidation
2026     if (flags & CBLK_INVALID) {
2027         // for offloaded tracks restoreTrack_l() will just update the sequence and clear
2028         // AudioSystem cache. We should not exit here but after calling the callback so
2029         // that the upper layers can recreate the track
2030         if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
2031             status_t status __unused = restoreTrack_l("processAudioBuffer");
2032             // FIXME unused status
2033             // after restoration, continue below to make sure that the loop and buffer events
2034             // are notified because they have been cleared from mCblk->mFlags above.
2035         }
2036     }
2037 
2038     bool waitStreamEnd = mState == STATE_STOPPING;
2039     bool active = mState == STATE_ACTIVE;
2040 
2041     // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
2042     bool newUnderrun = false;
2043     if (flags & CBLK_UNDERRUN) {
2044 #if 0
2045         // Currently in shared buffer mode, when the server reaches the end of buffer,
2046         // the track stays active in continuous underrun state.  It's up to the application
2047         // to pause or stop the track, or set the position to a new offset within buffer.
2048         // This was some experimental code to auto-pause on underrun.   Keeping it here
2049         // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
2050         if (mTransfer == TRANSFER_SHARED) {
2051             mState = STATE_PAUSED;
2052             active = false;
2053         }
2054 #endif
2055         if (!mInUnderrun) {
2056             mInUnderrun = true;
2057             newUnderrun = true;
2058         }
2059     }
2060 
2061     // Get current position of server
2062     Modulo<uint32_t> position(updateAndGetPosition_l());
2063 
2064     // Manage marker callback
2065     bool markerReached = false;
2066     Modulo<uint32_t> markerPosition(mMarkerPosition);
2067     // uses 32 bit wraparound for comparison with position.
2068     if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
2069         mMarkerReached = markerReached = true;
2070     }
2071 
2072     // Determine number of new position callback(s) that will be needed, while locked
2073     size_t newPosCount = 0;
2074     Modulo<uint32_t> newPosition(mNewPosition);
2075     uint32_t updatePeriod = mUpdatePeriod;
2076     // FIXME fails for wraparound, need 64 bits
2077     if (updatePeriod > 0 && position >= newPosition) {
2078         newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
2079         mNewPosition += updatePeriod * newPosCount;
2080     }
2081 
2082     // Cache other fields that will be needed soon
2083     uint32_t sampleRate = mSampleRate;
2084     float speed = mPlaybackRate.mSpeed;
2085     const uint32_t notificationFrames = mNotificationFramesAct;
2086     if (mRefreshRemaining) {
2087         mRefreshRemaining = false;
2088         mRemainingFrames = notificationFrames;
2089         mRetryOnPartialBuffer = false;
2090     }
2091     size_t misalignment = mProxy->getMisalignment();
2092     uint32_t sequence = mSequence;
2093     sp<AudioTrackClientProxy> proxy = mProxy;
2094 
2095     // Determine the number of new loop callback(s) that will be needed, while locked.
2096     int loopCountNotifications = 0;
2097     uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
2098 
2099     if (mLoopCount > 0) {
2100         int loopCount;
2101         size_t bufferPosition;
2102         mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2103         loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
2104         loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
2105         mLoopCountNotified = loopCount; // discard any excess notifications
2106     } else if (mLoopCount < 0) {
2107         // FIXME: We're not accurate with notification count and position with infinite looping
2108         // since loopCount from server side will always return -1 (we could decrement it).
2109         size_t bufferPosition = mStaticProxy->getBufferPosition();
2110         loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
2111         loopPeriod = mLoopEnd - bufferPosition;
2112     } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
2113         size_t bufferPosition = mStaticProxy->getBufferPosition();
2114         loopPeriod = mFrameCount - bufferPosition;
2115     }
2116 
2117     // These fields don't need to be cached, because they are assigned only by set():
2118     //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
2119     // mFlags is also assigned by createTrack_l(), but not the bit we care about.
2120 
2121     mLock.unlock();
2122 
2123     // get anchor time to account for callbacks.
2124     const nsecs_t timeBeforeCallbacks = systemTime();
2125 
2126     if (waitStreamEnd) {
2127         // FIXME:  Instead of blocking in proxy->waitStreamEndDone(), Callback thread
2128         // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
2129         // (and make sure we don't callback for more data while we're stopping).
2130         // This helps with position, marker notifications, and track invalidation.
2131         struct timespec timeout;
2132         timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
2133         timeout.tv_nsec = 0;
2134 
2135         status_t status = proxy->waitStreamEndDone(&timeout);
2136         switch (status) {
2137         case NO_ERROR:
2138         case DEAD_OBJECT:
2139         case TIMED_OUT:
2140             if (status != DEAD_OBJECT) {
2141                 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
2142                 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
2143                 mCbf(EVENT_STREAM_END, mUserData, NULL);
2144             }
2145             {
2146                 AutoMutex lock(mLock);
2147                 // The previously assigned value of waitStreamEnd is no longer valid,
2148                 // since the mutex has been unlocked and either the callback handler
2149                 // or another thread could have re-started the AudioTrack during that time.
2150                 waitStreamEnd = mState == STATE_STOPPING;
2151                 if (waitStreamEnd) {
2152                     mState = STATE_STOPPED;
2153                     mReleased = 0;
2154                 }
2155             }
2156             if (waitStreamEnd && status != DEAD_OBJECT) {
2157                return NS_INACTIVE;
2158             }
2159             break;
2160         }
2161         return 0;
2162     }
2163 
2164     // perform callbacks while unlocked
2165     if (newUnderrun) {
2166         mCbf(EVENT_UNDERRUN, mUserData, NULL);
2167     }
2168     while (loopCountNotifications > 0) {
2169         mCbf(EVENT_LOOP_END, mUserData, NULL);
2170         --loopCountNotifications;
2171     }
2172     if (flags & CBLK_BUFFER_END) {
2173         mCbf(EVENT_BUFFER_END, mUserData, NULL);
2174     }
2175     if (markerReached) {
2176         mCbf(EVENT_MARKER, mUserData, &markerPosition);
2177     }
2178     while (newPosCount > 0) {
2179         size_t temp = newPosition.value(); // FIXME size_t != uint32_t
2180         mCbf(EVENT_NEW_POS, mUserData, &temp);
2181         newPosition += updatePeriod;
2182         newPosCount--;
2183     }
2184 
2185     if (mObservedSequence != sequence) {
2186         mObservedSequence = sequence;
2187         mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
2188         // for offloaded tracks, just wait for the upper layers to recreate the track
2189         if (isOffloadedOrDirect()) {
2190             return NS_INACTIVE;
2191         }
2192     }
2193 
2194     // if inactive, then don't run me again until re-started
2195     if (!active) {
2196         return NS_INACTIVE;
2197     }
2198 
2199     // Compute the estimated time until the next timed event (position, markers, loops)
2200     // FIXME only for non-compressed audio
2201     uint32_t minFrames = ~0;
2202     if (!markerReached && position < markerPosition) {
2203         minFrames = (markerPosition - position).value();
2204     }
2205     if (loopPeriod > 0 && loopPeriod < minFrames) {
2206         // loopPeriod is already adjusted for actual position.
2207         minFrames = loopPeriod;
2208     }
2209     if (updatePeriod > 0) {
2210         minFrames = min(minFrames, (newPosition - position).value());
2211     }
2212 
2213     // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
2214     static const uint32_t kPoll = 0;
2215     if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2216         minFrames = kPoll * notificationFrames;
2217     }
2218 
2219     // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2220     static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2221     const nsecs_t timeAfterCallbacks = systemTime();
2222 
2223     // Convert frame units to time units
2224     nsecs_t ns = NS_WHENEVER;
2225     if (minFrames != (uint32_t) ~0) {
2226         // AudioFlinger consumption of client data may be irregular when coming out of device
2227         // standby since the kernel buffers require filling. This is throttled to no more than 2x
2228         // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2229         // half (but no more than half a second) to improve callback accuracy during these temporary
2230         // data surges.
2231         const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2232         constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2233         ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
2234         ns -= (timeAfterCallbacks - timeBeforeCallbacks);  // account for callback time
2235         // TODO: Should we warn if the callback time is too long?
2236         if (ns < 0) ns = 0;
2237     }
2238 
2239     // If not supplying data by EVENT_MORE_DATA or EVENT_CAN_WRITE_MORE_DATA, then we're done
2240     if (mTransfer != TRANSFER_CALLBACK && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
2241         return ns;
2242     }
2243 
2244     // EVENT_MORE_DATA callback handling.
2245     // Timing for linear pcm audio data formats can be derived directly from the
2246     // buffer fill level.
2247     // Timing for compressed data is not directly available from the buffer fill level,
2248     // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2249     // to return a certain fill level.
2250 
2251     struct timespec timeout;
2252     const struct timespec *requested = &ClientProxy::kForever;
2253     if (ns != NS_WHENEVER) {
2254         timeout.tv_sec = ns / 1000000000LL;
2255         timeout.tv_nsec = ns % 1000000000LL;
2256         ALOGV("%s(%d): timeout %ld.%03d",
2257                 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
2258         requested = &timeout;
2259     }
2260 
2261     size_t writtenFrames = 0;
2262     while (mRemainingFrames > 0) {
2263 
2264         Buffer audioBuffer;
2265         audioBuffer.frameCount = mRemainingFrames;
2266         size_t nonContig;
2267         status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2268         LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
2269                 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
2270                  __func__, mPortId, err, audioBuffer.frameCount);
2271         requested = &ClientProxy::kNonBlocking;
2272         size_t avail = audioBuffer.frameCount + nonContig;
2273         ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
2274                 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
2275         if (err != NO_ERROR) {
2276             if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2277                     (isOffloaded() && (err == DEAD_OBJECT))) {
2278                 // FIXME bug 25195759
2279                 return 1000000;
2280             }
2281             ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
2282                     __func__, mPortId, err);
2283             return NS_NEVER;
2284         }
2285 
2286         if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
2287             mRetryOnPartialBuffer = false;
2288             if (avail < mRemainingFrames) {
2289                 if (ns > 0) { // account for obtain time
2290                     const nsecs_t timeNow = systemTime();
2291                     ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2292                 }
2293 
2294                 // delayNs is first computed by the additional frames required in the buffer.
2295                 nsecs_t delayNs = framesToNanoseconds(
2296                         mRemainingFrames - avail, sampleRate, speed);
2297 
2298                 // afNs is the AudioFlinger mixer period in ns.
2299                 const nsecs_t afNs = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2300 
2301                 // If the AudioTrack is double buffered based on the AudioFlinger mixer period,
2302                 // we may have a race if we wait based on the number of frames desired.
2303                 // This is a possible issue with resampling and AAudio.
2304                 //
2305                 // The granularity of audioflinger processing is one mixer period; if
2306                 // our wait time is less than one mixer period, wait at most half the period.
2307                 if (delayNs < afNs) {
2308                     delayNs = std::min(delayNs, afNs / 2);
2309                 }
2310 
2311                 // adjust our ns wait by delayNs.
2312                 if (ns < 0 /* NS_WHENEVER */ || delayNs < ns) {
2313                     ns = delayNs;
2314                 }
2315                 return ns;
2316             }
2317         }
2318 
2319         size_t reqSize = audioBuffer.size;
2320         if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2321             // when notifying client it can write more data, pass the total size that can be
2322             // written in the next write() call, since it's not passed through the callback
2323             audioBuffer.size += nonContig;
2324         }
2325         mCbf(mTransfer == TRANSFER_CALLBACK ? EVENT_MORE_DATA : EVENT_CAN_WRITE_MORE_DATA,
2326                 mUserData, &audioBuffer);
2327         size_t writtenSize = audioBuffer.size;
2328 
2329         // Sanity check on returned size
2330         if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
2331             ALOGE("%s(%d): EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
2332                     __func__, mPortId, reqSize, ssize_t(writtenSize));
2333             return NS_NEVER;
2334         }
2335 
2336         if (writtenSize == 0) {
2337             if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2338                 // The callback EVENT_CAN_WRITE_MORE_DATA was processed in the JNI of
2339                 // android.media.AudioTrack. The JNI is not using the callback to provide data,
2340                 // it only signals to the Java client that it can provide more data, which
2341                 // this track is read to accept now.
2342                 // The playback thread will be awaken at the next ::write()
2343                 return NS_WHENEVER;
2344             }
2345             // The callback is done filling buffers
2346             // Keep this thread going to handle timed events and
2347             // still try to get more data in intervals of WAIT_PERIOD_MS
2348             // but don't just loop and block the CPU, so wait
2349 
2350             // mCbf(EVENT_MORE_DATA, ...) might either
2351             // (1) Block until it can fill the buffer, returning 0 size on EOS.
2352             // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2353             // (3) Return 0 size when no data is available, does not wait for more data.
2354             //
2355             // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2356             // We try to compute the wait time to avoid a tight sleep-wait cycle,
2357             // especially for case (3).
2358             //
2359             // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2360             // and this loop; whereas for case (3) we could simply check once with the full
2361             // buffer size and skip the loop entirely.
2362 
2363             nsecs_t myns;
2364             if (audio_has_proportional_frames(mFormat)) {
2365                 // time to wait based on buffer occupancy
2366                 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2367                         framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2368                 // audio flinger thread buffer size (TODO: adjust for fast tracks)
2369                 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
2370                 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2371                 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2372                 myns = datans + (afns / 2);
2373             } else {
2374                 // FIXME: This could ping quite a bit if the buffer isn't full.
2375                 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2376                 myns = kWaitPeriodNs;
2377             }
2378             if (ns > 0) { // account for obtain and callback time
2379                 const nsecs_t timeNow = systemTime();
2380                 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2381             }
2382             if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2383                 ns = myns;
2384             }
2385             return ns;
2386         }
2387 
2388         size_t releasedFrames = writtenSize / mFrameSize;
2389         audioBuffer.frameCount = releasedFrames;
2390         mRemainingFrames -= releasedFrames;
2391         if (misalignment >= releasedFrames) {
2392             misalignment -= releasedFrames;
2393         } else {
2394             misalignment = 0;
2395         }
2396 
2397         releaseBuffer(&audioBuffer);
2398         writtenFrames += releasedFrames;
2399 
2400         // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2401         // if callback doesn't like to accept the full chunk
2402         if (writtenSize < reqSize) {
2403             continue;
2404         }
2405 
2406         // There could be enough non-contiguous frames available to satisfy the remaining request
2407         if (mRemainingFrames <= nonContig) {
2408             continue;
2409         }
2410 
2411 #if 0
2412         // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2413         // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
2414         // that total to a sum == notificationFrames.
2415         if (0 < misalignment && misalignment <= mRemainingFrames) {
2416             mRemainingFrames = misalignment;
2417             return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
2418         }
2419 #endif
2420 
2421     }
2422     if (writtenFrames > 0) {
2423         AutoMutex lock(mLock);
2424         mFramesWritten += writtenFrames;
2425     }
2426     mRemainingFrames = notificationFrames;
2427     mRetryOnPartialBuffer = true;
2428 
2429     // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2430     return 0;
2431 }
2432 
restoreTrack_l(const char * from)2433 status_t AudioTrack::restoreTrack_l(const char *from)
2434 {
2435     status_t result = NO_ERROR;  // logged: make sure to set this before returning.
2436     const int64_t beginNs = systemTime();
2437     mediametrics::Defer defer([&] {
2438         mediametrics::LogItem(mMetricsId)
2439             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_RESTORE)
2440             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
2441             .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
2442             .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
2443             .set(AMEDIAMETRICS_PROP_WHERE, from)
2444             .record(); });
2445 
2446     ALOGW("%s(%d): dead IAudioTrack, %s, creating a new one from %s()",
2447             __func__, mPortId, isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
2448     ++mSequence;
2449 
2450     // refresh the audio configuration cache in this process to make sure we get new
2451     // output parameters and new IAudioFlinger in createTrack_l()
2452     AudioSystem::clearAudioConfigCache();
2453 
2454     if (isOffloadedOrDirect_l() || mDoNotReconnect) {
2455         // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2456         // reconsider enabling for linear PCM encodings when position can be preserved.
2457         result = DEAD_OBJECT;
2458         return result;
2459     }
2460 
2461     // Save so we can return count since creation.
2462     mUnderrunCountOffset = getUnderrunCount_l();
2463 
2464     // save the old static buffer position
2465     uint32_t staticPosition = 0;
2466     size_t bufferPosition = 0;
2467     int loopCount = 0;
2468     if (mStaticProxy != 0) {
2469         mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2470         staticPosition = mStaticProxy->getPosition().unsignedValue();
2471     }
2472 
2473     // See b/74409267. Connecting to a BT A2DP device supporting multiple codecs
2474     // causes a lot of churn on the service side, and it can reject starting
2475     // playback of a previously created track. May also apply to other cases.
2476     const int INITIAL_RETRIES = 3;
2477     int retries = INITIAL_RETRIES;
2478 retry:
2479     if (retries < INITIAL_RETRIES) {
2480         // See the comment for clearAudioConfigCache at the start of the function.
2481         AudioSystem::clearAudioConfigCache();
2482     }
2483     mFlags = mOrigFlags;
2484 
2485     // If a new IAudioTrack is successfully created, createTrack_l() will modify the
2486     // following member variables: mAudioTrack, mCblkMemory and mCblk.
2487     // It will also delete the strong references on previous IAudioTrack and IMemory.
2488     // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
2489     result = createTrack_l();
2490 
2491     if (result == NO_ERROR) {
2492         // take the frames that will be lost by track recreation into account in saved position
2493         // For streaming tracks, this is the amount we obtained from the user/client
2494         // (not the number actually consumed at the server - those are already lost).
2495         if (mStaticProxy == 0) {
2496             mPosition = mReleased;
2497         }
2498         // Continue playback from last known position and restore loop.
2499         if (mStaticProxy != 0) {
2500             if (loopCount != 0) {
2501                 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2502                         mLoopStart, mLoopEnd, loopCount);
2503             } else {
2504                 mStaticProxy->setBufferPosition(bufferPosition);
2505                 if (bufferPosition == mFrameCount) {
2506                     ALOGD("%s(%d): restoring track at end of static buffer", __func__, mPortId);
2507                 }
2508             }
2509         }
2510         // restore volume handler
2511         mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2512             sp<VolumeShaper::Operation> operationToEnd =
2513                     new VolumeShaper::Operation(shaper.mOperation);
2514             // TODO: Ideally we would restore to the exact xOffset position
2515             // as returned by getVolumeShaperState(), but we don't have that
2516             // information when restoring at the client unless we periodically poll
2517             // the server or create shared memory state.
2518             //
2519             // For now, we simply advance to the end of the VolumeShaper effect
2520             // if it has been started.
2521             if (shaper.isStarted()) {
2522                 operationToEnd->setNormalizedTime(1.f);
2523             }
2524             return mAudioTrack->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
2525         });
2526 
2527         if (mState == STATE_ACTIVE) {
2528             result = mAudioTrack->start();
2529         }
2530         // server resets to zero so we offset
2531         mFramesWrittenServerOffset =
2532                 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2533         mFramesWrittenAtRestore = mFramesWrittenServerOffset;
2534     }
2535     if (result != NO_ERROR) {
2536         ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
2537         if (--retries > 0) {
2538             // leave time for an eventual race condition to clear before retrying
2539             usleep(500000);
2540             goto retry;
2541         }
2542         // if no retries left, set invalid bit to force restoring at next occasion
2543         // and avoid inconsistent active state on client and server sides
2544         if (mCblk != nullptr) {
2545             android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
2546         }
2547     }
2548     return result;
2549 }
2550 
updateAndGetPosition_l()2551 Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
2552 {
2553     // This is the sole place to read server consumed frames
2554     Modulo<uint32_t> newServer(mProxy->getPosition());
2555     const int32_t delta = (newServer - mServer).signedValue();
2556     // TODO There is controversy about whether there can be "negative jitter" in server position.
2557     //      This should be investigated further, and if possible, it should be addressed.
2558     //      A more definite failure mode is infrequent polling by client.
2559     //      One could call (void)getPosition_l() in releaseBuffer(),
2560     //      so mReleased and mPosition are always lock-step as best possible.
2561     //      That should ensure delta never goes negative for infrequent polling
2562     //      unless the server has more than 2^31 frames in its buffer,
2563     //      in which case the use of uint32_t for these counters has bigger issues.
2564     ALOGE_IF(delta < 0,
2565             "%s(%d): detected illegal retrograde motion by the server: mServer advanced by %d",
2566             __func__, mPortId, delta);
2567     mServer = newServer;
2568     if (delta > 0) { // avoid retrograde
2569         mPosition += delta;
2570     }
2571     return mPosition;
2572 }
2573 
isSampleRateSpeedAllowed_l(uint32_t sampleRate,float speed)2574 bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
2575 {
2576     updateLatency_l();
2577     // applicable for mixing tracks only (not offloaded or direct)
2578     if (mStaticProxy != 0) {
2579         return true; // static tracks do not have issues with buffer sizing.
2580     }
2581     const size_t minFrameCount =
2582             AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2583                                             sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2584     const bool allowed = mFrameCount >= minFrameCount;
2585     ALOGD_IF(!allowed,
2586             "%s(%d): denied "
2587             "mAfLatency:%u  mAfFrameCount:%zu  mAfSampleRate:%u  sampleRate:%u  speed:%f "
2588             "mFrameCount:%zu < minFrameCount:%zu",
2589             __func__, mPortId,
2590             mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
2591             mFrameCount, minFrameCount);
2592     return allowed;
2593 }
2594 
setParameters(const String8 & keyValuePairs)2595 status_t AudioTrack::setParameters(const String8& keyValuePairs)
2596 {
2597     AutoMutex lock(mLock);
2598     return mAudioTrack->setParameters(keyValuePairs);
2599 }
2600 
selectPresentation(int presentationId,int programId)2601 status_t AudioTrack::selectPresentation(int presentationId, int programId)
2602 {
2603     AutoMutex lock(mLock);
2604     AudioParameter param = AudioParameter();
2605     param.addInt(String8(AudioParameter::keyPresentationId), presentationId);
2606     param.addInt(String8(AudioParameter::keyProgramId), programId);
2607     ALOGV("%s(%d): PresentationId/ProgramId[%s]",
2608             __func__, mPortId, param.toString().string());
2609 
2610     return mAudioTrack->setParameters(param.toString());
2611 }
2612 
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)2613 VolumeShaper::Status AudioTrack::applyVolumeShaper(
2614         const sp<VolumeShaper::Configuration>& configuration,
2615         const sp<VolumeShaper::Operation>& operation)
2616 {
2617     AutoMutex lock(mLock);
2618     mVolumeHandler->setIdIfNecessary(configuration);
2619     VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
2620 
2621     if (status == DEAD_OBJECT) {
2622         if (restoreTrack_l("applyVolumeShaper") == OK) {
2623             status = mAudioTrack->applyVolumeShaper(configuration, operation);
2624         }
2625     }
2626     if (status >= 0) {
2627         // save VolumeShaper for restore
2628         mVolumeHandler->applyVolumeShaper(configuration, operation);
2629         if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2630             mVolumeHandler->setStarted();
2631         }
2632     } else {
2633         // warn only if not an expected restore failure.
2634         ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
2635                 "%s(%d): applyVolumeShaper failed: %d", __func__, mPortId, status);
2636     }
2637     return status;
2638 }
2639 
getVolumeShaperState(int id)2640 sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2641 {
2642     AutoMutex lock(mLock);
2643     sp<VolumeShaper::State> state = mAudioTrack->getVolumeShaperState(id);
2644     if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2645         if (restoreTrack_l("getVolumeShaperState") == OK) {
2646             state = mAudioTrack->getVolumeShaperState(id);
2647         }
2648     }
2649     return state;
2650 }
2651 
getTimestamp(ExtendedTimestamp * timestamp)2652 status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2653 {
2654     if (timestamp == nullptr) {
2655         return BAD_VALUE;
2656     }
2657     AutoMutex lock(mLock);
2658     return getTimestamp_l(timestamp);
2659 }
2660 
getTimestamp_l(ExtendedTimestamp * timestamp)2661 status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2662 {
2663     if (mCblk->mFlags & CBLK_INVALID) {
2664         const status_t status = restoreTrack_l("getTimestampExtended");
2665         if (status != OK) {
2666             // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2667             // recommending that the track be recreated.
2668             return DEAD_OBJECT;
2669         }
2670     }
2671     // check for offloaded/direct here in case restoring somehow changed those flags.
2672     if (isOffloadedOrDirect_l()) {
2673         return INVALID_OPERATION; // not supported
2674     }
2675     status_t status = mProxy->getTimestamp(timestamp);
2676     LOG_ALWAYS_FATAL_IF(status != OK, "%s(%d): status %d not allowed from proxy getTimestamp",
2677             __func__, mPortId, status);
2678     bool found = false;
2679     timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2680     timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2681     // server side frame offset in case AudioTrack has been restored.
2682     for (int i = ExtendedTimestamp::LOCATION_SERVER;
2683             i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2684         if (timestamp->mTimeNs[i] >= 0) {
2685             // apply server offset (frames flushed is ignored
2686             // so we don't report the jump when the flush occurs).
2687             timestamp->mPosition[i] += mFramesWrittenServerOffset;
2688             found = true;
2689         }
2690     }
2691     return found ? OK : WOULD_BLOCK;
2692 }
2693 
getTimestamp(AudioTimestamp & timestamp)2694 status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2695 {
2696     AutoMutex lock(mLock);
2697     return getTimestamp_l(timestamp);
2698 }
2699 
getTimestamp_l(AudioTimestamp & timestamp)2700 status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2701 {
2702     bool previousTimestampValid = mPreviousTimestampValid;
2703     // Set false here to cover all the error return cases.
2704     mPreviousTimestampValid = false;
2705 
2706     switch (mState) {
2707     case STATE_ACTIVE:
2708     case STATE_PAUSED:
2709         break; // handle below
2710     case STATE_FLUSHED:
2711     case STATE_STOPPED:
2712         return WOULD_BLOCK;
2713     case STATE_STOPPING:
2714     case STATE_PAUSED_STOPPING:
2715         if (!isOffloaded_l()) {
2716             return INVALID_OPERATION;
2717         }
2718         break; // offloaded tracks handled below
2719     default:
2720         LOG_ALWAYS_FATAL("%s(%d): Invalid mState in getTimestamp(): %d",
2721                __func__, mPortId, mState);
2722         break;
2723     }
2724 
2725     if (mCblk->mFlags & CBLK_INVALID) {
2726         const status_t status = restoreTrack_l("getTimestamp");
2727         if (status != OK) {
2728             // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2729             // recommending that the track be recreated.
2730             return DEAD_OBJECT;
2731         }
2732     }
2733 
2734     // The presented frame count must always lag behind the consumed frame count.
2735     // To avoid a race, read the presented frames first.  This ensures that presented <= consumed.
2736 
2737     status_t status;
2738     if (isOffloadedOrDirect_l()) {
2739         // use Binder to get timestamp
2740         status = mAudioTrack->getTimestamp(timestamp);
2741     } else {
2742         // read timestamp from shared memory
2743         ExtendedTimestamp ets;
2744         status = mProxy->getTimestamp(&ets);
2745         if (status == OK) {
2746             ExtendedTimestamp::Location location;
2747             status = ets.getBestTimestamp(&timestamp, &location);
2748 
2749             if (status == OK) {
2750                 updateLatency_l();
2751                 // It is possible that the best location has moved from the kernel to the server.
2752                 // In this case we adjust the position from the previous computed latency.
2753                 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2754                     ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
2755                             "%s(%d): location moved from kernel to server",
2756                             __func__, mPortId);
2757                     // check that the last kernel OK time info exists and the positions
2758                     // are valid (if they predate the current track, the positions may
2759                     // be zero or negative).
2760                     const int64_t frames =
2761                             (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2762                             ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2763                             ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2764                             ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
2765                             ?
2766                             int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2767                                     / 1000)
2768                             :
2769                             (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2770                             - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
2771                     ALOGV("%s(%d): frame adjustment:%lld  timestamp:%s",
2772                             __func__, mPortId, (long long)frames, ets.toString().c_str());
2773                     if (frames >= ets.mPosition[location]) {
2774                         timestamp.mPosition = 0;
2775                     } else {
2776                         timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2777                     }
2778                 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2779                     ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
2780                             "%s(%d): location moved from server to kernel",
2781                             __func__, mPortId);
2782 
2783                     if (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER] ==
2784                             ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL]) {
2785                         // In Q, we don't return errors as an invalid time
2786                         // but instead we leave the last kernel good timestamp alone.
2787                         //
2788                         // If server is identical to kernel, the device data pipeline is idle.
2789                         // A better start time is now.  The retrograde check ensures
2790                         // timestamp monotonicity.
2791                         const int64_t nowNs = systemTime();
2792                         if (!mTimestampStallReported) {
2793                             ALOGD("%s(%d): device stall time corrected using current time %lld",
2794                                     __func__, mPortId, (long long)nowNs);
2795                             mTimestampStallReported = true;
2796                         }
2797                         timestamp.mTime = convertNsToTimespec(nowNs);
2798                     }  else {
2799                         mTimestampStallReported = false;
2800                     }
2801                 }
2802 
2803                 // We update the timestamp time even when paused.
2804                 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2805                     const int64_t now = systemTime();
2806                     const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
2807                     const int64_t lag =
2808                             (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2809                                 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2810                             ? int64_t(mAfLatency * 1000000LL)
2811                             : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2812                              - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2813                              * NANOS_PER_SECOND / mSampleRate;
2814                     const int64_t limit = now - lag; // no earlier than this limit
2815                     if (at < limit) {
2816                         ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2817                                 (long long)lag, (long long)at, (long long)limit);
2818                         timestamp.mTime = convertNsToTimespec(limit);
2819                     }
2820                 }
2821                 mPreviousLocation = location;
2822             } else {
2823                 // right after AudioTrack is started, one may not find a timestamp
2824                 ALOGV("%s(%d): getBestTimestamp did not find timestamp", __func__, mPortId);
2825             }
2826         }
2827         if (status == INVALID_OPERATION) {
2828             // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2829             // other failures are signaled by a negative time.
2830             // If we come out of FLUSHED or STOPPED where the position is known
2831             // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2832             // "zero" for NuPlayer).  We don't convert for track restoration as position
2833             // does not reset.
2834             ALOGV("%s(%d): timestamp server offset:%lld restore frames:%lld",
2835                     __func__, mPortId,
2836                     (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2837             if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2838                 status = WOULD_BLOCK;
2839             }
2840         }
2841     }
2842     if (status != NO_ERROR) {
2843         ALOGV_IF(status != WOULD_BLOCK, "%s(%d): getTimestamp error:%#x", __func__, mPortId, status);
2844         return status;
2845     }
2846     if (isOffloadedOrDirect_l()) {
2847         if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2848             // use cached paused position in case another offloaded track is running.
2849             timestamp.mPosition = mPausedPosition;
2850             clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2851             // TODO: adjust for delay
2852             return NO_ERROR;
2853         }
2854 
2855         // Check whether a pending flush or stop has completed, as those commands may
2856         // be asynchronous or return near finish or exhibit glitchy behavior.
2857         //
2858         // Originally this showed up as the first timestamp being a continuation of
2859         // the previous song under gapless playback.
2860         // However, we sometimes see zero timestamps, then a glitch of
2861         // the previous song's position, and then correct timestamps afterwards.
2862         if (mStartFromZeroUs != 0 && mSampleRate != 0) {
2863             static const int kTimeJitterUs = 100000; // 100 ms
2864             static const int k1SecUs = 1000000;
2865 
2866             const int64_t timeNow = getNowUs();
2867 
2868             if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
2869                 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2870                 if (timestampTimeUs < mStartFromZeroUs) {
2871                     return WOULD_BLOCK;  // stale timestamp time, occurs before start.
2872                 }
2873                 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
2874                 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
2875                         / ((double)mSampleRate * mPlaybackRate.mSpeed);
2876 
2877                 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2878                     // Verify that the counter can't count faster than the sample rate
2879                     // since the start time.  If greater, then that means we may have failed
2880                     // to completely flush or stop the previous playing track.
2881                     ALOGW_IF(!mTimestampStartupGlitchReported,
2882                             "%s(%d): startup glitch detected"
2883                             " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2884                             __func__, mPortId,
2885                             (long long)deltaTimeUs, (long long)deltaPositionByUs,
2886                             timestamp.mPosition);
2887                     mTimestampStartupGlitchReported = true;
2888                     if (previousTimestampValid
2889                             && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2890                         timestamp = mPreviousTimestamp;
2891                         mPreviousTimestampValid = true;
2892                         return NO_ERROR;
2893                     }
2894                     return WOULD_BLOCK;
2895                 }
2896                 if (deltaPositionByUs != 0) {
2897                     mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
2898                 }
2899             } else {
2900                 mStartFromZeroUs = 0; // don't check again, start time expired.
2901             }
2902             mTimestampStartupGlitchReported = false;
2903         }
2904     } else {
2905         // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2906         (void) updateAndGetPosition_l();
2907         // Server consumed (mServer) and presented both use the same server time base,
2908         // and server consumed is always >= presented.
2909         // The delta between these represents the number of frames in the buffer pipeline.
2910         // If this delta between these is greater than the client position, it means that
2911         // actually presented is still stuck at the starting line (figuratively speaking),
2912         // waiting for the first frame to go by.  So we can't report a valid timestamp yet.
2913         // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
2914         // mPosition exceeds 32 bits.
2915         // TODO Remove when timestamp is updated to contain pipeline status info.
2916         const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
2917         if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
2918                 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
2919             return INVALID_OPERATION;
2920         }
2921         // Convert timestamp position from server time base to client time base.
2922         // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2923         // But if we change it to 64-bit then this could fail.
2924         // Use Modulo computation here.
2925         timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
2926         // Immediately after a call to getPosition_l(), mPosition and
2927         // mServer both represent the same frame position.  mPosition is
2928         // in client's point of view, and mServer is in server's point of
2929         // view.  So the difference between them is the "fudge factor"
2930         // between client and server views due to stop() and/or new
2931         // IAudioTrack.  And timestamp.mPosition is initially in server's
2932         // point of view, so we need to apply the same fudge factor to it.
2933     }
2934 
2935     // Prevent retrograde motion in timestamp.
2936     // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2937     if (status == NO_ERROR) {
2938         // Fix stale time when checking timestamp right after start().
2939         // The position is at the last reported location but the time can be stale
2940         // due to pause or standby or cold start latency.
2941         //
2942         // We keep advancing the time (but not the position) to ensure that the
2943         // stale value does not confuse the application.
2944         //
2945         // For offload compatibility, use a default lag value here.
2946         // Any time discrepancy between this update and the pause timestamp is handled
2947         // by the retrograde check afterwards.
2948         int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
2949         const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
2950         const int64_t limitNs = mStartNs - lagNs;
2951         if (currentTimeNanos < limitNs) {
2952             if (!mTimestampStaleTimeReported) {
2953                 ALOGD("%s(%d): stale timestamp time corrected, "
2954                         "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
2955                         __func__, mPortId,
2956                         (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
2957                 mTimestampStaleTimeReported = true;
2958             }
2959             timestamp.mTime = convertNsToTimespec(limitNs);
2960             currentTimeNanos = limitNs;
2961         } else {
2962             mTimestampStaleTimeReported = false;
2963         }
2964 
2965         // previousTimestampValid is set to false when starting after a stop or flush.
2966         if (previousTimestampValid) {
2967             const int64_t previousTimeNanos =
2968                     audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
2969 
2970             // retrograde check
2971             if (currentTimeNanos < previousTimeNanos) {
2972                 if (!mTimestampRetrogradeTimeReported) {
2973                     ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
2974                             __func__, mPortId,
2975                             (long long)currentTimeNanos, (long long)previousTimeNanos);
2976                     mTimestampRetrogradeTimeReported = true;
2977                 }
2978                 timestamp.mTime = mPreviousTimestamp.mTime;
2979             } else {
2980                 mTimestampRetrogradeTimeReported = false;
2981             }
2982 
2983             // Looking at signed delta will work even when the timestamps
2984             // are wrapping around.
2985             int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
2986                     - mPreviousTimestamp.mPosition).signedValue();
2987             if (deltaPosition < 0) {
2988                 // Only report once per position instead of spamming the log.
2989                 if (!mTimestampRetrogradePositionReported) {
2990                     ALOGW("%s(%d): retrograde timestamp position corrected, %d = %u - %u",
2991                             __func__, mPortId,
2992                             deltaPosition,
2993                             timestamp.mPosition,
2994                             mPreviousTimestamp.mPosition);
2995                     mTimestampRetrogradePositionReported = true;
2996                 }
2997             } else {
2998                 mTimestampRetrogradePositionReported = false;
2999             }
3000             if (deltaPosition < 0) {
3001                 timestamp.mPosition = mPreviousTimestamp.mPosition;
3002                 deltaPosition = 0;
3003             }
3004 #if 0
3005             // Uncomment this to verify audio timestamp rate.
3006             const int64_t deltaTime =
3007                     audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
3008             if (deltaTime != 0) {
3009                 const int64_t computedSampleRate =
3010                         deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
3011                 ALOGD("%s(%d): computedSampleRate:%u  sampleRate:%u",
3012                         __func__, mPortId,
3013                         (unsigned)computedSampleRate, mSampleRate);
3014             }
3015 #endif
3016         }
3017         mPreviousTimestamp = timestamp;
3018         mPreviousTimestampValid = true;
3019     }
3020 
3021     return status;
3022 }
3023 
getParameters(const String8 & keys)3024 String8 AudioTrack::getParameters(const String8& keys)
3025 {
3026     audio_io_handle_t output = getOutput();
3027     if (output != AUDIO_IO_HANDLE_NONE) {
3028         return AudioSystem::getParameters(output, keys);
3029     } else {
3030         return String8::empty();
3031     }
3032 }
3033 
isOffloaded() const3034 bool AudioTrack::isOffloaded() const
3035 {
3036     AutoMutex lock(mLock);
3037     return isOffloaded_l();
3038 }
3039 
isDirect() const3040 bool AudioTrack::isDirect() const
3041 {
3042     AutoMutex lock(mLock);
3043     return isDirect_l();
3044 }
3045 
isOffloadedOrDirect() const3046 bool AudioTrack::isOffloadedOrDirect() const
3047 {
3048     AutoMutex lock(mLock);
3049     return isOffloadedOrDirect_l();
3050 }
3051 
3052 
dump(int fd,const Vector<String16> & args __unused) const3053 status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
3054 {
3055     String8 result;
3056 
3057     result.append(" AudioTrack::dump\n");
3058     result.appendFormat("  id(%d) status(%d), state(%d), session Id(%d), flags(%#x)\n",
3059                         mPortId, mStatus, mState, mSessionId, mFlags);
3060     result.appendFormat("  stream type(%d), left - right volume(%f, %f)\n",
3061                         (mStreamType == AUDIO_STREAM_DEFAULT) ?
3062                             AudioSystem::attributesToStreamType(mAttributes) :
3063                             mStreamType,
3064                         mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
3065     result.appendFormat("  format(%#x), channel mask(%#x), channel count(%u)\n",
3066                   mFormat, mChannelMask, mChannelCount);
3067     result.appendFormat("  sample rate(%u), original sample rate(%u), speed(%f)\n",
3068                   mSampleRate, mOriginalSampleRate, mPlaybackRate.mSpeed);
3069     result.appendFormat("  frame count(%zu), req. frame count(%zu)\n",
3070                   mFrameCount, mReqFrameCount);
3071     result.appendFormat("  notif. frame count(%u), req. notif. frame count(%u),"
3072             " req. notif. per buff(%u)\n",
3073              mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq);
3074     result.appendFormat("  latency (%d), selected device Id(%d), routed device Id(%d)\n",
3075                         mLatency, mSelectedDeviceId, mRoutedDeviceId);
3076     result.appendFormat("  output(%d) AF latency (%u) AF frame count(%zu) AF SampleRate(%u)\n",
3077                         mOutput, mAfLatency, mAfFrameCount, mAfSampleRate);
3078     ::write(fd, result.string(), result.size());
3079     return NO_ERROR;
3080 }
3081 
getUnderrunCount() const3082 uint32_t AudioTrack::getUnderrunCount() const
3083 {
3084     AutoMutex lock(mLock);
3085     return getUnderrunCount_l();
3086 }
3087 
getUnderrunCount_l() const3088 uint32_t AudioTrack::getUnderrunCount_l() const
3089 {
3090     return mProxy->getUnderrunCount() + mUnderrunCountOffset;
3091 }
3092 
getUnderrunFrames() const3093 uint32_t AudioTrack::getUnderrunFrames() const
3094 {
3095     AutoMutex lock(mLock);
3096     return mProxy->getUnderrunFrames();
3097 }
3098 
addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)3099 status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
3100 {
3101 
3102     if (callback == 0) {
3103         ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
3104         return BAD_VALUE;
3105     }
3106     AutoMutex lock(mLock);
3107     if (mDeviceCallback.unsafe_get() == callback.get()) {
3108         ALOGW("%s(%d): adding same callback!", __func__, mPortId);
3109         return INVALID_OPERATION;
3110     }
3111     status_t status = NO_ERROR;
3112     if (mOutput != AUDIO_IO_HANDLE_NONE) {
3113         if (mDeviceCallback != 0) {
3114             ALOGW("%s(%d): callback already present!", __func__, mPortId);
3115             AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
3116         }
3117         status = AudioSystem::addAudioDeviceCallback(this, mOutput, mPortId);
3118     }
3119     mDeviceCallback = callback;
3120     return status;
3121 }
3122 
removeAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)3123 status_t AudioTrack::removeAudioDeviceCallback(
3124         const sp<AudioSystem::AudioDeviceCallback>& callback)
3125 {
3126     if (callback == 0) {
3127         ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
3128         return BAD_VALUE;
3129     }
3130     AutoMutex lock(mLock);
3131     if (mDeviceCallback.unsafe_get() != callback.get()) {
3132         ALOGW("%s removing different callback!", __FUNCTION__);
3133         return INVALID_OPERATION;
3134     }
3135     mDeviceCallback.clear();
3136     if (mOutput != AUDIO_IO_HANDLE_NONE) {
3137         AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
3138     }
3139     return NO_ERROR;
3140 }
3141 
3142 
onAudioDeviceUpdate(audio_io_handle_t audioIo,audio_port_handle_t deviceId)3143 void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
3144                                  audio_port_handle_t deviceId)
3145 {
3146     sp<AudioSystem::AudioDeviceCallback> callback;
3147     {
3148         AutoMutex lock(mLock);
3149         if (audioIo != mOutput) {
3150             return;
3151         }
3152         callback = mDeviceCallback.promote();
3153         // only update device if the track is active as route changes due to other use cases are
3154         // irrelevant for this client
3155         if (mState == STATE_ACTIVE) {
3156             mRoutedDeviceId = deviceId;
3157         }
3158     }
3159 
3160     if (callback.get() != nullptr) {
3161         callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
3162     }
3163 }
3164 
pendingDuration(int32_t * msec,ExtendedTimestamp::Location location)3165 status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
3166 {
3167     if (msec == nullptr ||
3168             (location != ExtendedTimestamp::LOCATION_SERVER
3169                     && location != ExtendedTimestamp::LOCATION_KERNEL)) {
3170         return BAD_VALUE;
3171     }
3172     AutoMutex lock(mLock);
3173     // inclusive of offloaded and direct tracks.
3174     //
3175     // It is possible, but not enabled, to allow duration computation for non-pcm
3176     // audio_has_proportional_frames() formats because currently they have
3177     // the drain rate equivalent to the pcm sample rate * framesize.
3178     if (!isPurePcmData_l()) {
3179         return INVALID_OPERATION;
3180     }
3181     ExtendedTimestamp ets;
3182     if (getTimestamp_l(&ets) == OK
3183             && ets.mTimeNs[location] > 0) {
3184         int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
3185                 - ets.mPosition[location];
3186         if (diff < 0) {
3187             *msec = 0;
3188         } else {
3189             // ms is the playback time by frames
3190             int64_t ms = (int64_t)((double)diff * 1000 /
3191                     ((double)mSampleRate * mPlaybackRate.mSpeed));
3192             // clockdiff is the timestamp age (negative)
3193             int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
3194                     ets.mTimeNs[location]
3195                     + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
3196                     - systemTime(SYSTEM_TIME_MONOTONIC);
3197 
3198             //ALOGV("ms: %lld  clockdiff: %lld", (long long)ms, (long long)clockdiff);
3199             static const int NANOS_PER_MILLIS = 1000000;
3200             *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
3201         }
3202         return NO_ERROR;
3203     }
3204     if (location != ExtendedTimestamp::LOCATION_SERVER) {
3205         return INVALID_OPERATION; // LOCATION_KERNEL is not available
3206     }
3207     // use server position directly (offloaded and direct arrive here)
3208     updateAndGetPosition_l();
3209     int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
3210     *msec = (diff <= 0) ? 0
3211             : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
3212     return NO_ERROR;
3213 }
3214 
hasStarted()3215 bool AudioTrack::hasStarted()
3216 {
3217     AutoMutex lock(mLock);
3218     switch (mState) {
3219     case STATE_STOPPED:
3220         if (isOffloadedOrDirect_l()) {
3221             // check if we have started in the past to return true.
3222             return mStartFromZeroUs > 0;
3223         }
3224         // A normal audio track may still be draining, so
3225         // check if stream has ended.  This covers fasttrack position
3226         // instability and start/stop without any data written.
3227         if (mProxy->getStreamEndDone()) {
3228             return true;
3229         }
3230         FALLTHROUGH_INTENDED;
3231     case STATE_ACTIVE:
3232     case STATE_STOPPING:
3233         break;
3234     case STATE_PAUSED:
3235     case STATE_PAUSED_STOPPING:
3236     case STATE_FLUSHED:
3237         return false;  // we're not active
3238     default:
3239         LOG_ALWAYS_FATAL("%s(%d): Invalid mState in hasStarted(): %d", __func__, mPortId, mState);
3240         break;
3241     }
3242 
3243     // wait indicates whether we need to wait for a timestamp.
3244     // This is conservatively figured - if we encounter an unexpected error
3245     // then we will not wait.
3246     bool wait = false;
3247     if (isOffloadedOrDirect_l()) {
3248         AudioTimestamp ts;
3249         status_t status = getTimestamp_l(ts);
3250         if (status == WOULD_BLOCK) {
3251             wait = true;
3252         } else if (status == OK) {
3253             wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
3254         }
3255         ALOGV("%s(%d): hasStarted wait:%d  ts:%u  start position:%lld",
3256                 __func__, mPortId,
3257                 (int)wait,
3258                 ts.mPosition,
3259                 (long long)mStartTs.mPosition);
3260     } else {
3261         int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
3262         ExtendedTimestamp ets;
3263         status_t status = getTimestamp_l(&ets);
3264         if (status == WOULD_BLOCK) {  // no SERVER or KERNEL frame info in ets
3265             wait = true;
3266         } else if (status == OK) {
3267             for (location = ExtendedTimestamp::LOCATION_KERNEL;
3268                     location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
3269                 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
3270                     continue;
3271                 }
3272                 wait = ets.mPosition[location] == 0
3273                         || ets.mPosition[location] == mStartEts.mPosition[location];
3274                 break;
3275             }
3276         }
3277         ALOGV("%s(%d): hasStarted wait:%d  ets:%lld  start position:%lld",
3278                 __func__, mPortId,
3279                 (int)wait,
3280                 (long long)ets.mPosition[location],
3281                 (long long)mStartEts.mPosition[location]);
3282     }
3283     return !wait;
3284 }
3285 
3286 // =========================================================================
3287 
binderDied(const wp<IBinder> & who __unused)3288 void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
3289 {
3290     sp<AudioTrack> audioTrack = mAudioTrack.promote();
3291     if (audioTrack != 0) {
3292         AutoMutex lock(audioTrack->mLock);
3293         audioTrack->mProxy->binderDied();
3294     }
3295 }
3296 
3297 // =========================================================================
3298 
AudioTrackThread(AudioTrack & receiver)3299 AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver)
3300     : Thread(true /* bCanCallJava */)  // binder recursion on restoreTrack_l() may call Java.
3301     , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
3302       mIgnoreNextPausedInt(false)
3303 {
3304 }
3305 
~AudioTrackThread()3306 AudioTrack::AudioTrackThread::~AudioTrackThread()
3307 {
3308 }
3309 
threadLoop()3310 bool AudioTrack::AudioTrackThread::threadLoop()
3311 {
3312     {
3313         AutoMutex _l(mMyLock);
3314         if (mPaused) {
3315             // TODO check return value and handle or log
3316             mMyCond.wait(mMyLock);
3317             // caller will check for exitPending()
3318             return true;
3319         }
3320         if (mIgnoreNextPausedInt) {
3321             mIgnoreNextPausedInt = false;
3322             mPausedInt = false;
3323         }
3324         if (mPausedInt) {
3325             // TODO use futex instead of condition, for event flag "or"
3326             if (mPausedNs > 0) {
3327                 // TODO check return value and handle or log
3328                 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3329             } else {
3330                 // TODO check return value and handle or log
3331                 mMyCond.wait(mMyLock);
3332             }
3333             mPausedInt = false;
3334             return true;
3335         }
3336     }
3337     if (exitPending()) {
3338         return false;
3339     }
3340     nsecs_t ns = mReceiver.processAudioBuffer();
3341     switch (ns) {
3342     case 0:
3343         return true;
3344     case NS_INACTIVE:
3345         pauseInternal();
3346         return true;
3347     case NS_NEVER:
3348         return false;
3349     case NS_WHENEVER:
3350         // Event driven: call wake() when callback notifications conditions change.
3351         ns = INT64_MAX;
3352         FALLTHROUGH_INTENDED;
3353     default:
3354         LOG_ALWAYS_FATAL_IF(ns < 0, "%s(%d): processAudioBuffer() returned %lld",
3355                 __func__, mReceiver.mPortId, (long long)ns);
3356         pauseInternal(ns);
3357         return true;
3358     }
3359 }
3360 
requestExit()3361 void AudioTrack::AudioTrackThread::requestExit()
3362 {
3363     // must be in this order to avoid a race condition
3364     Thread::requestExit();
3365     resume();
3366 }
3367 
pause()3368 void AudioTrack::AudioTrackThread::pause()
3369 {
3370     AutoMutex _l(mMyLock);
3371     mPaused = true;
3372 }
3373 
resume()3374 void AudioTrack::AudioTrackThread::resume()
3375 {
3376     AutoMutex _l(mMyLock);
3377     mIgnoreNextPausedInt = true;
3378     if (mPaused || mPausedInt) {
3379         mPaused = false;
3380         mPausedInt = false;
3381         mMyCond.signal();
3382     }
3383 }
3384 
wake()3385 void AudioTrack::AudioTrackThread::wake()
3386 {
3387     AutoMutex _l(mMyLock);
3388     if (!mPaused) {
3389         // wake() might be called while servicing a callback - ignore the next
3390         // pause time and call processAudioBuffer.
3391         mIgnoreNextPausedInt = true;
3392         if (mPausedInt && mPausedNs > 0) {
3393             // audio track is active and internally paused with timeout.
3394             mPausedInt = false;
3395             mMyCond.signal();
3396         }
3397     }
3398 }
3399 
pauseInternal(nsecs_t ns)3400 void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3401 {
3402     AutoMutex _l(mMyLock);
3403     mPausedInt = true;
3404     mPausedNs = ns;
3405 }
3406 
onCodecFormatChanged(const std::vector<uint8_t> & audioMetadata)3407 binder::Status AudioTrack::AudioTrackCallback::onCodecFormatChanged(
3408         const std::vector<uint8_t>& audioMetadata)
3409 {
3410     AutoMutex _l(mAudioTrackCbLock);
3411     sp<media::IAudioTrackCallback> callback = mCallback.promote();
3412     if (callback.get() != nullptr) {
3413         callback->onCodecFormatChanged(audioMetadata);
3414     } else {
3415         mCallback.clear();
3416     }
3417     return binder::Status::ok();
3418 }
3419 
setAudioTrackCallback(const sp<media::IAudioTrackCallback> & callback)3420 void AudioTrack::AudioTrackCallback::setAudioTrackCallback(
3421         const sp<media::IAudioTrackCallback> &callback) {
3422     AutoMutex lock(mAudioTrackCbLock);
3423     mCallback = callback;
3424 }
3425 
3426 } // namespace android
3427