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