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