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