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