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