AudioTrack.cpp revision a075db4ff9b086ac2885df77bb6da0869293df92
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    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
804    if (mIsTimed) {
805        trackFlags |= IAudioFlinger::TRACK_TIMED;
806    }
807    sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
808                                                      streamType,
809                                                      sampleRate,
810                                                      format,
811                                                      channelMask,
812                                                      frameCount,
813                                                      trackFlags,
814                                                      sharedBuffer,
815                                                      output,
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