• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <audio_utils/primitives.h>
26 #include <binder/IPCThreadState.h>
27 #include <media/AudioTrack.h>
28 #include <utils/Log.h>
29 #include <private/media/AudioTrackShared.h>
30 #include <media/IAudioFlinger.h>
31 #include <media/AudioPolicyHelper.h>
32 #include <media/AudioResamplerPublic.h>
33 
34 #define WAIT_PERIOD_MS                  10
35 #define WAIT_STREAM_END_TIMEOUT_SEC     120
36 static const int kMaxLoopCountNotifications = 32;
37 
38 namespace android {
39 // ---------------------------------------------------------------------------
40 
41 // TODO: Move to a separate .h
42 
43 template <typename T>
min(const T & x,const T & y)44 static inline const T &min(const T &x, const T &y) {
45     return x < y ? x : y;
46 }
47 
48 template <typename T>
max(const T & x,const T & y)49 static inline const T &max(const T &x, const T &y) {
50     return x > y ? x : y;
51 }
52 
framesToNanoseconds(ssize_t frames,uint32_t sampleRate,float speed)53 static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
54 {
55     return ((double)frames * 1000000000) / ((double)sampleRate * speed);
56 }
57 
convertTimespecToUs(const struct timespec & tv)58 static int64_t convertTimespecToUs(const struct timespec &tv)
59 {
60     return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
61 }
62 
63 // current monotonic time in microseconds.
getNowUs()64 static int64_t getNowUs()
65 {
66     struct timespec tv;
67     (void) clock_gettime(CLOCK_MONOTONIC, &tv);
68     return convertTimespecToUs(tv);
69 }
70 
71 // FIXME: we don't use the pitch setting in the time stretcher (not working);
72 // instead we emulate it using our sample rate converter.
73 static const bool kFixPitch = true; // enable pitch fix
adjustSampleRate(uint32_t sampleRate,float pitch)74 static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
75 {
76     return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
77 }
78 
adjustSpeed(float speed,float pitch)79 static inline float adjustSpeed(float speed, float pitch)
80 {
81     return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
82 }
83 
adjustPitch(float pitch)84 static inline float adjustPitch(float pitch)
85 {
86     return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
87 }
88 
89 // Must match similar computation in createTrack_l in Threads.cpp.
90 // TODO: Move to a common library
calculateMinFrameCount(uint32_t afLatencyMs,uint32_t afFrameCount,uint32_t afSampleRate,uint32_t sampleRate,float speed)91 static size_t calculateMinFrameCount(
92         uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
93         uint32_t sampleRate, float speed)
94 {
95     // Ensure that buffer depth covers at least audio hardware latency
96     uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
97     if (minBufCount < 2) {
98         minBufCount = 2;
99     }
100     ALOGV("calculateMinFrameCount afLatency %u  afFrameCount %u  afSampleRate %u  "
101             "sampleRate %u  speed %f  minBufCount: %u",
102             afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount);
103     return minBufCount * sourceFramesNeededWithTimestretch(
104             sampleRate, afFrameCount, afSampleRate, speed);
105 }
106 
107 // static
getMinFrameCount(size_t * frameCount,audio_stream_type_t streamType,uint32_t sampleRate)108 status_t AudioTrack::getMinFrameCount(
109         size_t* frameCount,
110         audio_stream_type_t streamType,
111         uint32_t sampleRate)
112 {
113     if (frameCount == NULL) {
114         return BAD_VALUE;
115     }
116 
117     // FIXME handle in server, like createTrack_l(), possible missing info:
118     //          audio_io_handle_t output
119     //          audio_format_t format
120     //          audio_channel_mask_t channelMask
121     //          audio_output_flags_t flags (FAST)
122     uint32_t afSampleRate;
123     status_t status;
124     status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
125     if (status != NO_ERROR) {
126         ALOGE("Unable to query output sample rate for stream type %d; status %d",
127                 streamType, status);
128         return status;
129     }
130     size_t afFrameCount;
131     status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
132     if (status != NO_ERROR) {
133         ALOGE("Unable to query output frame count for stream type %d; status %d",
134                 streamType, status);
135         return status;
136     }
137     uint32_t afLatency;
138     status = AudioSystem::getOutputLatency(&afLatency, streamType);
139     if (status != NO_ERROR) {
140         ALOGE("Unable to query output latency for stream type %d; status %d",
141                 streamType, status);
142         return status;
143     }
144 
145     // When called from createTrack, speed is 1.0f (normal speed).
146     // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
147     *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f);
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("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
154                 streamType, sampleRate);
155         return BAD_VALUE;
156     }
157     ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
158             *frameCount, afFrameCount, afSampleRate, afLatency);
159     return NO_ERROR;
160 }
161 
162 // ---------------------------------------------------------------------------
163 
AudioTrack()164 AudioTrack::AudioTrack()
165     : mStatus(NO_INIT),
166       mIsTimed(false),
167       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
168       mPreviousSchedulingGroup(SP_DEFAULT),
169       mPausedPosition(0),
170       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
171 {
172     mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
173     mAttributes.usage = AUDIO_USAGE_UNKNOWN;
174     mAttributes.flags = 0x0;
175     strcpy(mAttributes.tags, "");
176 }
177 
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,uint32_t notificationFrames,int sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,int uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect)178 AudioTrack::AudioTrack(
179         audio_stream_type_t streamType,
180         uint32_t sampleRate,
181         audio_format_t format,
182         audio_channel_mask_t channelMask,
183         size_t frameCount,
184         audio_output_flags_t flags,
185         callback_t cbf,
186         void* user,
187         uint32_t notificationFrames,
188         int sessionId,
189         transfer_type transferType,
190         const audio_offload_info_t *offloadInfo,
191         int uid,
192         pid_t pid,
193         const audio_attributes_t* pAttributes,
194         bool doNotReconnect)
195     : mStatus(NO_INIT),
196       mIsTimed(false),
197       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
198       mPreviousSchedulingGroup(SP_DEFAULT),
199       mPausedPosition(0),
200       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
201 {
202     mStatus = set(streamType, sampleRate, format, channelMask,
203             frameCount, flags, cbf, user, notificationFrames,
204             0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
205             offloadInfo, uid, pid, pAttributes, doNotReconnect);
206 }
207 
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,uint32_t notificationFrames,int sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,int uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect)208 AudioTrack::AudioTrack(
209         audio_stream_type_t streamType,
210         uint32_t sampleRate,
211         audio_format_t format,
212         audio_channel_mask_t channelMask,
213         const sp<IMemory>& sharedBuffer,
214         audio_output_flags_t flags,
215         callback_t cbf,
216         void* user,
217         uint32_t notificationFrames,
218         int sessionId,
219         transfer_type transferType,
220         const audio_offload_info_t *offloadInfo,
221         int uid,
222         pid_t pid,
223         const audio_attributes_t* pAttributes,
224         bool doNotReconnect)
225     : mStatus(NO_INIT),
226       mIsTimed(false),
227       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
228       mPreviousSchedulingGroup(SP_DEFAULT),
229       mPausedPosition(0),
230       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
231 {
232     mStatus = set(streamType, sampleRate, format, channelMask,
233             0 /*frameCount*/, flags, cbf, user, notificationFrames,
234             sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
235             uid, pid, pAttributes, doNotReconnect);
236 }
237 
~AudioTrack()238 AudioTrack::~AudioTrack()
239 {
240     if (mStatus == NO_ERROR) {
241         // Make sure that callback function exits in the case where
242         // it is looping on buffer full condition in obtainBuffer().
243         // Otherwise the callback thread will never exit.
244         stop();
245         if (mAudioTrackThread != 0) {
246             mProxy->interrupt();
247             mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
248             mAudioTrackThread->requestExitAndWait();
249             mAudioTrackThread.clear();
250         }
251         // No lock here: worst case we remove a NULL callback which will be a nop
252         if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
253             AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
254         }
255         IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
256         mAudioTrack.clear();
257         mCblkMemory.clear();
258         mSharedBuffer.clear();
259         IPCThreadState::self()->flushCommands();
260         ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
261                 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
262         AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
263     }
264 }
265 
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,uint32_t notificationFrames,const sp<IMemory> & sharedBuffer,bool threadCanCallJava,int sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,int uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect)266 status_t AudioTrack::set(
267         audio_stream_type_t streamType,
268         uint32_t sampleRate,
269         audio_format_t format,
270         audio_channel_mask_t channelMask,
271         size_t frameCount,
272         audio_output_flags_t flags,
273         callback_t cbf,
274         void* user,
275         uint32_t notificationFrames,
276         const sp<IMemory>& sharedBuffer,
277         bool threadCanCallJava,
278         int sessionId,
279         transfer_type transferType,
280         const audio_offload_info_t *offloadInfo,
281         int uid,
282         pid_t pid,
283         const audio_attributes_t* pAttributes,
284         bool doNotReconnect)
285 {
286     ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
287           "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
288           streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
289           sessionId, transferType, uid, pid);
290 
291     switch (transferType) {
292     case TRANSFER_DEFAULT:
293         if (sharedBuffer != 0) {
294             transferType = TRANSFER_SHARED;
295         } else if (cbf == NULL || threadCanCallJava) {
296             transferType = TRANSFER_SYNC;
297         } else {
298             transferType = TRANSFER_CALLBACK;
299         }
300         break;
301     case TRANSFER_CALLBACK:
302         if (cbf == NULL || sharedBuffer != 0) {
303             ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
304             return BAD_VALUE;
305         }
306         break;
307     case TRANSFER_OBTAIN:
308     case TRANSFER_SYNC:
309         if (sharedBuffer != 0) {
310             ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
311             return BAD_VALUE;
312         }
313         break;
314     case TRANSFER_SHARED:
315         if (sharedBuffer == 0) {
316             ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
317             return BAD_VALUE;
318         }
319         break;
320     default:
321         ALOGE("Invalid transfer type %d", transferType);
322         return BAD_VALUE;
323     }
324     mSharedBuffer = sharedBuffer;
325     mTransfer = transferType;
326     mDoNotReconnect = doNotReconnect;
327 
328     ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
329             sharedBuffer->size());
330 
331     ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
332 
333     // invariant that mAudioTrack != 0 is true only after set() returns successfully
334     if (mAudioTrack != 0) {
335         ALOGE("Track already in use");
336         return INVALID_OPERATION;
337     }
338 
339     // handle default values first.
340     if (streamType == AUDIO_STREAM_DEFAULT) {
341         streamType = AUDIO_STREAM_MUSIC;
342     }
343     if (pAttributes == NULL) {
344         if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
345             ALOGE("Invalid stream type %d", streamType);
346             return BAD_VALUE;
347         }
348         mStreamType = streamType;
349 
350     } else {
351         // stream type shouldn't be looked at, this track has audio attributes
352         memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
353         ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
354                 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
355         mStreamType = AUDIO_STREAM_DEFAULT;
356         if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
357             flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
358         }
359     }
360 
361     // these below should probably come from the audioFlinger too...
362     if (format == AUDIO_FORMAT_DEFAULT) {
363         format = AUDIO_FORMAT_PCM_16_BIT;
364     }
365 
366     // validate parameters
367     if (!audio_is_valid_format(format)) {
368         ALOGE("Invalid format %#x", format);
369         return BAD_VALUE;
370     }
371     mFormat = format;
372 
373     if (!audio_is_output_channel(channelMask)) {
374         ALOGE("Invalid channel mask %#x", channelMask);
375         return BAD_VALUE;
376     }
377     mChannelMask = channelMask;
378     uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
379     mChannelCount = channelCount;
380 
381     // force direct flag if format is not linear PCM
382     // or offload was requested
383     if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
384             || !audio_is_linear_pcm(format)) {
385         ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
386                     ? "Offload request, forcing to Direct Output"
387                     : "Not linear PCM, forcing to Direct Output");
388         flags = (audio_output_flags_t)
389                 // FIXME why can't we allow direct AND fast?
390                 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
391     }
392 
393     // force direct flag if HW A/V sync requested
394     if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
395         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
396     }
397 
398     if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
399         if (audio_is_linear_pcm(format)) {
400             mFrameSize = channelCount * audio_bytes_per_sample(format);
401         } else {
402             mFrameSize = sizeof(uint8_t);
403         }
404     } else {
405         ALOG_ASSERT(audio_is_linear_pcm(format));
406         mFrameSize = channelCount * audio_bytes_per_sample(format);
407         // createTrack will return an error if PCM format is not supported by server,
408         // so no need to check for specific PCM formats here
409     }
410 
411     // sampling rate must be specified for direct outputs
412     if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
413         return BAD_VALUE;
414     }
415     mSampleRate = sampleRate;
416     mOriginalSampleRate = sampleRate;
417     mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
418 
419     // Make copy of input parameter offloadInfo so that in the future:
420     //  (a) createTrack_l doesn't need it as an input parameter
421     //  (b) we can support re-creation of offloaded tracks
422     if (offloadInfo != NULL) {
423         mOffloadInfoCopy = *offloadInfo;
424         mOffloadInfo = &mOffloadInfoCopy;
425     } else {
426         mOffloadInfo = NULL;
427     }
428 
429     mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
430     mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
431     mSendLevel = 0.0f;
432     // mFrameCount is initialized in createTrack_l
433     mReqFrameCount = frameCount;
434     mNotificationFramesReq = notificationFrames;
435     mNotificationFramesAct = 0;
436     if (sessionId == AUDIO_SESSION_ALLOCATE) {
437         mSessionId = AudioSystem::newAudioUniqueId();
438     } else {
439         mSessionId = sessionId;
440     }
441     int callingpid = IPCThreadState::self()->getCallingPid();
442     int mypid = getpid();
443     if (uid == -1 || (callingpid != mypid)) {
444         mClientUid = IPCThreadState::self()->getCallingUid();
445     } else {
446         mClientUid = uid;
447     }
448     if (pid == -1 || (callingpid != mypid)) {
449         mClientPid = callingpid;
450     } else {
451         mClientPid = pid;
452     }
453     mAuxEffectId = 0;
454     mFlags = flags;
455     mCbf = cbf;
456 
457     if (cbf != NULL) {
458         mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
459         mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
460         // thread begins in paused state, and will not reference us until start()
461     }
462 
463     // create the IAudioTrack
464     status_t status = createTrack_l();
465 
466     if (status != NO_ERROR) {
467         if (mAudioTrackThread != 0) {
468             mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
469             mAudioTrackThread->requestExitAndWait();
470             mAudioTrackThread.clear();
471         }
472         return status;
473     }
474 
475     mStatus = NO_ERROR;
476     mState = STATE_STOPPED;
477     mUserData = user;
478     mLoopCount = 0;
479     mLoopStart = 0;
480     mLoopEnd = 0;
481     mLoopCountNotified = 0;
482     mMarkerPosition = 0;
483     mMarkerReached = false;
484     mNewPosition = 0;
485     mUpdatePeriod = 0;
486     mPosition = 0;
487     mReleased = 0;
488     mStartUs = 0;
489     AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
490     mSequence = 1;
491     mObservedSequence = mSequence;
492     mInUnderrun = false;
493     mPreviousTimestampValid = false;
494     mTimestampStartupGlitchReported = false;
495     mRetrogradeMotionReported = false;
496 
497     return NO_ERROR;
498 }
499 
500 // -------------------------------------------------------------------------
501 
start()502 status_t AudioTrack::start()
503 {
504     AutoMutex lock(mLock);
505 
506     if (mState == STATE_ACTIVE) {
507         return INVALID_OPERATION;
508     }
509 
510     mInUnderrun = true;
511 
512     State previousState = mState;
513     if (previousState == STATE_PAUSED_STOPPING) {
514         mState = STATE_STOPPING;
515     } else {
516         mState = STATE_ACTIVE;
517     }
518     (void) updateAndGetPosition_l();
519     if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
520         // reset current position as seen by client to 0
521         mPosition = 0;
522         mPreviousTimestampValid = false;
523         mTimestampStartupGlitchReported = false;
524         mRetrogradeMotionReported = false;
525 
526         // If previousState == STATE_STOPPED, we reactivate markers (mMarkerPosition != 0)
527         // as the position is reset to 0. This is legacy behavior. This is not done
528         // in stop() to avoid a race condition where the last marker event is issued twice.
529         // Note: the if is technically unnecessary because previousState == STATE_FLUSHED
530         // is only for streaming tracks, and mMarkerReached is already set to false.
531         if (previousState == STATE_STOPPED) {
532             mMarkerReached = false;
533         }
534 
535         // For offloaded tracks, we don't know if the hardware counters are really zero here,
536         // since the flush is asynchronous and stop may not fully drain.
537         // We save the time when the track is started to later verify whether
538         // the counters are realistic (i.e. start from zero after this time).
539         mStartUs = getNowUs();
540 
541         // force refresh of remaining frames by processAudioBuffer() as last
542         // write before stop could be partial.
543         mRefreshRemaining = true;
544     }
545     mNewPosition = mPosition + mUpdatePeriod;
546     int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
547 
548     sp<AudioTrackThread> t = mAudioTrackThread;
549     if (t != 0) {
550         if (previousState == STATE_STOPPING) {
551             mProxy->interrupt();
552         } else {
553             t->resume();
554         }
555     } else {
556         mPreviousPriority = getpriority(PRIO_PROCESS, 0);
557         get_sched_policy(0, &mPreviousSchedulingGroup);
558         androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
559     }
560 
561     status_t status = NO_ERROR;
562     if (!(flags & CBLK_INVALID)) {
563         status = mAudioTrack->start();
564         if (status == DEAD_OBJECT) {
565             flags |= CBLK_INVALID;
566         }
567     }
568     if (flags & CBLK_INVALID) {
569         status = restoreTrack_l("start");
570     }
571 
572     if (status != NO_ERROR) {
573         ALOGE("start() status %d", status);
574         mState = previousState;
575         if (t != 0) {
576             if (previousState != STATE_STOPPING) {
577                 t->pause();
578             }
579         } else {
580             setpriority(PRIO_PROCESS, 0, mPreviousPriority);
581             set_sched_policy(0, mPreviousSchedulingGroup);
582         }
583     }
584 
585     return status;
586 }
587 
stop()588 void AudioTrack::stop()
589 {
590     AutoMutex lock(mLock);
591     if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
592         return;
593     }
594 
595     if (isOffloaded_l()) {
596         mState = STATE_STOPPING;
597     } else {
598         mState = STATE_STOPPED;
599         mReleased = 0;
600     }
601 
602     mProxy->interrupt();
603     mAudioTrack->stop();
604 
605     // Note: legacy handling - stop does not clear playback marker
606     // and periodic update counter, but flush does for streaming tracks.
607 
608     if (mSharedBuffer != 0) {
609         // clear buffer position and loop count.
610         mStaticProxy->setBufferPositionAndLoop(0 /* position */,
611                 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
612     }
613 
614     sp<AudioTrackThread> t = mAudioTrackThread;
615     if (t != 0) {
616         if (!isOffloaded_l()) {
617             t->pause();
618         }
619     } else {
620         setpriority(PRIO_PROCESS, 0, mPreviousPriority);
621         set_sched_policy(0, mPreviousSchedulingGroup);
622     }
623 }
624 
stopped() const625 bool AudioTrack::stopped() const
626 {
627     AutoMutex lock(mLock);
628     return mState != STATE_ACTIVE;
629 }
630 
flush()631 void AudioTrack::flush()
632 {
633     if (mSharedBuffer != 0) {
634         return;
635     }
636     AutoMutex lock(mLock);
637     if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
638         return;
639     }
640     flush_l();
641 }
642 
flush_l()643 void AudioTrack::flush_l()
644 {
645     ALOG_ASSERT(mState != STATE_ACTIVE);
646 
647     // clear playback marker and periodic update counter
648     mMarkerPosition = 0;
649     mMarkerReached = false;
650     mUpdatePeriod = 0;
651     mRefreshRemaining = true;
652 
653     mState = STATE_FLUSHED;
654     mReleased = 0;
655     if (isOffloaded_l()) {
656         mProxy->interrupt();
657     }
658     mProxy->flush();
659     mAudioTrack->flush();
660 }
661 
pause()662 void AudioTrack::pause()
663 {
664     AutoMutex lock(mLock);
665     if (mState == STATE_ACTIVE) {
666         mState = STATE_PAUSED;
667     } else if (mState == STATE_STOPPING) {
668         mState = STATE_PAUSED_STOPPING;
669     } else {
670         return;
671     }
672     mProxy->interrupt();
673     mAudioTrack->pause();
674 
675     if (isOffloaded_l()) {
676         if (mOutput != AUDIO_IO_HANDLE_NONE) {
677             // An offload output can be re-used between two audio tracks having
678             // the same configuration. A timestamp query for a paused track
679             // while the other is running would return an incorrect time.
680             // To fix this, cache the playback position on a pause() and return
681             // this time when requested until the track is resumed.
682 
683             // OffloadThread sends HAL pause in its threadLoop. Time saved
684             // here can be slightly off.
685 
686             // TODO: check return code for getRenderPosition.
687 
688             uint32_t halFrames;
689             AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
690             ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
691         }
692     }
693 }
694 
setVolume(float left,float right)695 status_t AudioTrack::setVolume(float left, float right)
696 {
697     // This duplicates a test by AudioTrack JNI, but that is not the only caller
698     if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
699             isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
700         return BAD_VALUE;
701     }
702 
703     AutoMutex lock(mLock);
704     mVolume[AUDIO_INTERLEAVE_LEFT] = left;
705     mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
706 
707     mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
708 
709     if (isOffloaded_l()) {
710         mAudioTrack->signal();
711     }
712     return NO_ERROR;
713 }
714 
setVolume(float volume)715 status_t AudioTrack::setVolume(float volume)
716 {
717     return setVolume(volume, volume);
718 }
719 
setAuxEffectSendLevel(float level)720 status_t AudioTrack::setAuxEffectSendLevel(float level)
721 {
722     // This duplicates a test by AudioTrack JNI, but that is not the only caller
723     if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
724         return BAD_VALUE;
725     }
726 
727     AutoMutex lock(mLock);
728     mSendLevel = level;
729     mProxy->setSendLevel(level);
730 
731     return NO_ERROR;
732 }
733 
getAuxEffectSendLevel(float * level) const734 void AudioTrack::getAuxEffectSendLevel(float* level) const
735 {
736     if (level != NULL) {
737         *level = mSendLevel;
738     }
739 }
740 
setSampleRate(uint32_t rate)741 status_t AudioTrack::setSampleRate(uint32_t rate)
742 {
743     AutoMutex lock(mLock);
744     if (rate == mSampleRate) {
745         return NO_ERROR;
746     }
747     if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
748         return INVALID_OPERATION;
749     }
750     if (mOutput == AUDIO_IO_HANDLE_NONE) {
751         return NO_INIT;
752     }
753     // NOTE: it is theoretically possible, but highly unlikely, that a device change
754     // could mean a previously allowed sampling rate is no longer allowed.
755     uint32_t afSamplingRate;
756     if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
757         return NO_INIT;
758     }
759     // pitch is emulated by adjusting speed and sampleRate
760     const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
761     if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
762         return BAD_VALUE;
763     }
764     // TODO: Should we also check if the buffer size is compatible?
765 
766     mSampleRate = rate;
767     mProxy->setSampleRate(effectiveSampleRate);
768 
769     return NO_ERROR;
770 }
771 
getSampleRate() const772 uint32_t AudioTrack::getSampleRate() const
773 {
774     if (mIsTimed) {
775         return 0;
776     }
777 
778     AutoMutex lock(mLock);
779 
780     // sample rate can be updated during playback by the offloaded decoder so we need to
781     // query the HAL and update if needed.
782 // FIXME use Proxy return channel to update the rate from server and avoid polling here
783     if (isOffloadedOrDirect_l()) {
784         if (mOutput != AUDIO_IO_HANDLE_NONE) {
785             uint32_t sampleRate = 0;
786             status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
787             if (status == NO_ERROR) {
788                 mSampleRate = sampleRate;
789             }
790         }
791     }
792     return mSampleRate;
793 }
794 
getOriginalSampleRate() const795 uint32_t AudioTrack::getOriginalSampleRate() const
796 {
797     if (mIsTimed) {
798         return 0;
799     }
800 
801     return mOriginalSampleRate;
802 }
803 
setPlaybackRate(const AudioPlaybackRate & playbackRate)804 status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
805 {
806     AutoMutex lock(mLock);
807     if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
808         return NO_ERROR;
809     }
810     if (mIsTimed || isOffloadedOrDirect_l()) {
811         return INVALID_OPERATION;
812     }
813     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
814         return INVALID_OPERATION;
815     }
816     // pitch is emulated by adjusting speed and sampleRate
817     const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
818     const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
819     const float effectivePitch = adjustPitch(playbackRate.mPitch);
820     AudioPlaybackRate playbackRateTemp = playbackRate;
821     playbackRateTemp.mSpeed = effectiveSpeed;
822     playbackRateTemp.mPitch = effectivePitch;
823 
824     if (!isAudioPlaybackRateValid(playbackRateTemp)) {
825         return BAD_VALUE;
826     }
827     // Check if the buffer size is compatible.
828     if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
829         ALOGV("setPlaybackRate(%f, %f) failed", playbackRate.mSpeed, playbackRate.mPitch);
830         return BAD_VALUE;
831     }
832 
833     // Check resampler ratios are within bounds
834     if (effectiveRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
835         ALOGV("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
836                 playbackRate.mSpeed, playbackRate.mPitch);
837         return BAD_VALUE;
838     }
839 
840     if (effectiveRate * AUDIO_RESAMPLER_UP_RATIO_MAX < mSampleRate) {
841         ALOGV("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
842                         playbackRate.mSpeed, playbackRate.mPitch);
843         return BAD_VALUE;
844     }
845     mPlaybackRate = playbackRate;
846     //set effective rates
847     mProxy->setPlaybackRate(playbackRateTemp);
848     mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
849     return NO_ERROR;
850 }
851 
getPlaybackRate() const852 const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
853 {
854     AutoMutex lock(mLock);
855     return mPlaybackRate;
856 }
857 
setLoop(uint32_t loopStart,uint32_t loopEnd,int loopCount)858 status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
859 {
860     if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
861         return INVALID_OPERATION;
862     }
863 
864     if (loopCount == 0) {
865         ;
866     } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
867             loopEnd - loopStart >= MIN_LOOP) {
868         ;
869     } else {
870         return BAD_VALUE;
871     }
872 
873     AutoMutex lock(mLock);
874     // See setPosition() regarding setting parameters such as loop points or position while active
875     if (mState == STATE_ACTIVE) {
876         return INVALID_OPERATION;
877     }
878     setLoop_l(loopStart, loopEnd, loopCount);
879     return NO_ERROR;
880 }
881 
setLoop_l(uint32_t loopStart,uint32_t loopEnd,int loopCount)882 void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
883 {
884     // We do not update the periodic notification point.
885     // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
886     mLoopCount = loopCount;
887     mLoopEnd = loopEnd;
888     mLoopStart = loopStart;
889     mLoopCountNotified = loopCount;
890     mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
891 
892     // Waking the AudioTrackThread is not needed as this cannot be called when active.
893 }
894 
setMarkerPosition(uint32_t marker)895 status_t AudioTrack::setMarkerPosition(uint32_t marker)
896 {
897     // The only purpose of setting marker position is to get a callback
898     if (mCbf == NULL || isOffloadedOrDirect()) {
899         return INVALID_OPERATION;
900     }
901 
902     AutoMutex lock(mLock);
903     mMarkerPosition = marker;
904     mMarkerReached = false;
905 
906     sp<AudioTrackThread> t = mAudioTrackThread;
907     if (t != 0) {
908         t->wake();
909     }
910     return NO_ERROR;
911 }
912 
getMarkerPosition(uint32_t * marker) const913 status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
914 {
915     if (isOffloadedOrDirect()) {
916         return INVALID_OPERATION;
917     }
918     if (marker == NULL) {
919         return BAD_VALUE;
920     }
921 
922     AutoMutex lock(mLock);
923     *marker = mMarkerPosition;
924 
925     return NO_ERROR;
926 }
927 
setPositionUpdatePeriod(uint32_t updatePeriod)928 status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
929 {
930     // The only purpose of setting position update period is to get a callback
931     if (mCbf == NULL || isOffloadedOrDirect()) {
932         return INVALID_OPERATION;
933     }
934 
935     AutoMutex lock(mLock);
936     mNewPosition = updateAndGetPosition_l() + updatePeriod;
937     mUpdatePeriod = updatePeriod;
938 
939     sp<AudioTrackThread> t = mAudioTrackThread;
940     if (t != 0) {
941         t->wake();
942     }
943     return NO_ERROR;
944 }
945 
getPositionUpdatePeriod(uint32_t * updatePeriod) const946 status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
947 {
948     if (isOffloadedOrDirect()) {
949         return INVALID_OPERATION;
950     }
951     if (updatePeriod == NULL) {
952         return BAD_VALUE;
953     }
954 
955     AutoMutex lock(mLock);
956     *updatePeriod = mUpdatePeriod;
957 
958     return NO_ERROR;
959 }
960 
setPosition(uint32_t position)961 status_t AudioTrack::setPosition(uint32_t position)
962 {
963     if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
964         return INVALID_OPERATION;
965     }
966     if (position > mFrameCount) {
967         return BAD_VALUE;
968     }
969 
970     AutoMutex lock(mLock);
971     // Currently we require that the player is inactive before setting parameters such as position
972     // or loop points.  Otherwise, there could be a race condition: the application could read the
973     // current position, compute a new position or loop parameters, and then set that position or
974     // loop parameters but it would do the "wrong" thing since the position has continued to advance
975     // in the mean time.  If we ever provide a sequencer in server, we could allow a way for the app
976     // to specify how it wants to handle such scenarios.
977     if (mState == STATE_ACTIVE) {
978         return INVALID_OPERATION;
979     }
980     // After setting the position, use full update period before notification.
981     mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
982     mStaticProxy->setBufferPosition(position);
983 
984     // Waking the AudioTrackThread is not needed as this cannot be called when active.
985     return NO_ERROR;
986 }
987 
getPosition(uint32_t * position)988 status_t AudioTrack::getPosition(uint32_t *position)
989 {
990     if (position == NULL) {
991         return BAD_VALUE;
992     }
993 
994     AutoMutex lock(mLock);
995     if (isOffloadedOrDirect_l()) {
996         uint32_t dspFrames = 0;
997 
998         if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
999             ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
1000             *position = mPausedPosition;
1001             return NO_ERROR;
1002         }
1003 
1004         if (mOutput != AUDIO_IO_HANDLE_NONE) {
1005             uint32_t halFrames; // actually unused
1006             (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1007             // FIXME: on getRenderPosition() error, we return OK with frame position 0.
1008         }
1009         // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1010         // due to hardware latency. We leave this behavior for now.
1011         *position = dspFrames;
1012     } else {
1013         if (mCblk->mFlags & CBLK_INVALID) {
1014             (void) restoreTrack_l("getPosition");
1015             // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1016             // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
1017         }
1018 
1019         // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
1020         *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
1021                 0 : updateAndGetPosition_l();
1022     }
1023     return NO_ERROR;
1024 }
1025 
getBufferPosition(uint32_t * position)1026 status_t AudioTrack::getBufferPosition(uint32_t *position)
1027 {
1028     if (mSharedBuffer == 0 || mIsTimed) {
1029         return INVALID_OPERATION;
1030     }
1031     if (position == NULL) {
1032         return BAD_VALUE;
1033     }
1034 
1035     AutoMutex lock(mLock);
1036     *position = mStaticProxy->getBufferPosition();
1037     return NO_ERROR;
1038 }
1039 
reload()1040 status_t AudioTrack::reload()
1041 {
1042     if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
1043         return INVALID_OPERATION;
1044     }
1045 
1046     AutoMutex lock(mLock);
1047     // See setPosition() regarding setting parameters such as loop points or position while active
1048     if (mState == STATE_ACTIVE) {
1049         return INVALID_OPERATION;
1050     }
1051     mNewPosition = mUpdatePeriod;
1052     (void) updateAndGetPosition_l();
1053     mPosition = 0;
1054     mPreviousTimestampValid = false;
1055 #if 0
1056     // The documentation is not clear on the behavior of reload() and the restoration
1057     // of loop count. Historically we have not restored loop count, start, end,
1058     // but it makes sense if one desires to repeat playing a particular sound.
1059     if (mLoopCount != 0) {
1060         mLoopCountNotified = mLoopCount;
1061         mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1062     }
1063 #endif
1064     mStaticProxy->setBufferPosition(0);
1065     return NO_ERROR;
1066 }
1067 
getOutput() const1068 audio_io_handle_t AudioTrack::getOutput() const
1069 {
1070     AutoMutex lock(mLock);
1071     return mOutput;
1072 }
1073 
setOutputDevice(audio_port_handle_t deviceId)1074 status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1075     AutoMutex lock(mLock);
1076     if (mSelectedDeviceId != deviceId) {
1077         mSelectedDeviceId = deviceId;
1078         android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
1079     }
1080     return NO_ERROR;
1081 }
1082 
getOutputDevice()1083 audio_port_handle_t AudioTrack::getOutputDevice() {
1084     AutoMutex lock(mLock);
1085     return mSelectedDeviceId;
1086 }
1087 
getRoutedDeviceId()1088 audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1089     AutoMutex lock(mLock);
1090     if (mOutput == AUDIO_IO_HANDLE_NONE) {
1091         return AUDIO_PORT_HANDLE_NONE;
1092     }
1093     return AudioSystem::getDeviceIdForIo(mOutput);
1094 }
1095 
attachAuxEffect(int effectId)1096 status_t AudioTrack::attachAuxEffect(int effectId)
1097 {
1098     AutoMutex lock(mLock);
1099     status_t status = mAudioTrack->attachAuxEffect(effectId);
1100     if (status == NO_ERROR) {
1101         mAuxEffectId = effectId;
1102     }
1103     return status;
1104 }
1105 
streamType() const1106 audio_stream_type_t AudioTrack::streamType() const
1107 {
1108     if (mStreamType == AUDIO_STREAM_DEFAULT) {
1109         return audio_attributes_to_stream_type(&mAttributes);
1110     }
1111     return mStreamType;
1112 }
1113 
1114 // -------------------------------------------------------------------------
1115 
1116 // must be called with mLock held
createTrack_l()1117 status_t AudioTrack::createTrack_l()
1118 {
1119     const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1120     if (audioFlinger == 0) {
1121         ALOGE("Could not get audioflinger");
1122         return NO_INIT;
1123     }
1124 
1125     if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
1126         AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
1127     }
1128     audio_io_handle_t output;
1129     audio_stream_type_t streamType = mStreamType;
1130     audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
1131 
1132     status_t status;
1133     status = AudioSystem::getOutputForAttr(attr, &output,
1134                                            (audio_session_t)mSessionId, &streamType, mClientUid,
1135                                            mSampleRate, mFormat, mChannelMask,
1136                                            mFlags, mSelectedDeviceId, mOffloadInfo);
1137 
1138     if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
1139         ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
1140               " channel mask %#x, flags %#x",
1141               mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
1142         return BAD_VALUE;
1143     }
1144     {
1145     // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1146     // we must release it ourselves if anything goes wrong.
1147 
1148     // Not all of these values are needed under all conditions, but it is easier to get them all
1149     status = AudioSystem::getLatency(output, &mAfLatency);
1150     if (status != NO_ERROR) {
1151         ALOGE("getLatency(%d) failed status %d", output, status);
1152         goto release;
1153     }
1154     ALOGV("createTrack_l() output %d afLatency %u", output, mAfLatency);
1155 
1156     status = AudioSystem::getFrameCount(output, &mAfFrameCount);
1157     if (status != NO_ERROR) {
1158         ALOGE("getFrameCount(output=%d) status %d", output, status);
1159         goto release;
1160     }
1161 
1162     status = AudioSystem::getSamplingRate(output, &mAfSampleRate);
1163     if (status != NO_ERROR) {
1164         ALOGE("getSamplingRate(output=%d) status %d", output, status);
1165         goto release;
1166     }
1167     if (mSampleRate == 0) {
1168         mSampleRate = mAfSampleRate;
1169         mOriginalSampleRate = mAfSampleRate;
1170     }
1171     // Client decides whether the track is TIMED (see below), but can only express a preference
1172     // for FAST.  Server will perform additional tests.
1173     if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
1174             // either of these use cases:
1175             // use case 1: shared buffer
1176             (mSharedBuffer != 0) ||
1177             // use case 2: callback transfer mode
1178             (mTransfer == TRANSFER_CALLBACK) ||
1179             // use case 3: obtain/release mode
1180             (mTransfer == TRANSFER_OBTAIN)) &&
1181             // matching sample rate
1182             (mSampleRate == mAfSampleRate))) {
1183         ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1184                 mTransfer, mSampleRate, mAfSampleRate);
1185         // once denied, do not request again if IAudioTrack is re-created
1186         mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1187     }
1188 
1189     // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
1190     //  n = 1   fast track with single buffering; nBuffering is ignored
1191     //  n = 2   fast track with double buffering
1192     //  n = 2   normal track, (including those with sample rate conversion)
1193     //  n >= 3  very high latency or very small notification interval (unused).
1194     const uint32_t nBuffering = 2;
1195 
1196     mNotificationFramesAct = mNotificationFramesReq;
1197 
1198     size_t frameCount = mReqFrameCount;
1199     if (!audio_is_linear_pcm(mFormat)) {
1200 
1201         if (mSharedBuffer != 0) {
1202             // Same comment as below about ignoring frameCount parameter for set()
1203             frameCount = mSharedBuffer->size();
1204         } else if (frameCount == 0) {
1205             frameCount = mAfFrameCount;
1206         }
1207         if (mNotificationFramesAct != frameCount) {
1208             mNotificationFramesAct = frameCount;
1209         }
1210     } else if (mSharedBuffer != 0) {
1211         // FIXME: Ensure client side memory buffers need
1212         // not have additional alignment beyond sample
1213         // (e.g. 16 bit stereo accessed as 32 bit frame).
1214         size_t alignment = audio_bytes_per_sample(mFormat);
1215         if (alignment & 1) {
1216             // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1217             alignment = 1;
1218         }
1219         if (mChannelCount > 1) {
1220             // More than 2 channels does not require stronger alignment than stereo
1221             alignment <<= 1;
1222         }
1223         if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
1224             ALOGE("Invalid buffer alignment: address %p, channel count %u",
1225                     mSharedBuffer->pointer(), mChannelCount);
1226             status = BAD_VALUE;
1227             goto release;
1228         }
1229 
1230         // When initializing a shared buffer AudioTrack via constructors,
1231         // there's no frameCount parameter.
1232         // But when initializing a shared buffer AudioTrack via set(),
1233         // there _is_ a frameCount parameter.  We silently ignore it.
1234         frameCount = mSharedBuffer->size() / mFrameSize;
1235     } else {
1236         // For fast tracks the frame count calculations and checks are done by server
1237 
1238         if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1239             // for normal tracks precompute the frame count based on speed.
1240             const size_t minFrameCount = calculateMinFrameCount(
1241                     mAfLatency, mAfFrameCount, mAfSampleRate, mSampleRate,
1242                     mPlaybackRate.mSpeed);
1243             if (frameCount < minFrameCount) {
1244                 frameCount = minFrameCount;
1245             }
1246         }
1247     }
1248 
1249     IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1250     if (mIsTimed) {
1251         trackFlags |= IAudioFlinger::TRACK_TIMED;
1252     }
1253 
1254     pid_t tid = -1;
1255     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1256         trackFlags |= IAudioFlinger::TRACK_FAST;
1257         if (mAudioTrackThread != 0) {
1258             tid = mAudioTrackThread->getTid();
1259         }
1260     }
1261 
1262     if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1263         trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1264     }
1265 
1266     if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1267         trackFlags |= IAudioFlinger::TRACK_DIRECT;
1268     }
1269 
1270     size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
1271                                 // but we will still need the original value also
1272     int originalSessionId = mSessionId;
1273     sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
1274                                                       mSampleRate,
1275                                                       mFormat,
1276                                                       mChannelMask,
1277                                                       &temp,
1278                                                       &trackFlags,
1279                                                       mSharedBuffer,
1280                                                       output,
1281                                                       tid,
1282                                                       &mSessionId,
1283                                                       mClientUid,
1284                                                       &status);
1285     ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1286             "session ID changed from %d to %d", originalSessionId, mSessionId);
1287 
1288     if (status != NO_ERROR) {
1289         ALOGE("AudioFlinger could not create track, status: %d", status);
1290         goto release;
1291     }
1292     ALOG_ASSERT(track != 0);
1293 
1294     // AudioFlinger now owns the reference to the I/O handle,
1295     // so we are no longer responsible for releasing it.
1296 
1297     sp<IMemory> iMem = track->getCblk();
1298     if (iMem == 0) {
1299         ALOGE("Could not get control block");
1300         return NO_INIT;
1301     }
1302     void *iMemPointer = iMem->pointer();
1303     if (iMemPointer == NULL) {
1304         ALOGE("Could not get control block pointer");
1305         return NO_INIT;
1306     }
1307     // invariant that mAudioTrack != 0 is true only after set() returns successfully
1308     if (mAudioTrack != 0) {
1309         IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
1310         mDeathNotifier.clear();
1311     }
1312     mAudioTrack = track;
1313     mCblkMemory = iMem;
1314     IPCThreadState::self()->flushCommands();
1315 
1316     audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
1317     mCblk = cblk;
1318     // note that temp is the (possibly revised) value of frameCount
1319     if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1320         // In current design, AudioTrack client checks and ensures frame count validity before
1321         // passing it to AudioFlinger so AudioFlinger should not return a different value except
1322         // for fast track as it uses a special method of assigning frame count.
1323         ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
1324     }
1325     frameCount = temp;
1326 
1327     mAwaitBoost = false;
1328     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1329         if (trackFlags & IAudioFlinger::TRACK_FAST) {
1330             ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
1331             mAwaitBoost = true;
1332         } else {
1333             ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
1334             // once denied, do not request again if IAudioTrack is re-created
1335             mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1336         }
1337     }
1338     if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1339         if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1340             ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1341         } else {
1342             ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1343             mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1344             // FIXME This is a warning, not an error, so don't return error status
1345             //return NO_INIT;
1346         }
1347     }
1348     if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1349         if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1350             ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1351         } else {
1352             ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1353             mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1354             // FIXME This is a warning, not an error, so don't return error status
1355             //return NO_INIT;
1356         }
1357     }
1358     // Make sure that application is notified with sufficient margin before underrun
1359     if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1360         // Theoretically double-buffering is not required for fast tracks,
1361         // due to tighter scheduling.  But in practice, to accommodate kernels with
1362         // scheduling jitter, and apps with computation jitter, we use double-buffering
1363         // for fast tracks just like normal streaming tracks.
1364         if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1365             mNotificationFramesAct = frameCount / nBuffering;
1366         }
1367     }
1368 
1369     // We retain a copy of the I/O handle, but don't own the reference
1370     mOutput = output;
1371     mRefreshRemaining = true;
1372 
1373     // Starting address of buffers in shared memory.  If there is a shared buffer, buffers
1374     // is the value of pointer() for the shared buffer, otherwise buffers points
1375     // immediately after the control block.  This address is for the mapping within client
1376     // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
1377     void* buffers;
1378     if (mSharedBuffer == 0) {
1379         buffers = cblk + 1;
1380     } else {
1381         buffers = mSharedBuffer->pointer();
1382         if (buffers == NULL) {
1383             ALOGE("Could not get buffer pointer");
1384             return NO_INIT;
1385         }
1386     }
1387 
1388     mAudioTrack->attachAuxEffect(mAuxEffectId);
1389     // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
1390     // FIXME don't believe this lie
1391     mLatency = mAfLatency + (1000*frameCount) / mSampleRate;
1392 
1393     mFrameCount = frameCount;
1394     // If IAudioTrack is re-created, don't let the requested frameCount
1395     // decrease.  This can confuse clients that cache frameCount().
1396     if (frameCount > mReqFrameCount) {
1397         mReqFrameCount = frameCount;
1398     }
1399 
1400     // reset server position to 0 as we have new cblk.
1401     mServer = 0;
1402 
1403     // update proxy
1404     if (mSharedBuffer == 0) {
1405         mStaticProxy.clear();
1406         mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
1407     } else {
1408         mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
1409         mProxy = mStaticProxy;
1410     }
1411 
1412     mProxy->setVolumeLR(gain_minifloat_pack(
1413             gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1414             gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1415 
1416     mProxy->setSendLevel(mSendLevel);
1417     const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1418     const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1419     const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
1420     mProxy->setSampleRate(effectiveSampleRate);
1421 
1422     AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1423     playbackRateTemp.mSpeed = effectiveSpeed;
1424     playbackRateTemp.mPitch = effectivePitch;
1425     mProxy->setPlaybackRate(playbackRateTemp);
1426     mProxy->setMinimum(mNotificationFramesAct);
1427 
1428     mDeathNotifier = new DeathNotifier(this);
1429     IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
1430 
1431     if (mDeviceCallback != 0) {
1432         AudioSystem::addAudioDeviceCallback(mDeviceCallback, mOutput);
1433     }
1434 
1435     return NO_ERROR;
1436     }
1437 
1438 release:
1439     AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
1440     if (status == NO_ERROR) {
1441         status = NO_INIT;
1442     }
1443     return status;
1444 }
1445 
obtainBuffer(Buffer * audioBuffer,int32_t waitCount,size_t * nonContig)1446 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
1447 {
1448     if (audioBuffer == NULL) {
1449         if (nonContig != NULL) {
1450             *nonContig = 0;
1451         }
1452         return BAD_VALUE;
1453     }
1454     if (mTransfer != TRANSFER_OBTAIN) {
1455         audioBuffer->frameCount = 0;
1456         audioBuffer->size = 0;
1457         audioBuffer->raw = NULL;
1458         if (nonContig != NULL) {
1459             *nonContig = 0;
1460         }
1461         return INVALID_OPERATION;
1462     }
1463 
1464     const struct timespec *requested;
1465     struct timespec timeout;
1466     if (waitCount == -1) {
1467         requested = &ClientProxy::kForever;
1468     } else if (waitCount == 0) {
1469         requested = &ClientProxy::kNonBlocking;
1470     } else if (waitCount > 0) {
1471         long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1472         timeout.tv_sec = ms / 1000;
1473         timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1474         requested = &timeout;
1475     } else {
1476         ALOGE("%s invalid waitCount %d", __func__, waitCount);
1477         requested = NULL;
1478     }
1479     return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
1480 }
1481 
obtainBuffer(Buffer * audioBuffer,const struct timespec * requested,struct timespec * elapsed,size_t * nonContig)1482 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1483         struct timespec *elapsed, size_t *nonContig)
1484 {
1485     // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1486     uint32_t oldSequence = 0;
1487     uint32_t newSequence;
1488 
1489     Proxy::Buffer buffer;
1490     status_t status = NO_ERROR;
1491 
1492     static const int32_t kMaxTries = 5;
1493     int32_t tryCounter = kMaxTries;
1494 
1495     do {
1496         // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1497         // keep them from going away if another thread re-creates the track during obtainBuffer()
1498         sp<AudioTrackClientProxy> proxy;
1499         sp<IMemory> iMem;
1500 
1501         {   // start of lock scope
1502             AutoMutex lock(mLock);
1503 
1504             newSequence = mSequence;
1505             // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1506             if (status == DEAD_OBJECT) {
1507                 // re-create track, unless someone else has already done so
1508                 if (newSequence == oldSequence) {
1509                     status = restoreTrack_l("obtainBuffer");
1510                     if (status != NO_ERROR) {
1511                         buffer.mFrameCount = 0;
1512                         buffer.mRaw = NULL;
1513                         buffer.mNonContig = 0;
1514                         break;
1515                     }
1516                 }
1517             }
1518             oldSequence = newSequence;
1519 
1520             // Keep the extra references
1521             proxy = mProxy;
1522             iMem = mCblkMemory;
1523 
1524             if (mState == STATE_STOPPING) {
1525                 status = -EINTR;
1526                 buffer.mFrameCount = 0;
1527                 buffer.mRaw = NULL;
1528                 buffer.mNonContig = 0;
1529                 break;
1530             }
1531 
1532             // Non-blocking if track is stopped or paused
1533             if (mState != STATE_ACTIVE) {
1534                 requested = &ClientProxy::kNonBlocking;
1535             }
1536 
1537         }   // end of lock scope
1538 
1539         buffer.mFrameCount = audioBuffer->frameCount;
1540         // FIXME starts the requested timeout and elapsed over from scratch
1541         status = proxy->obtainBuffer(&buffer, requested, elapsed);
1542 
1543     } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1544 
1545     audioBuffer->frameCount = buffer.mFrameCount;
1546     audioBuffer->size = buffer.mFrameCount * mFrameSize;
1547     audioBuffer->raw = buffer.mRaw;
1548     if (nonContig != NULL) {
1549         *nonContig = buffer.mNonContig;
1550     }
1551     return status;
1552 }
1553 
releaseBuffer(const Buffer * audioBuffer)1554 void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
1555 {
1556     // FIXME add error checking on mode, by adding an internal version
1557     if (mTransfer == TRANSFER_SHARED) {
1558         return;
1559     }
1560 
1561     size_t stepCount = audioBuffer->size / mFrameSize;
1562     if (stepCount == 0) {
1563         return;
1564     }
1565 
1566     Proxy::Buffer buffer;
1567     buffer.mFrameCount = stepCount;
1568     buffer.mRaw = audioBuffer->raw;
1569 
1570     AutoMutex lock(mLock);
1571     mReleased += stepCount;
1572     mInUnderrun = false;
1573     mProxy->releaseBuffer(&buffer);
1574 
1575     // restart track if it was disabled by audioflinger due to previous underrun
1576     if (mState == STATE_ACTIVE) {
1577         audio_track_cblk_t* cblk = mCblk;
1578         if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
1579             ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
1580             // FIXME ignoring status
1581             mAudioTrack->start();
1582         }
1583     }
1584 }
1585 
1586 // -------------------------------------------------------------------------
1587 
write(const void * buffer,size_t userSize,bool blocking)1588 ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
1589 {
1590     if (mTransfer != TRANSFER_SYNC || mIsTimed) {
1591         return INVALID_OPERATION;
1592     }
1593 
1594     if (isDirect()) {
1595         AutoMutex lock(mLock);
1596         int32_t flags = android_atomic_and(
1597                             ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1598                             &mCblk->mFlags);
1599         if (flags & CBLK_INVALID) {
1600             return DEAD_OBJECT;
1601         }
1602     }
1603 
1604     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
1605         // Sanity-check: user is most-likely passing an error code, and it would
1606         // make the return value ambiguous (actualSize vs error).
1607         ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
1608         return BAD_VALUE;
1609     }
1610 
1611     size_t written = 0;
1612     Buffer audioBuffer;
1613 
1614     while (userSize >= mFrameSize) {
1615         audioBuffer.frameCount = userSize / mFrameSize;
1616 
1617         status_t err = obtainBuffer(&audioBuffer,
1618                 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
1619         if (err < 0) {
1620             if (written > 0) {
1621                 break;
1622             }
1623             return ssize_t(err);
1624         }
1625 
1626         size_t toWrite = audioBuffer.size;
1627         memcpy(audioBuffer.i8, buffer, toWrite);
1628         buffer = ((const char *) buffer) + toWrite;
1629         userSize -= toWrite;
1630         written += toWrite;
1631 
1632         releaseBuffer(&audioBuffer);
1633     }
1634 
1635     return written;
1636 }
1637 
1638 // -------------------------------------------------------------------------
1639 
TimedAudioTrack()1640 TimedAudioTrack::TimedAudioTrack() {
1641     mIsTimed = true;
1642 }
1643 
allocateTimedBuffer(size_t size,sp<IMemory> * buffer)1644 status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1645 {
1646     AutoMutex lock(mLock);
1647     status_t result = UNKNOWN_ERROR;
1648 
1649 #if 1
1650     // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1651     // while we are accessing the cblk
1652     sp<IAudioTrack> audioTrack = mAudioTrack;
1653     sp<IMemory> iMem = mCblkMemory;
1654 #endif
1655 
1656     // If the track is not invalid already, try to allocate a buffer.  alloc
1657     // fails indicating that the server is dead, flag the track as invalid so
1658     // we can attempt to restore in just a bit.
1659     audio_track_cblk_t* cblk = mCblk;
1660     if (!(cblk->mFlags & CBLK_INVALID)) {
1661         result = mAudioTrack->allocateTimedBuffer(size, buffer);
1662         if (result == DEAD_OBJECT) {
1663             android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1664         }
1665     }
1666 
1667     // If the track is invalid at this point, attempt to restore it. and try the
1668     // allocation one more time.
1669     if (cblk->mFlags & CBLK_INVALID) {
1670         result = restoreTrack_l("allocateTimedBuffer");
1671 
1672         if (result == NO_ERROR) {
1673             result = mAudioTrack->allocateTimedBuffer(size, buffer);
1674         }
1675     }
1676 
1677     return result;
1678 }
1679 
queueTimedBuffer(const sp<IMemory> & buffer,int64_t pts)1680 status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1681                                            int64_t pts)
1682 {
1683     status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1684     {
1685         AutoMutex lock(mLock);
1686         audio_track_cblk_t* cblk = mCblk;
1687         // restart track if it was disabled by audioflinger due to previous underrun
1688         if (buffer->size() != 0 && status == NO_ERROR &&
1689                 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1690             android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
1691             ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1692             // FIXME ignoring status
1693             mAudioTrack->start();
1694         }
1695     }
1696     return status;
1697 }
1698 
setMediaTimeTransform(const LinearTransform & xform,TargetTimeline target)1699 status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1700                                                 TargetTimeline target)
1701 {
1702     return mAudioTrack->setMediaTimeTransform(xform, target);
1703 }
1704 
1705 // -------------------------------------------------------------------------
1706 
processAudioBuffer()1707 nsecs_t AudioTrack::processAudioBuffer()
1708 {
1709     // Currently the AudioTrack thread is not created if there are no callbacks.
1710     // Would it ever make sense to run the thread, even without callbacks?
1711     // If so, then replace this by checks at each use for mCbf != NULL.
1712     LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1713 
1714     mLock.lock();
1715     if (mAwaitBoost) {
1716         mAwaitBoost = false;
1717         mLock.unlock();
1718         static const int32_t kMaxTries = 5;
1719         int32_t tryCounter = kMaxTries;
1720         uint32_t pollUs = 10000;
1721         do {
1722             int policy = sched_getscheduler(0);
1723             if (policy == SCHED_FIFO || policy == SCHED_RR) {
1724                 break;
1725             }
1726             usleep(pollUs);
1727             pollUs <<= 1;
1728         } while (tryCounter-- > 0);
1729         if (tryCounter < 0) {
1730             ALOGE("did not receive expected priority boost on time");
1731         }
1732         // Run again immediately
1733         return 0;
1734     }
1735 
1736     // Can only reference mCblk while locked
1737     int32_t flags = android_atomic_and(
1738         ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
1739 
1740     // Check for track invalidation
1741     if (flags & CBLK_INVALID) {
1742         // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1743         // AudioSystem cache. We should not exit here but after calling the callback so
1744         // that the upper layers can recreate the track
1745         if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
1746             status_t status __unused = restoreTrack_l("processAudioBuffer");
1747             // FIXME unused status
1748             // after restoration, continue below to make sure that the loop and buffer events
1749             // are notified because they have been cleared from mCblk->mFlags above.
1750         }
1751     }
1752 
1753     bool waitStreamEnd = mState == STATE_STOPPING;
1754     bool active = mState == STATE_ACTIVE;
1755 
1756     // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1757     bool newUnderrun = false;
1758     if (flags & CBLK_UNDERRUN) {
1759 #if 0
1760         // Currently in shared buffer mode, when the server reaches the end of buffer,
1761         // the track stays active in continuous underrun state.  It's up to the application
1762         // to pause or stop the track, or set the position to a new offset within buffer.
1763         // This was some experimental code to auto-pause on underrun.   Keeping it here
1764         // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1765         if (mTransfer == TRANSFER_SHARED) {
1766             mState = STATE_PAUSED;
1767             active = false;
1768         }
1769 #endif
1770         if (!mInUnderrun) {
1771             mInUnderrun = true;
1772             newUnderrun = true;
1773         }
1774     }
1775 
1776     // Get current position of server
1777     size_t position = updateAndGetPosition_l();
1778 
1779     // Manage marker callback
1780     bool markerReached = false;
1781     size_t markerPosition = mMarkerPosition;
1782     // FIXME fails for wraparound, need 64 bits
1783     if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1784         mMarkerReached = markerReached = true;
1785     }
1786 
1787     // Determine number of new position callback(s) that will be needed, while locked
1788     size_t newPosCount = 0;
1789     size_t newPosition = mNewPosition;
1790     size_t updatePeriod = mUpdatePeriod;
1791     // FIXME fails for wraparound, need 64 bits
1792     if (updatePeriod > 0 && position >= newPosition) {
1793         newPosCount = ((position - newPosition) / updatePeriod) + 1;
1794         mNewPosition += updatePeriod * newPosCount;
1795     }
1796 
1797     // Cache other fields that will be needed soon
1798     uint32_t sampleRate = mSampleRate;
1799     float speed = mPlaybackRate.mSpeed;
1800     const uint32_t notificationFrames = mNotificationFramesAct;
1801     if (mRefreshRemaining) {
1802         mRefreshRemaining = false;
1803         mRemainingFrames = notificationFrames;
1804         mRetryOnPartialBuffer = false;
1805     }
1806     size_t misalignment = mProxy->getMisalignment();
1807     uint32_t sequence = mSequence;
1808     sp<AudioTrackClientProxy> proxy = mProxy;
1809 
1810     // Determine the number of new loop callback(s) that will be needed, while locked.
1811     int loopCountNotifications = 0;
1812     uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1813 
1814     if (mLoopCount > 0) {
1815         int loopCount;
1816         size_t bufferPosition;
1817         mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1818         loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1819         loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1820         mLoopCountNotified = loopCount; // discard any excess notifications
1821     } else if (mLoopCount < 0) {
1822         // FIXME: We're not accurate with notification count and position with infinite looping
1823         // since loopCount from server side will always return -1 (we could decrement it).
1824         size_t bufferPosition = mStaticProxy->getBufferPosition();
1825         loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1826         loopPeriod = mLoopEnd - bufferPosition;
1827     } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1828         size_t bufferPosition = mStaticProxy->getBufferPosition();
1829         loopPeriod = mFrameCount - bufferPosition;
1830     }
1831 
1832     // These fields don't need to be cached, because they are assigned only by set():
1833     //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
1834     // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1835 
1836     mLock.unlock();
1837 
1838     // get anchor time to account for callbacks.
1839     const nsecs_t timeBeforeCallbacks = systemTime();
1840 
1841     if (waitStreamEnd) {
1842         // FIXME:  Instead of blocking in proxy->waitStreamEndDone(), Callback thread
1843         // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
1844         // (and make sure we don't callback for more data while we're stopping).
1845         // This helps with position, marker notifications, and track invalidation.
1846         struct timespec timeout;
1847         timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1848         timeout.tv_nsec = 0;
1849 
1850         status_t status = proxy->waitStreamEndDone(&timeout);
1851         switch (status) {
1852         case NO_ERROR:
1853         case DEAD_OBJECT:
1854         case TIMED_OUT:
1855             if (status != DEAD_OBJECT) {
1856                 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
1857                 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
1858                 mCbf(EVENT_STREAM_END, mUserData, NULL);
1859             }
1860             {
1861                 AutoMutex lock(mLock);
1862                 // The previously assigned value of waitStreamEnd is no longer valid,
1863                 // since the mutex has been unlocked and either the callback handler
1864                 // or another thread could have re-started the AudioTrack during that time.
1865                 waitStreamEnd = mState == STATE_STOPPING;
1866                 if (waitStreamEnd) {
1867                     mState = STATE_STOPPED;
1868                     mReleased = 0;
1869                 }
1870             }
1871             if (waitStreamEnd && status != DEAD_OBJECT) {
1872                return NS_INACTIVE;
1873             }
1874             break;
1875         }
1876         return 0;
1877     }
1878 
1879     // perform callbacks while unlocked
1880     if (newUnderrun) {
1881         mCbf(EVENT_UNDERRUN, mUserData, NULL);
1882     }
1883     while (loopCountNotifications > 0) {
1884         mCbf(EVENT_LOOP_END, mUserData, NULL);
1885         --loopCountNotifications;
1886     }
1887     if (flags & CBLK_BUFFER_END) {
1888         mCbf(EVENT_BUFFER_END, mUserData, NULL);
1889     }
1890     if (markerReached) {
1891         mCbf(EVENT_MARKER, mUserData, &markerPosition);
1892     }
1893     while (newPosCount > 0) {
1894         size_t temp = newPosition;
1895         mCbf(EVENT_NEW_POS, mUserData, &temp);
1896         newPosition += updatePeriod;
1897         newPosCount--;
1898     }
1899 
1900     if (mObservedSequence != sequence) {
1901         mObservedSequence = sequence;
1902         mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
1903         // for offloaded tracks, just wait for the upper layers to recreate the track
1904         if (isOffloadedOrDirect()) {
1905             return NS_INACTIVE;
1906         }
1907     }
1908 
1909     // if inactive, then don't run me again until re-started
1910     if (!active) {
1911         return NS_INACTIVE;
1912     }
1913 
1914     // Compute the estimated time until the next timed event (position, markers, loops)
1915     // FIXME only for non-compressed audio
1916     uint32_t minFrames = ~0;
1917     if (!markerReached && position < markerPosition) {
1918         minFrames = markerPosition - position;
1919     }
1920     if (loopPeriod > 0 && loopPeriod < minFrames) {
1921         // loopPeriod is already adjusted for actual position.
1922         minFrames = loopPeriod;
1923     }
1924     if (updatePeriod > 0) {
1925         minFrames = min(minFrames, uint32_t(newPosition - position));
1926     }
1927 
1928     // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1929     static const uint32_t kPoll = 0;
1930     if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1931         minFrames = kPoll * notificationFrames;
1932     }
1933 
1934     // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1935     static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
1936     const nsecs_t timeAfterCallbacks = systemTime();
1937 
1938     // Convert frame units to time units
1939     nsecs_t ns = NS_WHENEVER;
1940     if (minFrames != (uint32_t) ~0) {
1941         ns = framesToNanoseconds(minFrames, sampleRate, speed) + kWaitPeriodNs;
1942         ns -= (timeAfterCallbacks - timeBeforeCallbacks);  // account for callback time
1943         // TODO: Should we warn if the callback time is too long?
1944         if (ns < 0) ns = 0;
1945     }
1946 
1947     // If not supplying data by EVENT_MORE_DATA, then we're done
1948     if (mTransfer != TRANSFER_CALLBACK) {
1949         return ns;
1950     }
1951 
1952     // EVENT_MORE_DATA callback handling.
1953     // Timing for linear pcm audio data formats can be derived directly from the
1954     // buffer fill level.
1955     // Timing for compressed data is not directly available from the buffer fill level,
1956     // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
1957     // to return a certain fill level.
1958 
1959     struct timespec timeout;
1960     const struct timespec *requested = &ClientProxy::kForever;
1961     if (ns != NS_WHENEVER) {
1962         timeout.tv_sec = ns / 1000000000LL;
1963         timeout.tv_nsec = ns % 1000000000LL;
1964         ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1965         requested = &timeout;
1966     }
1967 
1968     while (mRemainingFrames > 0) {
1969 
1970         Buffer audioBuffer;
1971         audioBuffer.frameCount = mRemainingFrames;
1972         size_t nonContig;
1973         status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1974         LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1975                 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
1976         requested = &ClientProxy::kNonBlocking;
1977         size_t avail = audioBuffer.frameCount + nonContig;
1978         ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1979                 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1980         if (err != NO_ERROR) {
1981             if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1982                     (isOffloaded() && (err == DEAD_OBJECT))) {
1983                 // FIXME bug 25195759
1984                 return 1000000;
1985             }
1986             ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1987             return NS_NEVER;
1988         }
1989 
1990         if (mRetryOnPartialBuffer && audio_is_linear_pcm(mFormat)) {
1991             mRetryOnPartialBuffer = false;
1992             if (avail < mRemainingFrames) {
1993                 if (ns > 0) { // account for obtain time
1994                     const nsecs_t timeNow = systemTime();
1995                     ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
1996                 }
1997                 nsecs_t myns = framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
1998                 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
1999                     ns = myns;
2000                 }
2001                 return ns;
2002             }
2003         }
2004 
2005         size_t reqSize = audioBuffer.size;
2006         mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
2007         size_t writtenSize = audioBuffer.size;
2008 
2009         // Sanity check on returned size
2010         if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
2011             ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
2012                     reqSize, ssize_t(writtenSize));
2013             return NS_NEVER;
2014         }
2015 
2016         if (writtenSize == 0) {
2017             // The callback is done filling buffers
2018             // Keep this thread going to handle timed events and
2019             // still try to get more data in intervals of WAIT_PERIOD_MS
2020             // but don't just loop and block the CPU, so wait
2021 
2022             // mCbf(EVENT_MORE_DATA, ...) might either
2023             // (1) Block until it can fill the buffer, returning 0 size on EOS.
2024             // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2025             // (3) Return 0 size when no data is available, does not wait for more data.
2026             //
2027             // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2028             // We try to compute the wait time to avoid a tight sleep-wait cycle,
2029             // especially for case (3).
2030             //
2031             // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2032             // and this loop; whereas for case (3) we could simply check once with the full
2033             // buffer size and skip the loop entirely.
2034 
2035             nsecs_t myns;
2036             if (audio_is_linear_pcm(mFormat)) {
2037                 // time to wait based on buffer occupancy
2038                 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2039                         framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2040                 // audio flinger thread buffer size (TODO: adjust for fast tracks)
2041                 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2042                 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2043                 myns = datans + (afns / 2);
2044             } else {
2045                 // FIXME: This could ping quite a bit if the buffer isn't full.
2046                 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2047                 myns = kWaitPeriodNs;
2048             }
2049             if (ns > 0) { // account for obtain and callback time
2050                 const nsecs_t timeNow = systemTime();
2051                 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2052             }
2053             if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2054                 ns = myns;
2055             }
2056             return ns;
2057         }
2058 
2059         size_t releasedFrames = writtenSize / mFrameSize;
2060         audioBuffer.frameCount = releasedFrames;
2061         mRemainingFrames -= releasedFrames;
2062         if (misalignment >= releasedFrames) {
2063             misalignment -= releasedFrames;
2064         } else {
2065             misalignment = 0;
2066         }
2067 
2068         releaseBuffer(&audioBuffer);
2069 
2070         // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2071         // if callback doesn't like to accept the full chunk
2072         if (writtenSize < reqSize) {
2073             continue;
2074         }
2075 
2076         // There could be enough non-contiguous frames available to satisfy the remaining request
2077         if (mRemainingFrames <= nonContig) {
2078             continue;
2079         }
2080 
2081 #if 0
2082         // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2083         // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
2084         // that total to a sum == notificationFrames.
2085         if (0 < misalignment && misalignment <= mRemainingFrames) {
2086             mRemainingFrames = misalignment;
2087             return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
2088         }
2089 #endif
2090 
2091     }
2092     mRemainingFrames = notificationFrames;
2093     mRetryOnPartialBuffer = true;
2094 
2095     // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2096     return 0;
2097 }
2098 
restoreTrack_l(const char * from)2099 status_t AudioTrack::restoreTrack_l(const char *from)
2100 {
2101     ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
2102           isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
2103     ++mSequence;
2104 
2105     // refresh the audio configuration cache in this process to make sure we get new
2106     // output parameters and new IAudioFlinger in createTrack_l()
2107     AudioSystem::clearAudioConfigCache();
2108 
2109     if (isOffloadedOrDirect_l() || mDoNotReconnect) {
2110         // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2111         // reconsider enabling for linear PCM encodings when position can be preserved.
2112         return DEAD_OBJECT;
2113     }
2114 
2115     // save the old static buffer position
2116     size_t bufferPosition = 0;
2117     int loopCount = 0;
2118     if (mStaticProxy != 0) {
2119         mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2120     }
2121 
2122     // If a new IAudioTrack is successfully created, createTrack_l() will modify the
2123     // following member variables: mAudioTrack, mCblkMemory and mCblk.
2124     // It will also delete the strong references on previous IAudioTrack and IMemory.
2125     // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
2126     status_t result = createTrack_l();
2127 
2128     if (result == NO_ERROR) {
2129         // take the frames that will be lost by track recreation into account in saved position
2130         // For streaming tracks, this is the amount we obtained from the user/client
2131         // (not the number actually consumed at the server - those are already lost).
2132         if (mStaticProxy == 0) {
2133             mPosition = mReleased;
2134         }
2135         // Continue playback from last known position and restore loop.
2136         if (mStaticProxy != 0) {
2137             if (loopCount != 0) {
2138                 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2139                         mLoopStart, mLoopEnd, loopCount);
2140             } else {
2141                 mStaticProxy->setBufferPosition(bufferPosition);
2142                 if (bufferPosition == mFrameCount) {
2143                     ALOGD("restoring track at end of static buffer");
2144                 }
2145             }
2146         }
2147         if (mState == STATE_ACTIVE) {
2148             result = mAudioTrack->start();
2149         }
2150     }
2151     if (result != NO_ERROR) {
2152         ALOGW("restoreTrack_l() failed status %d", result);
2153         mState = STATE_STOPPED;
2154         mReleased = 0;
2155     }
2156 
2157     return result;
2158 }
2159 
updateAndGetPosition_l()2160 uint32_t AudioTrack::updateAndGetPosition_l()
2161 {
2162     // This is the sole place to read server consumed frames
2163     uint32_t newServer = mProxy->getPosition();
2164     int32_t delta = newServer - mServer;
2165     mServer = newServer;
2166     // TODO There is controversy about whether there can be "negative jitter" in server position.
2167     //      This should be investigated further, and if possible, it should be addressed.
2168     //      A more definite failure mode is infrequent polling by client.
2169     //      One could call (void)getPosition_l() in releaseBuffer(),
2170     //      so mReleased and mPosition are always lock-step as best possible.
2171     //      That should ensure delta never goes negative for infrequent polling
2172     //      unless the server has more than 2^31 frames in its buffer,
2173     //      in which case the use of uint32_t for these counters has bigger issues.
2174     if (delta < 0) {
2175         ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2176         delta = 0;
2177     }
2178     return mPosition += (uint32_t) delta;
2179 }
2180 
isSampleRateSpeedAllowed_l(uint32_t sampleRate,float speed) const2181 bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2182 {
2183     // applicable for mixing tracks only (not offloaded or direct)
2184     if (mStaticProxy != 0) {
2185         return true; // static tracks do not have issues with buffer sizing.
2186     }
2187     const size_t minFrameCount =
2188             calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed);
2189     ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu  minFrameCount %zu",
2190             mFrameCount, minFrameCount);
2191     return mFrameCount >= minFrameCount;
2192 }
2193 
setParameters(const String8 & keyValuePairs)2194 status_t AudioTrack::setParameters(const String8& keyValuePairs)
2195 {
2196     AutoMutex lock(mLock);
2197     return mAudioTrack->setParameters(keyValuePairs);
2198 }
2199 
getTimestamp(AudioTimestamp & timestamp)2200 status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2201 {
2202     AutoMutex lock(mLock);
2203 
2204     bool previousTimestampValid = mPreviousTimestampValid;
2205     // Set false here to cover all the error return cases.
2206     mPreviousTimestampValid = false;
2207 
2208     // FIXME not implemented for fast tracks; should use proxy and SSQ
2209     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2210         return INVALID_OPERATION;
2211     }
2212 
2213     switch (mState) {
2214     case STATE_ACTIVE:
2215     case STATE_PAUSED:
2216         break; // handle below
2217     case STATE_FLUSHED:
2218     case STATE_STOPPED:
2219         return WOULD_BLOCK;
2220     case STATE_STOPPING:
2221     case STATE_PAUSED_STOPPING:
2222         if (!isOffloaded_l()) {
2223             return INVALID_OPERATION;
2224         }
2225         break; // offloaded tracks handled below
2226     default:
2227         LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2228         break;
2229     }
2230 
2231     if (mCblk->mFlags & CBLK_INVALID) {
2232         const status_t status = restoreTrack_l("getTimestamp");
2233         if (status != OK) {
2234             // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2235             // recommending that the track be recreated.
2236             return DEAD_OBJECT;
2237         }
2238     }
2239 
2240     // The presented frame count must always lag behind the consumed frame count.
2241     // To avoid a race, read the presented frames first.  This ensures that presented <= consumed.
2242     status_t status = mAudioTrack->getTimestamp(timestamp);
2243     if (status != NO_ERROR) {
2244         ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
2245         return status;
2246     }
2247     if (isOffloadedOrDirect_l()) {
2248         if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2249             // use cached paused position in case another offloaded track is running.
2250             timestamp.mPosition = mPausedPosition;
2251             clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2252             return NO_ERROR;
2253         }
2254 
2255         // Check whether a pending flush or stop has completed, as those commands may
2256         // be asynchronous or return near finish or exhibit glitchy behavior.
2257         //
2258         // Originally this showed up as the first timestamp being a continuation of
2259         // the previous song under gapless playback.
2260         // However, we sometimes see zero timestamps, then a glitch of
2261         // the previous song's position, and then correct timestamps afterwards.
2262         if (mStartUs != 0 && mSampleRate != 0) {
2263             static const int kTimeJitterUs = 100000; // 100 ms
2264             static const int k1SecUs = 1000000;
2265 
2266             const int64_t timeNow = getNowUs();
2267 
2268             if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2269                 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2270                 if (timestampTimeUs < mStartUs) {
2271                     return WOULD_BLOCK;  // stale timestamp time, occurs before start.
2272                 }
2273                 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
2274                 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
2275                         / ((double)mSampleRate * mPlaybackRate.mSpeed);
2276 
2277                 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2278                     // Verify that the counter can't count faster than the sample rate
2279                     // since the start time.  If greater, then that means we may have failed
2280                     // to completely flush or stop the previous playing track.
2281                     ALOGW_IF(!mTimestampStartupGlitchReported,
2282                             "getTimestamp startup glitch detected"
2283                             " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2284                             (long long)deltaTimeUs, (long long)deltaPositionByUs,
2285                             timestamp.mPosition);
2286                     mTimestampStartupGlitchReported = true;
2287                     if (previousTimestampValid
2288                             && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2289                         timestamp = mPreviousTimestamp;
2290                         mPreviousTimestampValid = true;
2291                         return NO_ERROR;
2292                     }
2293                     return WOULD_BLOCK;
2294                 }
2295                 if (deltaPositionByUs != 0) {
2296                     mStartUs = 0; // don't check again, we got valid nonzero position.
2297                 }
2298             } else {
2299                 mStartUs = 0; // don't check again, start time expired.
2300             }
2301             mTimestampStartupGlitchReported = false;
2302         }
2303     } else {
2304         // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2305         (void) updateAndGetPosition_l();
2306         // Server consumed (mServer) and presented both use the same server time base,
2307         // and server consumed is always >= presented.
2308         // The delta between these represents the number of frames in the buffer pipeline.
2309         // If this delta between these is greater than the client position, it means that
2310         // actually presented is still stuck at the starting line (figuratively speaking),
2311         // waiting for the first frame to go by.  So we can't report a valid timestamp yet.
2312         if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2313             return INVALID_OPERATION;
2314         }
2315         // Convert timestamp position from server time base to client time base.
2316         // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2317         // But if we change it to 64-bit then this could fail.
2318         // If (mPosition - mServer) can be negative then should use:
2319         //   (int32_t)(mPosition - mServer)
2320         timestamp.mPosition += mPosition - mServer;
2321         // Immediately after a call to getPosition_l(), mPosition and
2322         // mServer both represent the same frame position.  mPosition is
2323         // in client's point of view, and mServer is in server's point of
2324         // view.  So the difference between them is the "fudge factor"
2325         // between client and server views due to stop() and/or new
2326         // IAudioTrack.  And timestamp.mPosition is initially in server's
2327         // point of view, so we need to apply the same fudge factor to it.
2328     }
2329 
2330     // Prevent retrograde motion in timestamp.
2331     // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2332     if (status == NO_ERROR) {
2333         if (previousTimestampValid) {
2334 #define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * 1000000000 + time.tv_nsec)
2335             const uint64_t previousTimeNanos = TIME_TO_NANOS(mPreviousTimestamp.mTime);
2336             const uint64_t currentTimeNanos = TIME_TO_NANOS(timestamp.mTime);
2337 #undef TIME_TO_NANOS
2338             if (currentTimeNanos < previousTimeNanos) {
2339                 ALOGW("retrograde timestamp time");
2340                 // FIXME Consider blocking this from propagating upwards.
2341             }
2342 
2343             // Looking at signed delta will work even when the timestamps
2344             // are wrapping around.
2345             int32_t deltaPosition = static_cast<int32_t>(timestamp.mPosition
2346                     - mPreviousTimestamp.mPosition);
2347             // position can bobble slightly as an artifact; this hides the bobble
2348             static const int32_t MINIMUM_POSITION_DELTA = 8;
2349             if (deltaPosition < 0) {
2350                 // Only report once per position instead of spamming the log.
2351                 if (!mRetrogradeMotionReported) {
2352                     ALOGW("retrograde timestamp position corrected, %d = %u - %u",
2353                             deltaPosition,
2354                             timestamp.mPosition,
2355                             mPreviousTimestamp.mPosition);
2356                     mRetrogradeMotionReported = true;
2357                 }
2358             } else {
2359                 mRetrogradeMotionReported = false;
2360             }
2361             if (deltaPosition < MINIMUM_POSITION_DELTA) {
2362                 timestamp = mPreviousTimestamp;  // Use last valid timestamp.
2363             }
2364         }
2365         mPreviousTimestamp = timestamp;
2366         mPreviousTimestampValid = true;
2367     }
2368 
2369     return status;
2370 }
2371 
getParameters(const String8 & keys)2372 String8 AudioTrack::getParameters(const String8& keys)
2373 {
2374     audio_io_handle_t output = getOutput();
2375     if (output != AUDIO_IO_HANDLE_NONE) {
2376         return AudioSystem::getParameters(output, keys);
2377     } else {
2378         return String8::empty();
2379     }
2380 }
2381 
isOffloaded() const2382 bool AudioTrack::isOffloaded() const
2383 {
2384     AutoMutex lock(mLock);
2385     return isOffloaded_l();
2386 }
2387 
isDirect() const2388 bool AudioTrack::isDirect() const
2389 {
2390     AutoMutex lock(mLock);
2391     return isDirect_l();
2392 }
2393 
isOffloadedOrDirect() const2394 bool AudioTrack::isOffloadedOrDirect() const
2395 {
2396     AutoMutex lock(mLock);
2397     return isOffloadedOrDirect_l();
2398 }
2399 
2400 
dump(int fd,const Vector<String16> & args __unused) const2401 status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
2402 {
2403 
2404     const size_t SIZE = 256;
2405     char buffer[SIZE];
2406     String8 result;
2407 
2408     result.append(" AudioTrack::dump\n");
2409     snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
2410             mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
2411     result.append(buffer);
2412     snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
2413             mChannelCount, mFrameCount);
2414     result.append(buffer);
2415     snprintf(buffer, 255, "  sample rate(%u), speed(%f), status(%d)\n",
2416             mSampleRate, mPlaybackRate.mSpeed, mStatus);
2417     result.append(buffer);
2418     snprintf(buffer, 255, "  state(%d), latency (%d)\n", mState, mLatency);
2419     result.append(buffer);
2420     ::write(fd, result.string(), result.size());
2421     return NO_ERROR;
2422 }
2423 
getUnderrunFrames() const2424 uint32_t AudioTrack::getUnderrunFrames() const
2425 {
2426     AutoMutex lock(mLock);
2427     return mProxy->getUnderrunFrames();
2428 }
2429 
addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)2430 status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2431 {
2432     if (callback == 0) {
2433         ALOGW("%s adding NULL callback!", __FUNCTION__);
2434         return BAD_VALUE;
2435     }
2436     AutoMutex lock(mLock);
2437     if (mDeviceCallback == callback) {
2438         ALOGW("%s adding same callback!", __FUNCTION__);
2439         return INVALID_OPERATION;
2440     }
2441     status_t status = NO_ERROR;
2442     if (mOutput != AUDIO_IO_HANDLE_NONE) {
2443         if (mDeviceCallback != 0) {
2444             ALOGW("%s callback already present!", __FUNCTION__);
2445             AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2446         }
2447         status = AudioSystem::addAudioDeviceCallback(callback, mOutput);
2448     }
2449     mDeviceCallback = callback;
2450     return status;
2451 }
2452 
removeAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)2453 status_t AudioTrack::removeAudioDeviceCallback(
2454         const sp<AudioSystem::AudioDeviceCallback>& callback)
2455 {
2456     if (callback == 0) {
2457         ALOGW("%s removing NULL callback!", __FUNCTION__);
2458         return BAD_VALUE;
2459     }
2460     AutoMutex lock(mLock);
2461     if (mDeviceCallback != callback) {
2462         ALOGW("%s removing different callback!", __FUNCTION__);
2463         return INVALID_OPERATION;
2464     }
2465     if (mOutput != AUDIO_IO_HANDLE_NONE) {
2466         AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2467     }
2468     mDeviceCallback = 0;
2469     return NO_ERROR;
2470 }
2471 
2472 // =========================================================================
2473 
binderDied(const wp<IBinder> & who __unused)2474 void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
2475 {
2476     sp<AudioTrack> audioTrack = mAudioTrack.promote();
2477     if (audioTrack != 0) {
2478         AutoMutex lock(audioTrack->mLock);
2479         audioTrack->mProxy->binderDied();
2480     }
2481 }
2482 
2483 // =========================================================================
2484 
AudioTrackThread(AudioTrack & receiver,bool bCanCallJava)2485 AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
2486     : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2487       mIgnoreNextPausedInt(false)
2488 {
2489 }
2490 
~AudioTrackThread()2491 AudioTrack::AudioTrackThread::~AudioTrackThread()
2492 {
2493 }
2494 
threadLoop()2495 bool AudioTrack::AudioTrackThread::threadLoop()
2496 {
2497     {
2498         AutoMutex _l(mMyLock);
2499         if (mPaused) {
2500             mMyCond.wait(mMyLock);
2501             // caller will check for exitPending()
2502             return true;
2503         }
2504         if (mIgnoreNextPausedInt) {
2505             mIgnoreNextPausedInt = false;
2506             mPausedInt = false;
2507         }
2508         if (mPausedInt) {
2509             if (mPausedNs > 0) {
2510                 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2511             } else {
2512                 mMyCond.wait(mMyLock);
2513             }
2514             mPausedInt = false;
2515             return true;
2516         }
2517     }
2518     if (exitPending()) {
2519         return false;
2520     }
2521     nsecs_t ns = mReceiver.processAudioBuffer();
2522     switch (ns) {
2523     case 0:
2524         return true;
2525     case NS_INACTIVE:
2526         pauseInternal();
2527         return true;
2528     case NS_NEVER:
2529         return false;
2530     case NS_WHENEVER:
2531         // Event driven: call wake() when callback notifications conditions change.
2532         ns = INT64_MAX;
2533         // fall through
2534     default:
2535         LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
2536         pauseInternal(ns);
2537         return true;
2538     }
2539 }
2540 
requestExit()2541 void AudioTrack::AudioTrackThread::requestExit()
2542 {
2543     // must be in this order to avoid a race condition
2544     Thread::requestExit();
2545     resume();
2546 }
2547 
pause()2548 void AudioTrack::AudioTrackThread::pause()
2549 {
2550     AutoMutex _l(mMyLock);
2551     mPaused = true;
2552 }
2553 
resume()2554 void AudioTrack::AudioTrackThread::resume()
2555 {
2556     AutoMutex _l(mMyLock);
2557     mIgnoreNextPausedInt = true;
2558     if (mPaused || mPausedInt) {
2559         mPaused = false;
2560         mPausedInt = false;
2561         mMyCond.signal();
2562     }
2563 }
2564 
wake()2565 void AudioTrack::AudioTrackThread::wake()
2566 {
2567     AutoMutex _l(mMyLock);
2568     if (!mPaused) {
2569         // wake() might be called while servicing a callback - ignore the next
2570         // pause time and call processAudioBuffer.
2571         mIgnoreNextPausedInt = true;
2572         if (mPausedInt && mPausedNs > 0) {
2573             // audio track is active and internally paused with timeout.
2574             mPausedInt = false;
2575             mMyCond.signal();
2576         }
2577     }
2578 }
2579 
pauseInternal(nsecs_t ns)2580 void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2581 {
2582     AutoMutex _l(mMyLock);
2583     mPausedInt = true;
2584     mPausedNs = ns;
2585 }
2586 
2587 } // namespace android
2588