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