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