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