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