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