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