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