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