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