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