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