AudioTrack.cpp revision 7c027248e1a4ccd5b22bc4deafb03e2d87ac8f38
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        if (minBufCount < 2) {
865            minBufCount = 2;
866        }
867
868        size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
869        ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
870                ", afLatency=%d",
871                minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
872
873        if (frameCount == 0) {
874            frameCount = minFrameCount;
875        }
876        if (mNotificationFramesAct == 0) {
877            mNotificationFramesAct = frameCount/2;
878        }
879        // Make sure that application is notified with sufficient margin
880        // before underrun
881        if (mNotificationFramesAct > frameCount/2) {
882            mNotificationFramesAct = frameCount/2;
883        }
884        if (frameCount < minFrameCount) {
885            // not ALOGW because it happens all the time when playing key clicks over A2DP
886            ALOGV("Minimum buffer size corrected from %d to %d",
887                     frameCount, minFrameCount);
888            frameCount = minFrameCount;
889        }
890
891    } else {
892        // For fast tracks, the frame count calculations and checks are done by server
893    }
894
895    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
896    if (mIsTimed) {
897        trackFlags |= IAudioFlinger::TRACK_TIMED;
898    }
899
900    pid_t tid = -1;
901    if (flags & AUDIO_OUTPUT_FLAG_FAST) {
902        trackFlags |= IAudioFlinger::TRACK_FAST;
903        if (mAudioTrackThread != 0) {
904            tid = mAudioTrackThread->getTid();
905        }
906    }
907
908    sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
909                                                      sampleRate,
910                                                      // AudioFlinger only sees 16-bit PCM
911                                                      format == AUDIO_FORMAT_PCM_8_BIT ?
912                                                              AUDIO_FORMAT_PCM_16_BIT : format,
913                                                      mChannelMask,
914                                                      frameCount,
915                                                      &trackFlags,
916                                                      sharedBuffer,
917                                                      output,
918                                                      tid,
919                                                      &mSessionId,
920                                                      &status);
921
922    if (track == 0) {
923        ALOGE("AudioFlinger could not create track, status: %d", status);
924        return status;
925    }
926    sp<IMemory> iMem = track->getCblk();
927    if (iMem == 0) {
928        ALOGE("Could not get control block");
929        return NO_INIT;
930    }
931    mAudioTrack = track;
932    mCblkMemory = iMem;
933    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
934    mCblk = cblk;
935    size_t temp = cblk->frameCount_;
936    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
937        // In current design, AudioTrack client checks and ensures frame count validity before
938        // passing it to AudioFlinger so AudioFlinger should not return a different value except
939        // for fast track as it uses a special method of assigning frame count.
940        ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
941    }
942    frameCount = temp;
943    mAwaitBoost = false;
944    if (flags & AUDIO_OUTPUT_FLAG_FAST) {
945        if (trackFlags & IAudioFlinger::TRACK_FAST) {
946            ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
947            mAwaitBoost = true;
948        } else {
949            ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
950            // once denied, do not request again if IAudioTrack is re-created
951            flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
952            mFlags = flags;
953        }
954        if (sharedBuffer == 0) {
955            mNotificationFramesAct = frameCount/2;
956        }
957    }
958    if (sharedBuffer == 0) {
959        mBuffers = (char*)cblk + sizeof(audio_track_cblk_t);
960    } else {
961        mBuffers = sharedBuffer->pointer();
962    }
963
964    mAudioTrack->attachAuxEffect(mAuxEffectId);
965    cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
966    cblk->waitTimeMs = 0;
967    mRemainingFrames = mNotificationFramesAct;
968    // FIXME don't believe this lie
969    mLatency = afLatency + (1000*frameCount) / sampleRate;
970    mFrameCount = frameCount;
971    // If IAudioTrack is re-created, don't let the requested frameCount
972    // decrease.  This can confuse clients that cache frameCount().
973    if (frameCount > mReqFrameCount) {
974        mReqFrameCount = frameCount;
975    }
976
977    // update proxy
978    delete mProxy;
979    mProxy = new AudioTrackClientProxy(cblk, mBuffers, frameCount, mFrameSizeAF);
980    mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
981            uint16_t(mVolume[LEFT] * 0x1000));
982    mProxy->setSendLevel(mSendLevel);
983    mProxy->setSampleRate(mSampleRate);
984    if (sharedBuffer != 0) {
985        // Force buffer full condition as data is already present in shared memory
986        mProxy->stepUser(frameCount);
987    }
988
989    return NO_ERROR;
990}
991
992status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
993{
994    ALOG_ASSERT(mStatus == NO_ERROR && mProxy != NULL);
995
996    AutoMutex lock(mLock);
997    bool active;
998    status_t result = NO_ERROR;
999    audio_track_cblk_t* cblk = mCblk;
1000    uint32_t framesReq = audioBuffer->frameCount;
1001    uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
1002
1003    audioBuffer->frameCount  = 0;
1004    audioBuffer->size = 0;
1005
1006    size_t framesAvail = mProxy->framesAvailable();
1007
1008    cblk->lock.lock();
1009    if (cblk->flags & CBLK_INVALID) {
1010        goto create_new_track;
1011    }
1012    cblk->lock.unlock();
1013
1014    if (framesAvail == 0) {
1015        cblk->lock.lock();
1016        goto start_loop_here;
1017        while (framesAvail == 0) {
1018            active = mActive;
1019            if (CC_UNLIKELY(!active)) {
1020                ALOGV("Not active and NO_MORE_BUFFERS");
1021                cblk->lock.unlock();
1022                return NO_MORE_BUFFERS;
1023            }
1024            if (CC_UNLIKELY(!waitCount)) {
1025                cblk->lock.unlock();
1026                return WOULD_BLOCK;
1027            }
1028            if (!(cblk->flags & CBLK_INVALID)) {
1029                mLock.unlock();
1030                // this condition is in shared memory, so if IAudioTrack and control block
1031                // are replaced due to mediaserver death or IAudioTrack invalidation then
1032                // cv won't be signalled, but fortunately the timeout will limit the wait
1033                result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
1034                cblk->lock.unlock();
1035                mLock.lock();
1036                if (!mActive) {
1037                    return status_t(STOPPED);
1038                }
1039                // IAudioTrack may have been re-created while mLock was unlocked
1040                cblk = mCblk;
1041                cblk->lock.lock();
1042            }
1043
1044            if (cblk->flags & CBLK_INVALID) {
1045                goto create_new_track;
1046            }
1047            if (CC_UNLIKELY(result != NO_ERROR)) {
1048                cblk->waitTimeMs += waitTimeMs;
1049                if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
1050                    // timing out when a loop has been set and we have already written upto loop end
1051                    // is a normal condition: no need to wake AudioFlinger up.
1052                    if (cblk->user < cblk->loopEnd) {
1053                        ALOGW("obtainBuffer timed out (is the CPU pegged?) %p name=%#x user=%08x, "
1054                              "server=%08x", this, cblk->mName, cblk->user, cblk->server);
1055                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
1056                        cblk->lock.unlock();
1057                        result = mAudioTrack->start();
1058                        cblk->lock.lock();
1059                        if (result == DEAD_OBJECT) {
1060                            android_atomic_or(CBLK_INVALID, &cblk->flags);
1061create_new_track:
1062                            audio_track_cblk_t* temp = cblk;
1063                            result = restoreTrack_l(temp, false /*fromStart*/);
1064                            cblk = temp;
1065                        }
1066                        if (result != NO_ERROR) {
1067                            ALOGW("obtainBuffer create Track error %d", result);
1068                            cblk->lock.unlock();
1069                            return result;
1070                        }
1071                    }
1072                    cblk->waitTimeMs = 0;
1073                }
1074
1075                if (--waitCount == 0) {
1076                    cblk->lock.unlock();
1077                    return TIMED_OUT;
1078                }
1079            }
1080            // read the server count again
1081        start_loop_here:
1082            framesAvail = mProxy->framesAvailable_l();
1083        }
1084        cblk->lock.unlock();
1085    }
1086
1087    cblk->waitTimeMs = 0;
1088
1089    if (framesReq > framesAvail) {
1090        framesReq = framesAvail;
1091    }
1092
1093    uint32_t u = cblk->user;
1094    uint32_t bufferEnd = cblk->userBase + mFrameCount;
1095
1096    if (framesReq > bufferEnd - u) {
1097        framesReq = bufferEnd - u;
1098    }
1099
1100    audioBuffer->frameCount = framesReq;
1101    audioBuffer->size = framesReq * mFrameSizeAF;
1102    audioBuffer->raw = mProxy->buffer(u);
1103    active = mActive;
1104    return active ? status_t(NO_ERROR) : status_t(STOPPED);
1105}
1106
1107void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1108{
1109    ALOG_ASSERT(mStatus == NO_ERROR && mProxy != NULL);
1110
1111    AutoMutex lock(mLock);
1112    audio_track_cblk_t* cblk = mCblk;
1113    (void) mProxy->stepUser(audioBuffer->frameCount);
1114    if (audioBuffer->frameCount > 0) {
1115        // restart track if it was disabled by audioflinger due to previous underrun
1116        if (mActive && (cblk->flags & CBLK_DISABLED)) {
1117            android_atomic_and(~CBLK_DISABLED, &cblk->flags);
1118            ALOGW("releaseBuffer() track %p name=%#x disabled, restarting", this, cblk->mName);
1119            mAudioTrack->start();
1120        }
1121    }
1122}
1123
1124// -------------------------------------------------------------------------
1125
1126ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1127{
1128
1129    if (mSharedBuffer != 0 || mIsTimed) {
1130        return INVALID_OPERATION;
1131    }
1132
1133    if (ssize_t(userSize) < 0) {
1134        // Sanity-check: user is most-likely passing an error code, and it would
1135        // make the return value ambiguous (actualSize vs error).
1136        ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
1137                buffer, userSize, userSize);
1138        return BAD_VALUE;
1139    }
1140
1141    ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
1142
1143    if (userSize == 0) {
1144        return 0;
1145    }
1146
1147    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1148    // while we are accessing the cblk
1149    mLock.lock();
1150    sp<IAudioTrack> audioTrack = mAudioTrack;
1151    sp<IMemory> iMem = mCblkMemory;
1152    mLock.unlock();
1153
1154    // since mLock is unlocked the IAudioTrack and shared memory may be re-created,
1155    // so all cblk references might still refer to old shared memory, but that should be benign
1156
1157    ssize_t written = 0;
1158    const int8_t *src = (const int8_t *)buffer;
1159    Buffer audioBuffer;
1160    size_t frameSz = frameSize();
1161
1162    do {
1163        audioBuffer.frameCount = userSize/frameSz;
1164
1165        status_t err = obtainBuffer(&audioBuffer, -1);
1166        if (err < 0) {
1167            // out of buffers, return #bytes written
1168            if (err == status_t(NO_MORE_BUFFERS)) {
1169                break;
1170            }
1171            return ssize_t(err);
1172        }
1173
1174        size_t toWrite;
1175
1176        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1177            // Divide capacity by 2 to take expansion into account
1178            toWrite = audioBuffer.size>>1;
1179            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite);
1180        } else {
1181            toWrite = audioBuffer.size;
1182            memcpy(audioBuffer.i8, src, toWrite);
1183        }
1184        src += toWrite;
1185        userSize -= toWrite;
1186        written += toWrite;
1187
1188        releaseBuffer(&audioBuffer);
1189    } while (userSize >= frameSz);
1190
1191    return written;
1192}
1193
1194// -------------------------------------------------------------------------
1195
1196TimedAudioTrack::TimedAudioTrack() {
1197    mIsTimed = true;
1198}
1199
1200status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1201{
1202    AutoMutex lock(mLock);
1203    status_t result = UNKNOWN_ERROR;
1204
1205    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1206    // while we are accessing the cblk
1207    sp<IAudioTrack> audioTrack = mAudioTrack;
1208    sp<IMemory> iMem = mCblkMemory;
1209
1210    // If the track is not invalid already, try to allocate a buffer.  alloc
1211    // fails indicating that the server is dead, flag the track as invalid so
1212    // we can attempt to restore in just a bit.
1213    audio_track_cblk_t* cblk = mCblk;
1214    if (!(cblk->flags & CBLK_INVALID)) {
1215        result = mAudioTrack->allocateTimedBuffer(size, buffer);
1216        if (result == DEAD_OBJECT) {
1217            android_atomic_or(CBLK_INVALID, &cblk->flags);
1218        }
1219    }
1220
1221    // If the track is invalid at this point, attempt to restore it. and try the
1222    // allocation one more time.
1223    if (cblk->flags & CBLK_INVALID) {
1224        cblk->lock.lock();
1225        audio_track_cblk_t* temp = cblk;
1226        result = restoreTrack_l(temp, false /*fromStart*/);
1227        cblk = temp;
1228        cblk->lock.unlock();
1229
1230        if (result == OK) {
1231            result = mAudioTrack->allocateTimedBuffer(size, buffer);
1232        }
1233    }
1234
1235    return result;
1236}
1237
1238status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1239                                           int64_t pts)
1240{
1241    status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1242    {
1243        AutoMutex lock(mLock);
1244        audio_track_cblk_t* cblk = mCblk;
1245        // restart track if it was disabled by audioflinger due to previous underrun
1246        if (buffer->size() != 0 && status == NO_ERROR &&
1247                mActive && (cblk->flags & CBLK_DISABLED)) {
1248            android_atomic_and(~CBLK_DISABLED, &cblk->flags);
1249            ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1250            mAudioTrack->start();
1251        }
1252    }
1253    return status;
1254}
1255
1256status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1257                                                TargetTimeline target)
1258{
1259    return mAudioTrack->setMediaTimeTransform(xform, target);
1260}
1261
1262// -------------------------------------------------------------------------
1263
1264bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1265{
1266    Buffer audioBuffer;
1267    uint32_t frames;
1268    size_t writtenSize;
1269
1270    mLock.lock();
1271    if (mAwaitBoost) {
1272        mAwaitBoost = false;
1273        mLock.unlock();
1274        static const int32_t kMaxTries = 5;
1275        int32_t tryCounter = kMaxTries;
1276        uint32_t pollUs = 10000;
1277        do {
1278            int policy = sched_getscheduler(0);
1279            if (policy == SCHED_FIFO || policy == SCHED_RR) {
1280                break;
1281            }
1282            usleep(pollUs);
1283            pollUs <<= 1;
1284        } while (tryCounter-- > 0);
1285        if (tryCounter < 0) {
1286            ALOGE("did not receive expected priority boost on time");
1287        }
1288        return true;
1289    }
1290    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1291    // while we are accessing the cblk
1292    sp<IAudioTrack> audioTrack = mAudioTrack;
1293    sp<IMemory> iMem = mCblkMemory;
1294    audio_track_cblk_t* cblk = mCblk;
1295    bool active = mActive;
1296    mLock.unlock();
1297
1298    // since mLock is unlocked the IAudioTrack and shared memory may be re-created,
1299    // so all cblk references might still refer to old shared memory, but that should be benign
1300
1301    // Manage underrun callback
1302    if (active && (mProxy->framesAvailable() == mFrameCount)) {
1303        ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
1304        if (!(android_atomic_or(CBLK_UNDERRUN, &cblk->flags) & CBLK_UNDERRUN)) {
1305            mCbf(EVENT_UNDERRUN, mUserData, 0);
1306            if (cblk->server == mFrameCount) {
1307                mCbf(EVENT_BUFFER_END, mUserData, 0);
1308            }
1309            if (mSharedBuffer != 0) {
1310                return false;
1311            }
1312        }
1313    }
1314
1315    // Manage loop end callback
1316    while (mLoopCount > cblk->loopCount) {
1317        int loopCount = -1;
1318        mLoopCount--;
1319        if (mLoopCount >= 0) loopCount = mLoopCount;
1320
1321        mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1322    }
1323
1324    // Manage marker callback
1325    if (!mMarkerReached && (mMarkerPosition > 0)) {
1326        if (cblk->server >= mMarkerPosition) {
1327            mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
1328            mMarkerReached = true;
1329        }
1330    }
1331
1332    // Manage new position callback
1333    if (mUpdatePeriod > 0) {
1334        while (cblk->server >= mNewPosition) {
1335            mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1336            mNewPosition += mUpdatePeriod;
1337        }
1338    }
1339
1340    // If Shared buffer is used, no data is requested from client.
1341    if (mSharedBuffer != 0) {
1342        frames = 0;
1343    } else {
1344        frames = mRemainingFrames;
1345    }
1346
1347    // See description of waitCount parameter at declaration of obtainBuffer().
1348    // The logic below prevents us from being stuck below at obtainBuffer()
1349    // not being able to handle timed events (position, markers, loops).
1350    int32_t waitCount = -1;
1351    if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1352        waitCount = 1;
1353    }
1354
1355    do {
1356
1357        audioBuffer.frameCount = frames;
1358
1359        status_t err = obtainBuffer(&audioBuffer, waitCount);
1360        if (err < NO_ERROR) {
1361            if (err != TIMED_OUT) {
1362                ALOGE_IF(err != status_t(NO_MORE_BUFFERS),
1363                        "Error obtaining an audio buffer, giving up.");
1364                return false;
1365            }
1366            break;
1367        }
1368        if (err == status_t(STOPPED)) {
1369            return false;
1370        }
1371
1372        // Divide buffer size by 2 to take into account the expansion
1373        // due to 8 to 16 bit conversion: the callback must fill only half
1374        // of the destination buffer
1375        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1376            audioBuffer.size >>= 1;
1377        }
1378
1379        size_t reqSize = audioBuffer.size;
1380        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1381        writtenSize = audioBuffer.size;
1382
1383        // Sanity check on returned size
1384        if (ssize_t(writtenSize) <= 0) {
1385            // The callback is done filling buffers
1386            // Keep this thread going to handle timed events and
1387            // still try to get more data in intervals of WAIT_PERIOD_MS
1388            // but don't just loop and block the CPU, so wait
1389            usleep(WAIT_PERIOD_MS*1000);
1390            break;
1391        }
1392
1393        if (writtenSize > reqSize) {
1394            writtenSize = reqSize;
1395        }
1396
1397        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1398            // 8 to 16 bit conversion, note that source and destination are the same address
1399            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
1400            writtenSize <<= 1;
1401        }
1402
1403        audioBuffer.size = writtenSize;
1404        // NOTE: cblk->frameSize is not equal to AudioTrack::frameSize() for
1405        // 8 bit PCM data: in this case,  cblk->frameSize is based on a sample size of
1406        // 16 bit.
1407        audioBuffer.frameCount = writtenSize / mFrameSizeAF;
1408
1409        frames -= audioBuffer.frameCount;
1410
1411        releaseBuffer(&audioBuffer);
1412    }
1413    while (frames);
1414
1415    if (frames == 0) {
1416        mRemainingFrames = mNotificationFramesAct;
1417    } else {
1418        mRemainingFrames = frames;
1419    }
1420    return true;
1421}
1422
1423// must be called with mLock and refCblk.lock held. Callers must also hold strong references on
1424// the IAudioTrack and IMemory in case they are recreated here.
1425// If the IAudioTrack is successfully restored, the refCblk pointer is updated
1426// FIXME Don't depend on caller to hold strong references.
1427status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& refCblk, bool fromStart)
1428{
1429    status_t result;
1430
1431    audio_track_cblk_t* cblk = refCblk;
1432    audio_track_cblk_t* newCblk = cblk;
1433    ALOGW("dead IAudioTrack, creating a new one from %s",
1434        fromStart ? "start()" : "obtainBuffer()");
1435
1436    // signal old cblk condition so that other threads waiting for available buffers stop
1437    // waiting now
1438    cblk->cv.broadcast();
1439    cblk->lock.unlock();
1440
1441    // refresh the audio configuration cache in this process to make sure we get new
1442    // output parameters in getOutput_l() and createTrack_l()
1443    AudioSystem::clearAudioConfigCache();
1444
1445    // if the new IAudioTrack is created, createTrack_l() will modify the
1446    // following member variables: mAudioTrack, mCblkMemory and mCblk.
1447    // It will also delete the strong references on previous IAudioTrack and IMemory
1448    result = createTrack_l(mStreamType,
1449                           mSampleRate,
1450                           mFormat,
1451                           mReqFrameCount,  // so that frame count never goes down
1452                           mFlags,
1453                           mSharedBuffer,
1454                           getOutput_l());
1455
1456    if (result == NO_ERROR) {
1457        uint32_t user = cblk->user;
1458        uint32_t server = cblk->server;
1459        // restore write index and set other indexes to reflect empty buffer status
1460        newCblk = mCblk;
1461        newCblk->user = user;
1462        newCblk->server = user;
1463        newCblk->userBase = user;
1464        newCblk->serverBase = user;
1465        // restore loop: this is not guaranteed to succeed if new frame count is not
1466        // compatible with loop length
1467        setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
1468        size_t frames = 0;
1469        if (!fromStart) {
1470            newCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1471            // Make sure that a client relying on callback events indicating underrun or
1472            // the actual amount of audio frames played (e.g SoundPool) receives them.
1473            if (mSharedBuffer == 0) {
1474                if (user > server) {
1475                    frames = ((user - server) > mFrameCount) ?
1476                            mFrameCount : (user - server);
1477                    memset(mBuffers, 0, frames * mFrameSizeAF);
1478                }
1479                // restart playback even if buffer is not completely filled.
1480                android_atomic_or(CBLK_FORCEREADY, &newCblk->flags);
1481            }
1482        }
1483        if (mSharedBuffer != 0) {
1484            frames = mFrameCount;
1485        }
1486        if (frames > 0) {
1487            // stepUser() clears CBLK_UNDERRUN flag enabling underrun callbacks to
1488            // the client
1489            mProxy->stepUser(frames);
1490        }
1491        if (mActive) {
1492            result = mAudioTrack->start();
1493            ALOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
1494        }
1495        if (fromStart && result == NO_ERROR) {
1496            mNewPosition = newCblk->server + mUpdatePeriod;
1497        }
1498    }
1499    ALOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
1500    ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1501        result, mActive, newCblk, cblk, newCblk->flags, cblk->flags);
1502
1503    if (result == NO_ERROR) {
1504        // from now on we switch to the newly created cblk
1505        refCblk = newCblk;
1506    }
1507    newCblk->lock.lock();
1508
1509    ALOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1510
1511    return result;
1512}
1513
1514status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1515{
1516
1517    const size_t SIZE = 256;
1518    char buffer[SIZE];
1519    String8 result;
1520
1521    result.append(" AudioTrack::dump\n");
1522    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1523            mVolume[0], mVolume[1]);
1524    result.append(buffer);
1525    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%d)\n", mFormat,
1526            mChannelCount, mFrameCount);
1527    result.append(buffer);
1528    snprintf(buffer, 255, "  sample rate(%u), status(%d)\n", mSampleRate, mStatus);
1529    result.append(buffer);
1530    snprintf(buffer, 255, "  active(%d), latency (%d)\n", mActive, mLatency);
1531    result.append(buffer);
1532    ::write(fd, result.string(), result.size());
1533    return NO_ERROR;
1534}
1535
1536// =========================================================================
1537
1538AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1539    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true)
1540{
1541}
1542
1543AudioTrack::AudioTrackThread::~AudioTrackThread()
1544{
1545}
1546
1547bool AudioTrack::AudioTrackThread::threadLoop()
1548{
1549    {
1550        AutoMutex _l(mMyLock);
1551        if (mPaused) {
1552            mMyCond.wait(mMyLock);
1553            // caller will check for exitPending()
1554            return true;
1555        }
1556    }
1557    if (!mReceiver.processAudioBuffer(this)) {
1558        pause();
1559    }
1560    return true;
1561}
1562
1563void AudioTrack::AudioTrackThread::requestExit()
1564{
1565    // must be in this order to avoid a race condition
1566    Thread::requestExit();
1567    resume();
1568}
1569
1570void AudioTrack::AudioTrackThread::pause()
1571{
1572    AutoMutex _l(mMyLock);
1573    mPaused = true;
1574}
1575
1576void AudioTrack::AudioTrackThread::resume()
1577{
1578    AutoMutex _l(mMyLock);
1579    if (mPaused) {
1580        mPaused = false;
1581        mMyCond.signal();
1582    }
1583}
1584
1585}; // namespace android
1586