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