AudioTrack.cpp revision 64760240f931714858a59c1579f07264d7182ba2
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 channels,
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, channels,
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 channels,
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, channels,
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 channels,
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 (channels == 0) {
184        channels = 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(channels)) {
199        LOGE("Invalid channel mask");
200        return BAD_VALUE;
201    }
202    uint32_t channelCount = popcount(channels);
203
204    audio_io_handle_t output = AudioSystem::getOutput(
205                                    (audio_stream_type_t)streamType,
206                                    sampleRate,format, channels,
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                                  format,
226                                  channelCount,
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 = format;
249    mChannels = channels;
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", THREAD_PRIORITY_AUDIO_CLIENT);
346        } else {
347            setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
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, mChannels, (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        int format,
709        int channelCount,
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            if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
771                LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
772                return BAD_VALUE;
773            }
774            frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
775        }
776    }
777
778    sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
779                                                      streamType,
780                                                      sampleRate,
781                                                      format,
782                                                      channelCount,
783                                                      frameCount,
784                                                      ((uint16_t)flags) << 16,
785                                                      sharedBuffer,
786                                                      output,
787                                                      &mSessionId,
788                                                      &status);
789
790    if (track == 0) {
791        LOGE("AudioFlinger could not create track, status: %d", status);
792        return status;
793    }
794    sp<IMemory> cblk = track->getCblk();
795    if (cblk == 0) {
796        LOGE("Could not get control block");
797        return NO_INIT;
798    }
799    mAudioTrack.clear();
800    mAudioTrack = track;
801    mCblkMemory.clear();
802    mCblkMemory = cblk;
803    mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
804    android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
805    if (sharedBuffer == 0) {
806        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
807    } else {
808        mCblk->buffers = sharedBuffer->pointer();
809         // Force buffer full condition as data is already present in shared memory
810        mCblk->stepUser(mCblk->frameCount);
811    }
812
813    mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
814    mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
815    mAudioTrack->attachAuxEffect(mAuxEffectId);
816    mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
817    mCblk->waitTimeMs = 0;
818    mRemainingFrames = mNotificationFramesAct;
819    mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
820    return NO_ERROR;
821}
822
823status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
824{
825    AutoMutex lock(mLock);
826    int active;
827    status_t result;
828    audio_track_cblk_t* cblk = mCblk;
829    uint32_t framesReq = audioBuffer->frameCount;
830    uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
831
832    audioBuffer->frameCount  = 0;
833    audioBuffer->size = 0;
834
835    uint32_t framesAvail = cblk->framesAvailable();
836
837    cblk->lock.lock();
838    if (cblk->flags & CBLK_INVALID_MSK) {
839        goto create_new_track;
840    }
841    cblk->lock.unlock();
842
843    if (framesAvail == 0) {
844        cblk->lock.lock();
845        goto start_loop_here;
846        while (framesAvail == 0) {
847            active = mActive;
848            if (UNLIKELY(!active)) {
849                LOGV("Not active and NO_MORE_BUFFERS");
850                cblk->lock.unlock();
851                return NO_MORE_BUFFERS;
852            }
853            if (UNLIKELY(!waitCount)) {
854                cblk->lock.unlock();
855                return WOULD_BLOCK;
856            }
857            if (!(cblk->flags & CBLK_INVALID_MSK)) {
858                mLock.unlock();
859                result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
860                cblk->lock.unlock();
861                mLock.lock();
862                if (mActive == 0) {
863                    return status_t(STOPPED);
864                }
865                cblk->lock.lock();
866            }
867
868            if (cblk->flags & CBLK_INVALID_MSK) {
869                goto create_new_track;
870            }
871            if (__builtin_expect(result!=NO_ERROR, false)) {
872                cblk->waitTimeMs += waitTimeMs;
873                if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
874                    // timing out when a loop has been set and we have already written upto loop end
875                    // is a normal condition: no need to wake AudioFlinger up.
876                    if (cblk->user < cblk->loopEnd) {
877                        LOGW(   "obtainBuffer timed out (is the CPU pegged?) %p "
878                                "user=%08x, server=%08x", this, cblk->user, cblk->server);
879                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
880                        cblk->lock.unlock();
881                        result = mAudioTrack->start();
882                        cblk->lock.lock();
883                        if (result == DEAD_OBJECT) {
884                            android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
885create_new_track:
886                            result = restoreTrack_l(cblk, false);
887                        }
888                        if (result != NO_ERROR) {
889                            LOGW("obtainBuffer create Track error %d", result);
890                            cblk->lock.unlock();
891                            return result;
892                        }
893                    }
894                    cblk->waitTimeMs = 0;
895                }
896
897                if (--waitCount == 0) {
898                    cblk->lock.unlock();
899                    return TIMED_OUT;
900                }
901            }
902            // read the server count again
903        start_loop_here:
904            framesAvail = cblk->framesAvailable_l();
905        }
906        cblk->lock.unlock();
907    }
908
909    // restart track if it was disabled by audioflinger due to previous underrun
910    if (mActive && (cblk->flags & CBLK_DISABLED_MSK)) {
911        android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
912        LOGW("obtainBuffer() track %p disabled, restarting", this);
913        mAudioTrack->start();
914    }
915
916    cblk->waitTimeMs = 0;
917
918    if (framesReq > framesAvail) {
919        framesReq = framesAvail;
920    }
921
922    uint32_t u = cblk->user;
923    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
924
925    if (u + framesReq > bufferEnd) {
926        framesReq = bufferEnd - u;
927    }
928
929    audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
930    audioBuffer->channelCount = mChannelCount;
931    audioBuffer->frameCount = framesReq;
932    audioBuffer->size = framesReq * cblk->frameSize;
933    if (audio_is_linear_pcm(mFormat)) {
934        audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
935    } else {
936        audioBuffer->format = mFormat;
937    }
938    audioBuffer->raw = (int8_t *)cblk->buffer(u);
939    active = mActive;
940    return active ? status_t(NO_ERROR) : status_t(STOPPED);
941}
942
943void AudioTrack::releaseBuffer(Buffer* audioBuffer)
944{
945    AutoMutex lock(mLock);
946    mCblk->stepUser(audioBuffer->frameCount);
947}
948
949// -------------------------------------------------------------------------
950
951ssize_t AudioTrack::write(const void* buffer, size_t userSize)
952{
953
954    if (mSharedBuffer != 0) return INVALID_OPERATION;
955
956    if (ssize_t(userSize) < 0) {
957        // sanity-check. user is most-likely passing an error code.
958        LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
959                buffer, userSize, userSize);
960        return BAD_VALUE;
961    }
962
963    LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
964
965    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
966    // while we are accessing the cblk
967    mLock.lock();
968    sp <IAudioTrack> audioTrack = mAudioTrack;
969    sp <IMemory> iMem = mCblkMemory;
970    mLock.unlock();
971
972    ssize_t written = 0;
973    const int8_t *src = (const int8_t *)buffer;
974    Buffer audioBuffer;
975    size_t frameSz = (size_t)frameSize();
976
977    do {
978        audioBuffer.frameCount = userSize/frameSz;
979
980        // Calling obtainBuffer() with a negative wait count causes
981        // an (almost) infinite wait time.
982        status_t err = obtainBuffer(&audioBuffer, -1);
983        if (err < 0) {
984            // out of buffers, return #bytes written
985            if (err == status_t(NO_MORE_BUFFERS))
986                break;
987            return ssize_t(err);
988        }
989
990        size_t toWrite;
991
992        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
993            // Divide capacity by 2 to take expansion into account
994            toWrite = audioBuffer.size>>1;
995            // 8 to 16 bit conversion
996            int count = toWrite;
997            int16_t *dst = (int16_t *)(audioBuffer.i8);
998            while(count--) {
999                *dst++ = (int16_t)(*src++^0x80) << 8;
1000            }
1001        } else {
1002            toWrite = audioBuffer.size;
1003            memcpy(audioBuffer.i8, src, toWrite);
1004            src += toWrite;
1005        }
1006        userSize -= toWrite;
1007        written += toWrite;
1008
1009        releaseBuffer(&audioBuffer);
1010    } while (userSize >= frameSz);
1011
1012    return written;
1013}
1014
1015// -------------------------------------------------------------------------
1016
1017bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1018{
1019    Buffer audioBuffer;
1020    uint32_t frames;
1021    size_t writtenSize;
1022
1023    mLock.lock();
1024    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1025    // while we are accessing the cblk
1026    sp <IAudioTrack> audioTrack = mAudioTrack;
1027    sp <IMemory> iMem = mCblkMemory;
1028    audio_track_cblk_t* cblk = mCblk;
1029    mLock.unlock();
1030
1031    // Manage underrun callback
1032    if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
1033        LOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
1034        if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
1035            mCbf(EVENT_UNDERRUN, mUserData, 0);
1036            if (cblk->server == cblk->frameCount) {
1037                mCbf(EVENT_BUFFER_END, mUserData, 0);
1038            }
1039            if (mSharedBuffer != 0) return false;
1040        }
1041    }
1042
1043    // Manage loop end callback
1044    while (mLoopCount > cblk->loopCount) {
1045        int loopCount = -1;
1046        mLoopCount--;
1047        if (mLoopCount >= 0) loopCount = mLoopCount;
1048
1049        mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1050    }
1051
1052    // Manage marker callback
1053    if (!mMarkerReached && (mMarkerPosition > 0)) {
1054        if (cblk->server >= mMarkerPosition) {
1055            mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
1056            mMarkerReached = true;
1057        }
1058    }
1059
1060    // Manage new position callback
1061    if (mUpdatePeriod > 0) {
1062        while (cblk->server >= mNewPosition) {
1063            mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1064            mNewPosition += mUpdatePeriod;
1065        }
1066    }
1067
1068    // If Shared buffer is used, no data is requested from client.
1069    if (mSharedBuffer != 0) {
1070        frames = 0;
1071    } else {
1072        frames = mRemainingFrames;
1073    }
1074
1075    do {
1076
1077        audioBuffer.frameCount = frames;
1078
1079        // Calling obtainBuffer() with a wait count of 1
1080        // limits wait time to WAIT_PERIOD_MS. This prevents from being
1081        // stuck here not being able to handle timed events (position, markers, loops).
1082        status_t err = obtainBuffer(&audioBuffer, 1);
1083        if (err < NO_ERROR) {
1084            if (err != TIMED_OUT) {
1085                LOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
1086                return false;
1087            }
1088            break;
1089        }
1090        if (err == status_t(STOPPED)) return false;
1091
1092        // Divide buffer size by 2 to take into account the expansion
1093        // due to 8 to 16 bit conversion: the callback must fill only half
1094        // of the destination buffer
1095        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
1096            audioBuffer.size >>= 1;
1097        }
1098
1099        size_t reqSize = audioBuffer.size;
1100        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1101        writtenSize = audioBuffer.size;
1102
1103        // Sanity check on returned size
1104        if (ssize_t(writtenSize) <= 0) {
1105            // The callback is done filling buffers
1106            // Keep this thread going to handle timed events and
1107            // still try to get more data in intervals of WAIT_PERIOD_MS
1108            // but don't just loop and block the CPU, so wait
1109            usleep(WAIT_PERIOD_MS*1000);
1110            break;
1111        }
1112        if (writtenSize > reqSize) writtenSize = reqSize;
1113
1114        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
1115            // 8 to 16 bit conversion
1116            const int8_t *src = audioBuffer.i8 + writtenSize-1;
1117            int count = writtenSize;
1118            int16_t *dst = audioBuffer.i16 + writtenSize-1;
1119            while(count--) {
1120                *dst-- = (int16_t)(*src--^0x80) << 8;
1121            }
1122            writtenSize <<= 1;
1123        }
1124
1125        audioBuffer.size = writtenSize;
1126        // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1127        // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sampel size of
1128        // 16 bit.
1129        audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1130
1131        frames -= audioBuffer.frameCount;
1132
1133        releaseBuffer(&audioBuffer);
1134    }
1135    while (frames);
1136
1137    if (frames == 0) {
1138        mRemainingFrames = mNotificationFramesAct;
1139    } else {
1140        mRemainingFrames = frames;
1141    }
1142    return true;
1143}
1144
1145// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1146// the IAudioTrack and IMemory in case they are recreated here.
1147// If the IAudioTrack is successfully restored, the cblk pointer is updated
1148status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1149{
1150    status_t result;
1151
1152    if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
1153        LOGW("dead IAudioTrack, creating a new one from %s",
1154             fromStart ? "start()" : "obtainBuffer()");
1155
1156        // signal old cblk condition so that other threads waiting for available buffers stop
1157        // waiting now
1158        cblk->cv.broadcast();
1159        cblk->lock.unlock();
1160
1161        // if the new IAudioTrack is created, createTrack_l() will modify the
1162        // following member variables: mAudioTrack, mCblkMemory and mCblk.
1163        // It will also delete the strong references on previous IAudioTrack and IMemory
1164        result = createTrack_l(mStreamType,
1165                               cblk->sampleRate,
1166                               mFormat,
1167                               mChannelCount,
1168                               mFrameCount,
1169                               mFlags,
1170                               mSharedBuffer,
1171                               getOutput_l(),
1172                               false);
1173
1174        if (result == NO_ERROR) {
1175            // restore write index and set other indexes to reflect empty buffer status
1176            mCblk->user = cblk->user;
1177            mCblk->server = cblk->user;
1178            mCblk->userBase = cblk->user;
1179            mCblk->serverBase = cblk->user;
1180            // restore loop: this is not guaranteed to succeed if new frame count is not
1181            // compatible with loop length
1182            setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
1183            if (!fromStart) {
1184                mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1185            }
1186            if (mActive) {
1187                result = mAudioTrack->start();
1188            }
1189            if (fromStart && result == NO_ERROR) {
1190                mNewPosition = mCblk->server + mUpdatePeriod;
1191            }
1192        }
1193        if (result != NO_ERROR) {
1194            mActive = false;
1195        }
1196
1197        // signal old cblk condition for other threads waiting for restore completion
1198        android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
1199        cblk->cv.broadcast();
1200    } else {
1201        if (!(cblk->flags & CBLK_RESTORED_MSK)) {
1202            LOGW("dead IAudioTrack, waiting for a new one");
1203            mLock.unlock();
1204            result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1205            cblk->lock.unlock();
1206            mLock.lock();
1207        } else {
1208            LOGW("dead IAudioTrack, already restored");
1209            result = NO_ERROR;
1210            cblk->lock.unlock();
1211        }
1212        if (result != NO_ERROR || mActive == 0) {
1213            result = status_t(STOPPED);
1214        }
1215    }
1216    LOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1217         result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1218
1219    if (result == NO_ERROR) {
1220        // from now on we switch to the newly created cblk
1221        cblk = mCblk;
1222    }
1223    cblk->lock.lock();
1224
1225    LOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result);
1226
1227    return result;
1228}
1229
1230status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1231{
1232
1233    const size_t SIZE = 256;
1234    char buffer[SIZE];
1235    String8 result;
1236
1237    result.append(" AudioTrack::dump\n");
1238    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
1239    result.append(buffer);
1240    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mCblk->frameCount);
1241    result.append(buffer);
1242    snprintf(buffer, 255, "  sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
1243    result.append(buffer);
1244    snprintf(buffer, 255, "  active(%d), latency (%d)\n", mActive, mLatency);
1245    result.append(buffer);
1246    ::write(fd, result.string(), result.size());
1247    return NO_ERROR;
1248}
1249
1250// =========================================================================
1251
1252AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1253    : Thread(bCanCallJava), mReceiver(receiver)
1254{
1255}
1256
1257bool AudioTrack::AudioTrackThread::threadLoop()
1258{
1259    return mReceiver.processAudioBuffer(this);
1260}
1261
1262status_t AudioTrack::AudioTrackThread::readyToRun()
1263{
1264    return NO_ERROR;
1265}
1266
1267void AudioTrack::AudioTrackThread::onFirstRef()
1268{
1269}
1270
1271// =========================================================================
1272
1273
1274audio_track_cblk_t::audio_track_cblk_t()
1275    : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1276    userBase(0), serverBase(0), buffers(0), frameCount(0),
1277    loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
1278    sendLevel(0), flags(0)
1279{
1280}
1281
1282uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1283{
1284    uint32_t u = this->user;
1285
1286    u += frameCount;
1287    // Ensure that user is never ahead of server for AudioRecord
1288    if (flags & CBLK_DIRECTION_MSK) {
1289        // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1290        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1291            bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1292        }
1293    } else if (u > this->server) {
1294        LOGW("stepServer occured after track reset");
1295        u = this->server;
1296    }
1297
1298    if (u >= userBase + this->frameCount) {
1299        userBase += this->frameCount;
1300    }
1301
1302    this->user = u;
1303
1304    // Clear flow control error condition as new data has been written/read to/from buffer.
1305    if (flags & CBLK_UNDERRUN_MSK) {
1306        android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
1307    }
1308
1309    return u;
1310}
1311
1312bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1313{
1314    if (!tryLock()) {
1315        LOGW("stepServer() could not lock cblk");
1316        return false;
1317    }
1318
1319    uint32_t s = this->server;
1320
1321    s += frameCount;
1322    if (flags & CBLK_DIRECTION_MSK) {
1323        // Mark that we have read the first buffer so that next time stepUser() is called
1324        // we switch to normal obtainBuffer() timeout period
1325        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
1326            bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
1327        }
1328        // It is possible that we receive a flush()
1329        // while the mixer is processing a block: in this case,
1330        // stepServer() is called After the flush() has reset u & s and
1331        // we have s > u
1332        if (s > this->user) {
1333            LOGW("stepServer occured after track reset");
1334            s = this->user;
1335        }
1336    }
1337
1338    if (s >= loopEnd) {
1339        LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1340        s = loopStart;
1341        if (--loopCount == 0) {
1342            loopEnd = UINT_MAX;
1343            loopStart = UINT_MAX;
1344        }
1345    }
1346    if (s >= serverBase + this->frameCount) {
1347        serverBase += this->frameCount;
1348    }
1349
1350    this->server = s;
1351
1352    if (!(flags & CBLK_INVALID_MSK)) {
1353        cv.signal();
1354    }
1355    lock.unlock();
1356    return true;
1357}
1358
1359void* audio_track_cblk_t::buffer(uint32_t offset) const
1360{
1361    return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
1362}
1363
1364uint32_t audio_track_cblk_t::framesAvailable()
1365{
1366    Mutex::Autolock _l(lock);
1367    return framesAvailable_l();
1368}
1369
1370uint32_t audio_track_cblk_t::framesAvailable_l()
1371{
1372    uint32_t u = this->user;
1373    uint32_t s = this->server;
1374
1375    if (flags & CBLK_DIRECTION_MSK) {
1376        uint32_t limit = (s < loopStart) ? s : loopStart;
1377        return limit + frameCount - u;
1378    } else {
1379        return frameCount + u - s;
1380    }
1381}
1382
1383uint32_t audio_track_cblk_t::framesReady()
1384{
1385    uint32_t u = this->user;
1386    uint32_t s = this->server;
1387
1388    if (flags & CBLK_DIRECTION_MSK) {
1389        if (u < loopEnd) {
1390            return u - s;
1391        } else {
1392            // do not block on mutex shared with client on AudioFlinger side
1393            if (!tryLock()) {
1394                LOGW("framesReady() could not lock cblk");
1395                return 0;
1396            }
1397            uint32_t frames = UINT_MAX;
1398            if (loopCount >= 0) {
1399                frames = (loopEnd - loopStart)*loopCount + u - s;
1400            }
1401            lock.unlock();
1402            return frames;
1403        }
1404    } else {
1405        return s - u;
1406    }
1407}
1408
1409bool audio_track_cblk_t::tryLock()
1410{
1411    // the code below simulates lock-with-timeout
1412    // we MUST do this to protect the AudioFlinger server
1413    // as this lock is shared with the client.
1414    status_t err;
1415
1416    err = lock.tryLock();
1417    if (err == -EBUSY) { // just wait a bit
1418        usleep(1000);
1419        err = lock.tryLock();
1420    }
1421    if (err != NO_ERROR) {
1422        // probably, the client just died.
1423        return false;
1424    }
1425    return true;
1426}
1427
1428// -------------------------------------------------------------------------
1429
1430}; // namespace android
1431
1432