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