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