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