AudioTrack.cpp revision 18868c5db2f90309c6d11e5837822135e4a0c0fa
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 <stdint.h>
23#include <sys/types.h>
24#include <limits.h>
25
26#include <sched.h>
27#include <sys/resource.h>
28
29#include <private/media/AudioTrackShared.h>
30
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Log.h>
35#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
37#include <utils/Timers.h>
38#include <utils/Atomic.h>
39
40#include <cutils/bitops.h>
41#include <cutils/compiler.h>
42
43#include <system/audio.h>
44#include <system/audio_policy.h>
45
46#include <audio_utils/primitives.h>
47
48namespace android {
49// ---------------------------------------------------------------------------
50
51// static
52status_t AudioTrack::getMinFrameCount(
53        int* frameCount,
54        audio_stream_type_t streamType,
55        uint32_t sampleRate)
56{
57    int afSampleRate;
58    if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
59        return NO_INIT;
60    }
61    int afFrameCount;
62    if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
63        return NO_INIT;
64    }
65    uint32_t afLatency;
66    if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
67        return NO_INIT;
68    }
69
70    // Ensure that buffer depth covers at least audio hardware latency
71    uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
72    if (minBufCount < 2) minBufCount = 2;
73
74    *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
75              afFrameCount * minBufCount * sampleRate / afSampleRate;
76    return NO_ERROR;
77}
78
79// ---------------------------------------------------------------------------
80
81AudioTrack::AudioTrack()
82    : mStatus(NO_INIT),
83      mIsTimed(false),
84      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
85      mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
86{
87}
88
89AudioTrack::AudioTrack(
90        audio_stream_type_t streamType,
91        uint32_t sampleRate,
92        audio_format_t format,
93        int channelMask,
94        int frameCount,
95        audio_policy_output_flags_t flags,
96        callback_t cbf,
97        void* user,
98        int notificationFrames,
99        int sessionId)
100    : mStatus(NO_INIT),
101      mIsTimed(false),
102      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
103      mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
104{
105    mStatus = set(streamType, sampleRate, format, channelMask,
106            frameCount, flags, cbf, user, notificationFrames,
107            0, false, sessionId);
108}
109
110AudioTrack::AudioTrack(
111        int streamType,
112        uint32_t sampleRate,
113        int format,
114        int channelMask,
115        int frameCount,
116        uint32_t flags,
117        callback_t cbf,
118        void* user,
119        int notificationFrames,
120        int sessionId)
121    : mStatus(NO_INIT),
122      mIsTimed(false),
123      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
124{
125    mStatus = set((audio_stream_type_t)streamType, sampleRate, (audio_format_t)format, channelMask,
126            frameCount, (audio_policy_output_flags_t)flags, cbf, user, notificationFrames,
127            0, false, sessionId);
128}
129
130AudioTrack::AudioTrack(
131        audio_stream_type_t streamType,
132        uint32_t sampleRate,
133        audio_format_t format,
134        int channelMask,
135        const sp<IMemory>& sharedBuffer,
136        audio_policy_output_flags_t flags,
137        callback_t cbf,
138        void* user,
139        int notificationFrames,
140        int sessionId)
141    : mStatus(NO_INIT),
142      mIsTimed(false),
143      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
144      mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
145{
146    mStatus = set(streamType, sampleRate, format, channelMask,
147            0, flags, cbf, user, notificationFrames,
148            sharedBuffer, false, sessionId);
149}
150
151AudioTrack::~AudioTrack()
152{
153    ALOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
154
155    if (mStatus == NO_ERROR) {
156        // Make sure that callback function exits in the case where
157        // it is looping on buffer full condition in obtainBuffer().
158        // Otherwise the callback thread will never exit.
159        stop();
160        if (mAudioTrackThread != 0) {
161            mAudioTrackThread->requestExitAndWait();
162            mAudioTrackThread.clear();
163        }
164        mAudioTrack.clear();
165        IPCThreadState::self()->flushCommands();
166        AudioSystem::releaseAudioSessionId(mSessionId);
167    }
168}
169
170status_t AudioTrack::set(
171        audio_stream_type_t streamType,
172        uint32_t sampleRate,
173        audio_format_t format,
174        int channelMask,
175        int frameCount,
176        audio_policy_output_flags_t flags,
177        callback_t cbf,
178        void* user,
179        int notificationFrames,
180        const sp<IMemory>& sharedBuffer,
181        bool threadCanCallJava,
182        int sessionId)
183{
184
185    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
186
187    AutoMutex lock(mLock);
188    if (mAudioTrack != 0) {
189        ALOGE("Track already in use");
190        return INVALID_OPERATION;
191    }
192
193    int afSampleRate;
194    if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
195        return NO_INIT;
196    }
197    uint32_t afLatency;
198    if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
199        return NO_INIT;
200    }
201
202    // handle default values first.
203    if (streamType == AUDIO_STREAM_DEFAULT) {
204        streamType = AUDIO_STREAM_MUSIC;
205    }
206    if (sampleRate == 0) {
207        sampleRate = afSampleRate;
208    }
209    // these below should probably come from the audioFlinger too...
210    if (format == AUDIO_FORMAT_DEFAULT) {
211        format = AUDIO_FORMAT_PCM_16_BIT;
212    }
213    if (channelMask == 0) {
214        channelMask = AUDIO_CHANNEL_OUT_STEREO;
215    }
216
217    // validate parameters
218    if (!audio_is_valid_format(format)) {
219        ALOGE("Invalid format");
220        return BAD_VALUE;
221    }
222
223    // force direct flag if format is not linear PCM
224    if (!audio_is_linear_pcm(format)) {
225        flags = (audio_policy_output_flags_t) (flags | AUDIO_POLICY_OUTPUT_FLAG_DIRECT);
226    }
227
228    if (!audio_is_output_channel(channelMask)) {
229        ALOGE("Invalid channel mask");
230        return BAD_VALUE;
231    }
232    uint32_t channelCount = popcount(channelMask);
233
234    audio_io_handle_t output = AudioSystem::getOutput(
235                                    streamType,
236                                    sampleRate, format, channelMask,
237                                    flags);
238
239    if (output == 0) {
240        ALOGE("Could not get audio output for stream type %d", streamType);
241        return BAD_VALUE;
242    }
243
244    mVolume[LEFT] = 1.0f;
245    mVolume[RIGHT] = 1.0f;
246    mSendLevel = 0.0f;
247    mFrameCount = frameCount;
248    mNotificationFramesReq = notificationFrames;
249    mSessionId = sessionId;
250    mAuxEffectId = 0;
251
252    // create the IAudioTrack
253    status_t status = createTrack_l(streamType,
254                                  sampleRate,
255                                  format,
256                                  (uint32_t)channelMask,
257                                  frameCount,
258                                  flags,
259                                  sharedBuffer,
260                                  output,
261                                  true);
262
263    if (status != NO_ERROR) {
264        return status;
265    }
266
267    if (cbf != NULL) {
268        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
269    }
270
271    mStatus = NO_ERROR;
272
273    mStreamType = streamType;
274    mFormat = format;
275    mChannelMask = (uint32_t)channelMask;
276    mChannelCount = channelCount;
277    mSharedBuffer = sharedBuffer;
278    mMuted = false;
279    mActive = false;
280    mCbf = cbf;
281    mUserData = user;
282    mLoopCount = 0;
283    mMarkerPosition = 0;
284    mMarkerReached = false;
285    mNewPosition = 0;
286    mUpdatePeriod = 0;
287    mFlushed = false;
288    mFlags = flags;
289    AudioSystem::acquireAudioSessionId(mSessionId);
290    mRestoreStatus = NO_ERROR;
291    return NO_ERROR;
292}
293
294status_t AudioTrack::initCheck() const
295{
296    return mStatus;
297}
298
299// -------------------------------------------------------------------------
300
301uint32_t AudioTrack::latency() const
302{
303    return mLatency;
304}
305
306audio_stream_type_t AudioTrack::streamType() const
307{
308    return mStreamType;
309}
310
311audio_format_t AudioTrack::format() const
312{
313    return mFormat;
314}
315
316int AudioTrack::channelCount() const
317{
318    return mChannelCount;
319}
320
321uint32_t AudioTrack::frameCount() const
322{
323    return mCblk->frameCount;
324}
325
326size_t AudioTrack::frameSize() const
327{
328    if (audio_is_linear_pcm(mFormat)) {
329        return channelCount()*audio_bytes_per_sample(mFormat);
330    } else {
331        return sizeof(uint8_t);
332    }
333}
334
335sp<IMemory>& AudioTrack::sharedBuffer()
336{
337    return mSharedBuffer;
338}
339
340// -------------------------------------------------------------------------
341
342void AudioTrack::start()
343{
344    sp<AudioTrackThread> t = mAudioTrackThread;
345    status_t status = NO_ERROR;
346
347    ALOGV("start %p", this);
348    if (t != 0) {
349        if (t->exitPending()) {
350            if (t->requestExitAndWait() == WOULD_BLOCK) {
351                ALOGE("AudioTrack::start called from thread");
352                return;
353            }
354        }
355     }
356
357    AutoMutex lock(mLock);
358    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
359    // while we are accessing the cblk
360    sp <IAudioTrack> audioTrack = mAudioTrack;
361    sp <IMemory> iMem = mCblkMemory;
362    audio_track_cblk_t* cblk = mCblk;
363
364    if (!mActive) {
365        mFlushed = false;
366        mActive = true;
367        mNewPosition = cblk->server + mUpdatePeriod;
368        cblk->lock.lock();
369        cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
370        cblk->waitTimeMs = 0;
371        android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
372        pid_t tid;
373        if (t != 0) {
374            t->run("AudioTrack", ANDROID_PRIORITY_AUDIO);
375            tid = t->getTid();  // pid_t is unknown until run()
376            ALOGV("getTid=%d", tid);
377            if (tid == -1) {
378                tid = 0;
379            }
380        } else {
381            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
382            mPreviousSchedulingGroup = androidGetThreadSchedulingGroup(0);
383            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
384            tid = 0;    // not gettid()
385        }
386
387        ALOGV("start %p before lock cblk %p", this, mCblk);
388        if (!(cblk->flags & CBLK_INVALID_MSK)) {
389            cblk->lock.unlock();
390            ALOGV("mAudioTrack->start(tid=%d)", tid);
391            status = mAudioTrack->start(tid);
392            cblk->lock.lock();
393            if (status == DEAD_OBJECT) {
394                android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
395            }
396        }
397        if (cblk->flags & CBLK_INVALID_MSK) {
398            status = restoreTrack_l(cblk, true);
399        }
400        cblk->lock.unlock();
401        if (status != NO_ERROR) {
402            ALOGV("start() failed");
403            mActive = false;
404            if (t != 0) {
405                t->requestExit();
406            } else {
407                setpriority(PRIO_PROCESS, 0, mPreviousPriority);
408                androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
409            }
410        }
411    }
412
413}
414
415void AudioTrack::stop()
416{
417    sp<AudioTrackThread> t = mAudioTrackThread;
418
419    ALOGV("stop %p", this);
420
421    AutoMutex lock(mLock);
422    if (mActive) {
423        mActive = false;
424        mCblk->cv.signal();
425        mAudioTrack->stop();
426        // Cancel loops (If we are in the middle of a loop, playback
427        // would not stop until loopCount reaches 0).
428        setLoop_l(0, 0, 0);
429        // the playback head position will reset to 0, so if a marker is set, we need
430        // to activate it again
431        mMarkerReached = false;
432        // Force flush if a shared buffer is used otherwise audioflinger
433        // will not stop before end of buffer is reached.
434        if (mSharedBuffer != 0) {
435            flush_l();
436        }
437        if (t != 0) {
438            t->requestExit();
439        } else {
440            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
441            androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
442        }
443    }
444
445}
446
447bool AudioTrack::stopped() const
448{
449    AutoMutex lock(mLock);
450    return stopped_l();
451}
452
453void AudioTrack::flush()
454{
455    AutoMutex lock(mLock);
456    flush_l();
457}
458
459// must be called with mLock held
460void AudioTrack::flush_l()
461{
462    ALOGV("flush");
463
464    // clear playback marker and periodic update counter
465    mMarkerPosition = 0;
466    mMarkerReached = false;
467    mUpdatePeriod = 0;
468
469    if (!mActive) {
470        mFlushed = true;
471        mAudioTrack->flush();
472        // Release AudioTrack callback thread in case it was waiting for new buffers
473        // in AudioTrack::obtainBuffer()
474        mCblk->cv.signal();
475    }
476}
477
478void AudioTrack::pause()
479{
480    ALOGV("pause");
481    AutoMutex lock(mLock);
482    if (mActive) {
483        mActive = false;
484        mAudioTrack->pause();
485    }
486}
487
488void AudioTrack::mute(bool e)
489{
490    mAudioTrack->mute(e);
491    mMuted = e;
492}
493
494bool AudioTrack::muted() const
495{
496    return mMuted;
497}
498
499status_t AudioTrack::setVolume(float left, float right)
500{
501    if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
502        return BAD_VALUE;
503    }
504
505    AutoMutex lock(mLock);
506    mVolume[LEFT] = left;
507    mVolume[RIGHT] = right;
508
509    mCblk->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
510
511    return NO_ERROR;
512}
513
514void AudioTrack::getVolume(float* left, float* right) const
515{
516    if (left != NULL) {
517        *left  = mVolume[LEFT];
518    }
519    if (right != NULL) {
520        *right = mVolume[RIGHT];
521    }
522}
523
524status_t AudioTrack::setAuxEffectSendLevel(float level)
525{
526    ALOGV("setAuxEffectSendLevel(%f)", level);
527    if (level < 0.0f || level > 1.0f) {
528        return BAD_VALUE;
529    }
530    AutoMutex lock(mLock);
531
532    mSendLevel = level;
533
534    mCblk->setSendLevel(level);
535
536    return NO_ERROR;
537}
538
539void AudioTrack::getAuxEffectSendLevel(float* level) const
540{
541    if (level != NULL) {
542        *level  = mSendLevel;
543    }
544}
545
546status_t AudioTrack::setSampleRate(int rate)
547{
548    int afSamplingRate;
549
550    if (mIsTimed) {
551        return INVALID_OPERATION;
552    }
553
554    if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
555        return NO_INIT;
556    }
557    // Resampler implementation limits input sampling rate to 2 x output sampling rate.
558    if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
559
560    AutoMutex lock(mLock);
561    mCblk->sampleRate = rate;
562    return NO_ERROR;
563}
564
565uint32_t AudioTrack::getSampleRate() const
566{
567    if (mIsTimed) {
568        return INVALID_OPERATION;
569    }
570
571    AutoMutex lock(mLock);
572    return mCblk->sampleRate;
573}
574
575status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
576{
577    AutoMutex lock(mLock);
578    return setLoop_l(loopStart, loopEnd, loopCount);
579}
580
581// must be called with mLock held
582status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
583{
584    audio_track_cblk_t* cblk = mCblk;
585
586    Mutex::Autolock _l(cblk->lock);
587
588    if (loopCount == 0) {
589        cblk->loopStart = UINT_MAX;
590        cblk->loopEnd = UINT_MAX;
591        cblk->loopCount = 0;
592        mLoopCount = 0;
593        return NO_ERROR;
594    }
595
596    if (mIsTimed) {
597        return INVALID_OPERATION;
598    }
599
600    if (loopStart >= loopEnd ||
601        loopEnd - loopStart > cblk->frameCount ||
602        cblk->server > loopStart) {
603        ALOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, cblk->frameCount, cblk->user);
604        return BAD_VALUE;
605    }
606
607    if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
608        ALOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
609            loopStart, loopEnd, cblk->frameCount);
610        return BAD_VALUE;
611    }
612
613    cblk->loopStart = loopStart;
614    cblk->loopEnd = loopEnd;
615    cblk->loopCount = loopCount;
616    mLoopCount = loopCount;
617
618    return NO_ERROR;
619}
620
621status_t AudioTrack::setMarkerPosition(uint32_t marker)
622{
623    if (mCbf == NULL) return INVALID_OPERATION;
624
625    mMarkerPosition = marker;
626    mMarkerReached = false;
627
628    return NO_ERROR;
629}
630
631status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
632{
633    if (marker == NULL) return BAD_VALUE;
634
635    *marker = mMarkerPosition;
636
637    return NO_ERROR;
638}
639
640status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
641{
642    if (mCbf == NULL) return INVALID_OPERATION;
643
644    uint32_t curPosition;
645    getPosition(&curPosition);
646    mNewPosition = curPosition + updatePeriod;
647    mUpdatePeriod = updatePeriod;
648
649    return NO_ERROR;
650}
651
652status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
653{
654    if (updatePeriod == NULL) return BAD_VALUE;
655
656    *updatePeriod = mUpdatePeriod;
657
658    return NO_ERROR;
659}
660
661status_t AudioTrack::setPosition(uint32_t position)
662{
663    if (mIsTimed) return INVALID_OPERATION;
664
665    AutoMutex lock(mLock);
666
667    if (!stopped_l()) return INVALID_OPERATION;
668
669    Mutex::Autolock _l(mCblk->lock);
670
671    if (position > mCblk->user) return BAD_VALUE;
672
673    mCblk->server = position;
674    android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
675
676    return NO_ERROR;
677}
678
679status_t AudioTrack::getPosition(uint32_t *position)
680{
681    if (position == NULL) return BAD_VALUE;
682    AutoMutex lock(mLock);
683    *position = mFlushed ? 0 : mCblk->server;
684
685    return NO_ERROR;
686}
687
688status_t AudioTrack::reload()
689{
690    AutoMutex lock(mLock);
691
692    if (!stopped_l()) return INVALID_OPERATION;
693
694    flush_l();
695
696    mCblk->stepUser(mCblk->frameCount);
697
698    return NO_ERROR;
699}
700
701audio_io_handle_t AudioTrack::getOutput()
702{
703    AutoMutex lock(mLock);
704    return getOutput_l();
705}
706
707// must be called with mLock held
708audio_io_handle_t AudioTrack::getOutput_l()
709{
710    return AudioSystem::getOutput(mStreamType,
711            mCblk->sampleRate, mFormat, mChannelMask, mFlags);
712}
713
714int AudioTrack::getSessionId() const
715{
716    return mSessionId;
717}
718
719status_t AudioTrack::attachAuxEffect(int effectId)
720{
721    ALOGV("attachAuxEffect(%d)", effectId);
722    status_t status = mAudioTrack->attachAuxEffect(effectId);
723    if (status == NO_ERROR) {
724        mAuxEffectId = effectId;
725    }
726    return status;
727}
728
729// -------------------------------------------------------------------------
730
731// must be called with mLock held
732status_t AudioTrack::createTrack_l(
733        audio_stream_type_t streamType,
734        uint32_t sampleRate,
735        audio_format_t format,
736        uint32_t channelMask,
737        int frameCount,
738        audio_policy_output_flags_t flags,
739        const sp<IMemory>& sharedBuffer,
740        audio_io_handle_t output,
741        bool enforceFrameCount)
742{
743    status_t status;
744    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
745    if (audioFlinger == 0) {
746       ALOGE("Could not get audioflinger");
747       return NO_INIT;
748    }
749
750    int afSampleRate;
751    if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
752        return NO_INIT;
753    }
754    int afFrameCount;
755    if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
756        return NO_INIT;
757    }
758    uint32_t afLatency;
759    if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
760        return NO_INIT;
761    }
762
763    mNotificationFramesAct = mNotificationFramesReq;
764    if (!audio_is_linear_pcm(format)) {
765        if (sharedBuffer != 0) {
766            frameCount = sharedBuffer->size();
767        }
768    } else {
769        // Ensure that buffer depth covers at least audio hardware latency
770        uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
771        if (minBufCount < 2) minBufCount = 2;
772
773        int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
774
775        if (sharedBuffer == 0) {
776            if (frameCount == 0) {
777                frameCount = minFrameCount;
778            }
779            if (mNotificationFramesAct == 0) {
780                mNotificationFramesAct = frameCount/2;
781            }
782            // Make sure that application is notified with sufficient margin
783            // before underrun
784            if (mNotificationFramesAct > (uint32_t)frameCount/2) {
785                mNotificationFramesAct = frameCount/2;
786            }
787            if (frameCount < minFrameCount) {
788                ALOGW_IF(enforceFrameCount, "Minimum buffer size corrected from %d to %d",
789                         frameCount, minFrameCount);
790                frameCount = minFrameCount;
791            }
792        } else {
793            // Ensure that buffer alignment matches channelCount
794            int channelCount = popcount(channelMask);
795            if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
796                ALOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
797                return BAD_VALUE;
798            }
799            frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
800        }
801    }
802
803    sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
804                                                      streamType,
805                                                      sampleRate,
806                                                      format,
807                                                      channelMask,
808                                                      frameCount,
809                                                      ((uint16_t)flags) << 16,
810                                                      sharedBuffer,
811                                                      output,
812                                                      mIsTimed,
813                                                      &mSessionId,
814                                                      &status);
815
816    if (track == 0) {
817        ALOGE("AudioFlinger could not create track, status: %d", status);
818        return status;
819    }
820    sp<IMemory> cblk = track->getCblk();
821    if (cblk == 0) {
822        ALOGE("Could not get control block");
823        return NO_INIT;
824    }
825    mAudioTrack = track;
826    mCblkMemory = cblk;
827    mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
828    android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
829    if (sharedBuffer == 0) {
830        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
831    } else {
832        mCblk->buffers = sharedBuffer->pointer();
833         // Force buffer full condition as data is already present in shared memory
834        mCblk->stepUser(mCblk->frameCount);
835    }
836
837    mCblk->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000));
838    mCblk->setSendLevel(mSendLevel);
839    mAudioTrack->attachAuxEffect(mAuxEffectId);
840    mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
841    mCblk->waitTimeMs = 0;
842    mRemainingFrames = mNotificationFramesAct;
843    mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
844    return NO_ERROR;
845}
846
847status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
848{
849    AutoMutex lock(mLock);
850    bool active;
851    status_t result = NO_ERROR;
852    audio_track_cblk_t* cblk = mCblk;
853    uint32_t framesReq = audioBuffer->frameCount;
854    uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
855
856    audioBuffer->frameCount  = 0;
857    audioBuffer->size = 0;
858
859    uint32_t framesAvail = cblk->framesAvailable();
860
861    cblk->lock.lock();
862    if (cblk->flags & CBLK_INVALID_MSK) {
863        goto create_new_track;
864    }
865    cblk->lock.unlock();
866
867    if (framesAvail == 0) {
868        cblk->lock.lock();
869        goto start_loop_here;
870        while (framesAvail == 0) {
871            active = mActive;
872            if (CC_UNLIKELY(!active)) {
873                ALOGV("Not active and NO_MORE_BUFFERS");
874                cblk->lock.unlock();
875                return NO_MORE_BUFFERS;
876            }
877            if (CC_UNLIKELY(!waitCount)) {
878                cblk->lock.unlock();
879                return WOULD_BLOCK;
880            }
881            if (!(cblk->flags & CBLK_INVALID_MSK)) {
882                mLock.unlock();
883                result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
884                cblk->lock.unlock();
885                mLock.lock();
886                if (!mActive) {
887                    return status_t(STOPPED);
888                }
889                cblk->lock.lock();
890            }
891
892            if (cblk->flags & CBLK_INVALID_MSK) {
893                goto create_new_track;
894            }
895            if (CC_UNLIKELY(result != NO_ERROR)) {
896                cblk->waitTimeMs += waitTimeMs;
897                if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
898                    // timing out when a loop has been set and we have already written upto loop end
899                    // is a normal condition: no need to wake AudioFlinger up.
900                    if (cblk->user < cblk->loopEnd) {
901                        ALOGW(   "obtainBuffer timed out (is the CPU pegged?) %p "
902                                "user=%08x, server=%08x", this, cblk->user, cblk->server);
903                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
904                        cblk->lock.unlock();
905                        result = mAudioTrack->start(0); // callback thread hasn't changed
906                        cblk->lock.lock();
907                        if (result == DEAD_OBJECT) {
908                            android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
909create_new_track:
910                            result = restoreTrack_l(cblk, false);
911                        }
912                        if (result != NO_ERROR) {
913                            ALOGW("obtainBuffer create Track error %d", result);
914                            cblk->lock.unlock();
915                            return result;
916                        }
917                    }
918                    cblk->waitTimeMs = 0;
919                }
920
921                if (--waitCount == 0) {
922                    cblk->lock.unlock();
923                    return TIMED_OUT;
924                }
925            }
926            // read the server count again
927        start_loop_here:
928            framesAvail = cblk->framesAvailable_l();
929        }
930        cblk->lock.unlock();
931    }
932
933    // restart track if it was disabled by audioflinger due to previous underrun
934    if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
935        android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
936        ALOGW("obtainBuffer() track %p disabled, restarting", this);
937        mAudioTrack->start(0);  // callback thread hasn't changed
938    }
939
940    cblk->waitTimeMs = 0;
941
942    if (framesReq > framesAvail) {
943        framesReq = framesAvail;
944    }
945
946    uint32_t u = cblk->user;
947    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
948
949    if (u + framesReq > bufferEnd) {
950        framesReq = bufferEnd - u;
951    }
952
953    audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
954    audioBuffer->channelCount = mChannelCount;
955    audioBuffer->frameCount = framesReq;
956    audioBuffer->size = framesReq * cblk->frameSize;
957    if (audio_is_linear_pcm(mFormat)) {
958        audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
959    } else {
960        audioBuffer->format = mFormat;
961    }
962    audioBuffer->raw = (int8_t *)cblk->buffer(u);
963    active = mActive;
964    return active ? status_t(NO_ERROR) : status_t(STOPPED);
965}
966
967void AudioTrack::releaseBuffer(Buffer* audioBuffer)
968{
969    AutoMutex lock(mLock);
970    mCblk->stepUser(audioBuffer->frameCount);
971}
972
973// -------------------------------------------------------------------------
974
975ssize_t AudioTrack::write(const void* buffer, size_t userSize)
976{
977
978    if (mSharedBuffer != 0) return INVALID_OPERATION;
979    if (mIsTimed) return INVALID_OPERATION;
980
981    if (ssize_t(userSize) < 0) {
982        // Sanity-check: user is most-likely passing an error code, and it would
983        // make the return value ambiguous (actualSize vs error).
984        ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
985                buffer, userSize, userSize);
986        return BAD_VALUE;
987    }
988
989    ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
990
991    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
992    // while we are accessing the cblk
993    mLock.lock();
994    sp <IAudioTrack> audioTrack = mAudioTrack;
995    sp <IMemory> iMem = mCblkMemory;
996    mLock.unlock();
997
998    ssize_t written = 0;
999    const int8_t *src = (const int8_t *)buffer;
1000    Buffer audioBuffer;
1001    size_t frameSz = frameSize();
1002
1003    do {
1004        audioBuffer.frameCount = userSize/frameSz;
1005
1006        status_t err = obtainBuffer(&audioBuffer, -1);
1007        if (err < 0) {
1008            // out of buffers, return #bytes written
1009            if (err == status_t(NO_MORE_BUFFERS))
1010                break;
1011            return ssize_t(err);
1012        }
1013
1014        size_t toWrite;
1015
1016        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
1017            // Divide capacity by 2 to take expansion into account
1018            toWrite = audioBuffer.size>>1;
1019            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite);
1020        } else {
1021            toWrite = audioBuffer.size;
1022            memcpy(audioBuffer.i8, src, toWrite);
1023            src += toWrite;
1024        }
1025        userSize -= toWrite;
1026        written += toWrite;
1027
1028        releaseBuffer(&audioBuffer);
1029    } while (userSize >= frameSz);
1030
1031    return written;
1032}
1033
1034// -------------------------------------------------------------------------
1035
1036TimedAudioTrack::TimedAudioTrack() {
1037    mIsTimed = true;
1038}
1039
1040status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1041{
1042    status_t result = UNKNOWN_ERROR;
1043
1044    // If the track is not invalid already, try to allocate a buffer.  alloc
1045    // fails indicating that the server is dead, flag the track as invalid so
1046    // we can attempt to restore in in just a bit.
1047    if (!(mCblk->flags & CBLK_INVALID_MSK)) {
1048        result = mAudioTrack->allocateTimedBuffer(size, buffer);
1049        if (result == DEAD_OBJECT) {
1050            android_atomic_or(CBLK_INVALID_ON, &mCblk->flags);
1051        }
1052    }
1053
1054    // If the track is invalid at this point, attempt to restore it. and try the
1055    // allocation one more time.
1056    if (mCblk->flags & CBLK_INVALID_MSK) {
1057        mCblk->lock.lock();
1058        result = restoreTrack_l(mCblk, false);
1059        mCblk->lock.unlock();
1060
1061        if (result == OK)
1062            result = mAudioTrack->allocateTimedBuffer(size, buffer);
1063    }
1064
1065    return result;
1066}
1067
1068status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1069                                           int64_t pts)
1070{
1071    // restart track if it was disabled by audioflinger due to previous underrun
1072    if (mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
1073        android_atomic_and(~CBLK_DISABLED_ON, &mCblk->flags);
1074        ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1075        mAudioTrack->start(0);
1076    }
1077
1078    return mAudioTrack->queueTimedBuffer(buffer, pts);
1079}
1080
1081status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1082                                                TargetTimeline target)
1083{
1084    return mAudioTrack->setMediaTimeTransform(xform, target);
1085}
1086
1087// -------------------------------------------------------------------------
1088
1089bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1090{
1091    Buffer audioBuffer;
1092    uint32_t frames;
1093    size_t writtenSize;
1094
1095    mLock.lock();
1096    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1097    // while we are accessing the cblk
1098    sp <IAudioTrack> audioTrack = mAudioTrack;
1099    sp <IMemory> iMem = mCblkMemory;
1100    audio_track_cblk_t* cblk = mCblk;
1101    bool active = mActive;
1102    mLock.unlock();
1103
1104    // Manage underrun callback
1105    if (active && (cblk->framesAvailable() == cblk->frameCount)) {
1106        ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
1107        if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
1108            mCbf(EVENT_UNDERRUN, mUserData, 0);
1109            if (cblk->server == cblk->frameCount) {
1110                mCbf(EVENT_BUFFER_END, mUserData, 0);
1111            }
1112            if (mSharedBuffer != 0) return false;
1113        }
1114    }
1115
1116    // Manage loop end callback
1117    while (mLoopCount > cblk->loopCount) {
1118        int loopCount = -1;
1119        mLoopCount--;
1120        if (mLoopCount >= 0) loopCount = mLoopCount;
1121
1122        mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1123    }
1124
1125    // Manage marker callback
1126    if (!mMarkerReached && (mMarkerPosition > 0)) {
1127        if (cblk->server >= mMarkerPosition) {
1128            mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
1129            mMarkerReached = true;
1130        }
1131    }
1132
1133    // Manage new position callback
1134    if (mUpdatePeriod > 0) {
1135        while (cblk->server >= mNewPosition) {
1136            mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1137            mNewPosition += mUpdatePeriod;
1138        }
1139    }
1140
1141    // If Shared buffer is used, no data is requested from client.
1142    if (mSharedBuffer != 0) {
1143        frames = 0;
1144    } else {
1145        frames = mRemainingFrames;
1146    }
1147
1148    // See description of waitCount parameter at declaration of obtainBuffer().
1149    // The logic below prevents us from being stuck below at obtainBuffer()
1150    // not being able to handle timed events (position, markers, loops).
1151    int32_t waitCount = -1;
1152    if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1153        waitCount = 1;
1154    }
1155
1156    do {
1157
1158        audioBuffer.frameCount = frames;
1159
1160        status_t err = obtainBuffer(&audioBuffer, waitCount);
1161        if (err < NO_ERROR) {
1162            if (err != TIMED_OUT) {
1163                ALOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
1164                return false;
1165            }
1166            break;
1167        }
1168        if (err == status_t(STOPPED)) return false;
1169
1170        // Divide buffer size by 2 to take into account the expansion
1171        // due to 8 to 16 bit conversion: the callback must fill only half
1172        // of the destination buffer
1173        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
1174            audioBuffer.size >>= 1;
1175        }
1176
1177        size_t reqSize = audioBuffer.size;
1178        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1179        writtenSize = audioBuffer.size;
1180
1181        // Sanity check on returned size
1182        if (ssize_t(writtenSize) <= 0) {
1183            // The callback is done filling buffers
1184            // Keep this thread going to handle timed events and
1185            // still try to get more data in intervals of WAIT_PERIOD_MS
1186            // but don't just loop and block the CPU, so wait
1187            usleep(WAIT_PERIOD_MS*1000);
1188            break;
1189        }
1190        if (writtenSize > reqSize) writtenSize = reqSize;
1191
1192        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
1193            // 8 to 16 bit conversion, note that source and destination are the same address
1194            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
1195            writtenSize <<= 1;
1196        }
1197
1198        audioBuffer.size = writtenSize;
1199        // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1200        // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sample size of
1201        // 16 bit.
1202        audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1203
1204        frames -= audioBuffer.frameCount;
1205
1206        releaseBuffer(&audioBuffer);
1207    }
1208    while (frames);
1209
1210    if (frames == 0) {
1211        mRemainingFrames = mNotificationFramesAct;
1212    } else {
1213        mRemainingFrames = frames;
1214    }
1215    return true;
1216}
1217
1218// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1219// the IAudioTrack and IMemory in case they are recreated here.
1220// If the IAudioTrack is successfully restored, the cblk pointer is updated
1221status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1222{
1223    status_t result;
1224
1225    if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
1226        ALOGW("dead IAudioTrack, creating a new one from %s TID %d",
1227             fromStart ? "start()" : "obtainBuffer()", gettid());
1228
1229        // signal old cblk condition so that other threads waiting for available buffers stop
1230        // waiting now
1231        cblk->cv.broadcast();
1232        cblk->lock.unlock();
1233
1234        // refresh the audio configuration cache in this process to make sure we get new
1235        // output parameters in getOutput_l() and createTrack_l()
1236        AudioSystem::clearAudioConfigCache();
1237
1238        // if the new IAudioTrack is created, createTrack_l() will modify the
1239        // following member variables: mAudioTrack, mCblkMemory and mCblk.
1240        // It will also delete the strong references on previous IAudioTrack and IMemory
1241        result = createTrack_l(mStreamType,
1242                               cblk->sampleRate,
1243                               mFormat,
1244                               mChannelMask,
1245                               mFrameCount,
1246                               mFlags,
1247                               mSharedBuffer,
1248                               getOutput_l(),
1249                               false);
1250
1251        if (result == NO_ERROR) {
1252            uint32_t user = cblk->user;
1253            uint32_t server = cblk->server;
1254            // restore write index and set other indexes to reflect empty buffer status
1255            mCblk->user = user;
1256            mCblk->server = user;
1257            mCblk->userBase = user;
1258            mCblk->serverBase = user;
1259            // restore loop: this is not guaranteed to succeed if new frame count is not
1260            // compatible with loop length
1261            setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
1262            if (!fromStart) {
1263                mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1264                // Make sure that a client relying on callback events indicating underrun or
1265                // the actual amount of audio frames played (e.g SoundPool) receives them.
1266                if (mSharedBuffer == 0) {
1267                    uint32_t frames = 0;
1268                    if (user > server) {
1269                        frames = ((user - server) > mCblk->frameCount) ?
1270                                mCblk->frameCount : (user - server);
1271                        memset(mCblk->buffers, 0, frames * mCblk->frameSize);
1272                    }
1273                    // restart playback even if buffer is not completely filled.
1274                    android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
1275                    // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
1276                    // the client
1277                    mCblk->stepUser(frames);
1278                }
1279            }
1280            if (mActive) {
1281                result = mAudioTrack->start(0); // callback thread hasn't changed
1282                ALOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
1283            }
1284            if (fromStart && result == NO_ERROR) {
1285                mNewPosition = mCblk->server + mUpdatePeriod;
1286            }
1287        }
1288        if (result != NO_ERROR) {
1289            android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
1290            ALOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
1291        }
1292        mRestoreStatus = result;
1293        // signal old cblk condition for other threads waiting for restore completion
1294        android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
1295        cblk->cv.broadcast();
1296    } else {
1297        if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1298            ALOGW("dead IAudioTrack, waiting for a new one TID %d", gettid());
1299            mLock.unlock();
1300            result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1301            if (result == NO_ERROR) {
1302                result = mRestoreStatus;
1303            }
1304            cblk->lock.unlock();
1305            mLock.lock();
1306        } else {
1307            ALOGW("dead IAudioTrack, already restored TID %d", gettid());
1308            result = mRestoreStatus;
1309            cblk->lock.unlock();
1310        }
1311    }
1312    ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1313         result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1314
1315    if (result == NO_ERROR) {
1316        // from now on we switch to the newly created cblk
1317        cblk = mCblk;
1318    }
1319    cblk->lock.lock();
1320
1321    ALOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
1322
1323    return result;
1324}
1325
1326status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1327{
1328
1329    const size_t SIZE = 256;
1330    char buffer[SIZE];
1331    String8 result;
1332
1333    result.append(" AudioTrack::dump\n");
1334    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1335    result.append(buffer);
1336    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mCblk->frameCount);
1337    result.append(buffer);
1338    snprintf(buffer, 255, "  sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
1339    result.append(buffer);
1340    snprintf(buffer, 255, "  active(%d), latency (%d)\n", mActive, mLatency);
1341    result.append(buffer);
1342    ::write(fd, result.string(), result.size());
1343    return NO_ERROR;
1344}
1345
1346// =========================================================================
1347
1348AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1349    : Thread(bCanCallJava), mReceiver(receiver)
1350{
1351}
1352
1353bool AudioTrack::AudioTrackThread::threadLoop()
1354{
1355    return mReceiver.processAudioBuffer(this);
1356}
1357
1358status_t AudioTrack::AudioTrackThread::readyToRun()
1359{
1360    return NO_ERROR;
1361}
1362
1363void AudioTrack::AudioTrackThread::onFirstRef()
1364{
1365}
1366
1367// =========================================================================
1368
1369
1370audio_track_cblk_t::audio_track_cblk_t()
1371    : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1372    userBase(0), serverBase(0), buffers(NULL), frameCount(0),
1373    loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), mVolumeLR(0x10001000),
1374    mSendLevel(0), flags(0)
1375{
1376}
1377
1378uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1379{
1380    uint32_t u = user;
1381
1382    u += frameCount;
1383    // Ensure that user is never ahead of server for AudioRecord
1384    if (flags & CBLK_DIRECTION_MSK) {
1385        // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1386        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1387            bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1388        }
1389    } else if (u > server) {
1390        ALOGW("stepServer occurred after track reset");
1391        u = server;
1392    }
1393
1394    if (u >= userBase + this->frameCount) {
1395        userBase += this->frameCount;
1396    }
1397
1398    user = u;
1399
1400    // Clear flow control error condition as new data has been written/read to/from buffer.
1401    if (flags & CBLK_UNDERRUN_MSK) {
1402        android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
1403    }
1404
1405    return u;
1406}
1407
1408bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1409{
1410    if (!tryLock()) {
1411        ALOGW("stepServer() could not lock cblk");
1412        return false;
1413    }
1414
1415    uint32_t s = server;
1416
1417    s += frameCount;
1418    if (flags & CBLK_DIRECTION_MSK) {
1419        // Mark that we have read the first buffer so that next time stepUser() is called
1420        // we switch to normal obtainBuffer() timeout period
1421        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
1422            bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
1423        }
1424        // It is possible that we receive a flush()
1425        // while the mixer is processing a block: in this case,
1426        // stepServer() is called After the flush() has reset u & s and
1427        // we have s > u
1428        if (s > user) {
1429            ALOGW("stepServer occurred after track reset");
1430            s = user;
1431        }
1432    }
1433
1434    if (s >= loopEnd) {
1435        ALOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1436        s = loopStart;
1437        if (--loopCount == 0) {
1438            loopEnd = UINT_MAX;
1439            loopStart = UINT_MAX;
1440        }
1441    }
1442    if (s >= serverBase + this->frameCount) {
1443        serverBase += this->frameCount;
1444    }
1445
1446    server = s;
1447
1448    if (!(flags & CBLK_INVALID_MSK)) {
1449        cv.signal();
1450    }
1451    lock.unlock();
1452    return true;
1453}
1454
1455void* audio_track_cblk_t::buffer(uint32_t offset) const
1456{
1457    return (int8_t *)buffers + (offset - userBase) * frameSize;
1458}
1459
1460uint32_t audio_track_cblk_t::framesAvailable()
1461{
1462    Mutex::Autolock _l(lock);
1463    return framesAvailable_l();
1464}
1465
1466uint32_t audio_track_cblk_t::framesAvailable_l()
1467{
1468    uint32_t u = user;
1469    uint32_t s = server;
1470
1471    if (flags & CBLK_DIRECTION_MSK) {
1472        uint32_t limit = (s < loopStart) ? s : loopStart;
1473        return limit + frameCount - u;
1474    } else {
1475        return frameCount + u - s;
1476    }
1477}
1478
1479uint32_t audio_track_cblk_t::framesReady()
1480{
1481    uint32_t u = user;
1482    uint32_t s = server;
1483
1484    if (flags & CBLK_DIRECTION_MSK) {
1485        if (u < loopEnd) {
1486            return u - s;
1487        } else {
1488            // do not block on mutex shared with client on AudioFlinger side
1489            if (!tryLock()) {
1490                ALOGW("framesReady() could not lock cblk");
1491                return 0;
1492            }
1493            uint32_t frames = UINT_MAX;
1494            if (loopCount >= 0) {
1495                frames = (loopEnd - loopStart)*loopCount + u - s;
1496            }
1497            lock.unlock();
1498            return frames;
1499        }
1500    } else {
1501        return s - u;
1502    }
1503}
1504
1505bool audio_track_cblk_t::tryLock()
1506{
1507    // the code below simulates lock-with-timeout
1508    // we MUST do this to protect the AudioFlinger server
1509    // as this lock is shared with the client.
1510    status_t err;
1511
1512    err = lock.tryLock();
1513    if (err == -EBUSY) { // just wait a bit
1514        usleep(1000);
1515        err = lock.tryLock();
1516    }
1517    if (err != NO_ERROR) {
1518        // probably, the client just died.
1519        return false;
1520    }
1521    return true;
1522}
1523
1524// -------------------------------------------------------------------------
1525
1526}; // namespace android
1527