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