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