AudioTrack.cpp revision b07c28b90b2d2793be2b8878d813b607f3eebbb7
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/MemoryDealer.h>
36#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
38#include <utils/Timers.h>
39#include <cutils/atomic.h>
40
41#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
42#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
43
44namespace android {
45
46// ---------------------------------------------------------------------------
47
48AudioTrack::AudioTrack()
49    : mStatus(NO_INIT)
50{
51}
52
53AudioTrack::AudioTrack(
54        int streamType,
55        uint32_t sampleRate,
56        int format,
57        int channelCount,
58        int frameCount,
59        uint32_t flags,
60        callback_t cbf,
61        void* user,
62        int notificationFrames)
63    : mStatus(NO_INIT)
64{
65    mStatus = set(streamType, sampleRate, format, channelCount,
66            frameCount, flags, cbf, user, notificationFrames, 0);
67}
68
69AudioTrack::AudioTrack(
70        int streamType,
71        uint32_t sampleRate,
72        int format,
73        int channelCount,
74        const sp<IMemory>& sharedBuffer,
75        uint32_t flags,
76        callback_t cbf,
77        void* user,
78        int notificationFrames)
79    : mStatus(NO_INIT)
80{
81    mStatus = set(streamType, sampleRate, format, channelCount,
82            0, flags, cbf, user, notificationFrames, sharedBuffer);
83}
84
85AudioTrack::~AudioTrack()
86{
87    LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
88
89    if (mStatus == NO_ERROR) {
90        // Make sure that callback function exits in the case where
91        // it is looping on buffer full condition in obtainBuffer().
92        // Otherwise the callback thread will never exit.
93        stop();
94        if (mAudioTrackThread != 0) {
95            mAudioTrackThread->requestExitAndWait();
96            mAudioTrackThread.clear();
97        }
98        mAudioTrack.clear();
99        IPCThreadState::self()->flushCommands();
100    }
101}
102
103status_t AudioTrack::set(
104        int streamType,
105        uint32_t sampleRate,
106        int format,
107        int channelCount,
108        int frameCount,
109        uint32_t flags,
110        callback_t cbf,
111        void* user,
112        int notificationFrames,
113        const sp<IMemory>& sharedBuffer,
114        bool threadCanCallJava)
115{
116
117    LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
118
119    if (mAudioTrack != 0) {
120        LOGE("Track already in use");
121        return INVALID_OPERATION;
122    }
123
124    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
125    if (audioFlinger == 0) {
126       LOGE("Could not get audioflinger");
127       return NO_INIT;
128    }
129    int afSampleRate;
130    if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
131        return NO_INIT;
132    }
133    int afFrameCount;
134    if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
135        return NO_INIT;
136    }
137    uint32_t afLatency;
138    if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
139        return NO_INIT;
140    }
141
142    // handle default values first.
143    if (streamType == AudioSystem::DEFAULT) {
144        streamType = AudioSystem::MUSIC;
145    }
146    if (sampleRate == 0) {
147        sampleRate = afSampleRate;
148    }
149    // these below should probably come from the audioFlinger too...
150    if (format == 0) {
151        format = AudioSystem::PCM_16_BIT;
152    }
153    if (channelCount == 0) {
154        channelCount = 2;
155    }
156
157    // validate parameters
158    if (((format != AudioSystem::PCM_8_BIT) || sharedBuffer != 0) &&
159        (format != AudioSystem::PCM_16_BIT)) {
160        LOGE("Invalid format");
161        return BAD_VALUE;
162    }
163    if (channelCount != 1 && channelCount != 2) {
164        LOGE("Invalid channel number");
165        return BAD_VALUE;
166    }
167
168    // Ensure that buffer depth covers at least audio hardware latency
169    uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
170    if (minBufCount < 2) minBufCount = 2;
171
172    // When playing from shared buffer, playback will start even if last audioflinger
173    // block is partly filled.
174    if (sharedBuffer != 0 && minBufCount > 1) {
175        minBufCount--;
176    }
177
178    int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
179
180    if (sharedBuffer == 0) {
181        if (frameCount == 0) {
182            frameCount = minFrameCount;
183        }
184        if (notificationFrames == 0) {
185            notificationFrames = frameCount/2;
186        }
187        // Make sure that application is notified with sufficient margin
188        // before underrun
189        if (notificationFrames > frameCount/2) {
190            notificationFrames = frameCount/2;
191        }
192    } else {
193        // Ensure that buffer alignment matches channelcount
194        if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
195            LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
196            return BAD_VALUE;
197        }
198        frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
199    }
200
201    if (frameCount < minFrameCount) {
202      LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
203      return BAD_VALUE;
204    }
205
206    // create the track
207    status_t status;
208    sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
209                streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status);
210
211    if (track == 0) {
212        LOGE("AudioFlinger could not create track, status: %d", status);
213        return status;
214    }
215    sp<IMemory> cblk = track->getCblk();
216    if (cblk == 0) {
217        LOGE("Could not get control block");
218        return NO_INIT;
219    }
220    if (cbf != 0) {
221        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
222        if (mAudioTrackThread == 0) {
223          LOGE("Could not create callback thread");
224          return NO_INIT;
225        }
226    }
227
228    mStatus = NO_ERROR;
229
230    mAudioTrack = track;
231    mCblkMemory = cblk;
232    mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
233    mCblk->out = 1;
234    // Update buffer size in case it has been limited by AudioFlinger during track creation
235    mFrameCount = mCblk->frameCount;
236    if (sharedBuffer == 0) {
237        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
238    } else {
239        mCblk->buffers = sharedBuffer->pointer();
240         // Force buffer full condition as data is already present in shared memory
241        mCblk->stepUser(mFrameCount);
242    }
243    mCblk->volume[0] = mCblk->volume[1] = 0x1000;
244    mVolume[LEFT] = 1.0f;
245    mVolume[RIGHT] = 1.0f;
246    mStreamType = streamType;
247    mFormat = format;
248    mChannelCount = channelCount;
249    mSharedBuffer = sharedBuffer;
250    mMuted = false;
251    mActive = 0;
252    mCbf = cbf;
253    mNotificationFrames = notificationFrames;
254    mRemainingFrames = notificationFrames;
255    mUserData = user;
256    mLatency = afLatency + (1000*mFrameCount) / sampleRate;
257    mLoopCount = 0;
258    mMarkerPosition = 0;
259    mMarkerReached = false;
260    mNewPosition = 0;
261    mUpdatePeriod = 0;
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 mFrameCount;
296}
297
298int AudioTrack::frameSize() const
299{
300    return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
301}
302
303sp<IMemory>& AudioTrack::sharedBuffer()
304{
305    return mSharedBuffer;
306}
307
308// -------------------------------------------------------------------------
309
310void AudioTrack::start()
311{
312    sp<AudioTrackThread> t = mAudioTrackThread;
313
314    LOGV("start %p", this);
315    if (t != 0) {
316        if (t->exitPending()) {
317            if (t->requestExitAndWait() == WOULD_BLOCK) {
318                LOGE("AudioTrack::start called from thread");
319                return;
320            }
321        }
322        t->mLock.lock();
323     }
324
325    if (android_atomic_or(1, &mActive) == 0) {
326        mNewPosition = mCblk->server + mUpdatePeriod;
327        mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
328        mCblk->waitTimeMs = 0;
329        if (t != 0) {
330           t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
331        } else {
332            setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
333        }
334        mAudioTrack->start();
335    }
336
337    if (t != 0) {
338        t->mLock.unlock();
339    }
340}
341
342void AudioTrack::stop()
343{
344    sp<AudioTrackThread> t = mAudioTrackThread;
345
346    LOGV("stop %p", this);
347    if (t != 0) {
348        t->mLock.lock();
349    }
350
351    if (android_atomic_and(~1, &mActive) == 1) {
352        mCblk->cv.signal();
353        mAudioTrack->stop();
354        // Cancel loops (If we are in the middle of a loop, playback
355        // would not stop until loopCount reaches 0).
356        setLoop(0, 0, 0);
357        // the playback head position will reset to 0, so if a marker is set, we need
358        // to activate it again
359        mMarkerReached = false;
360        // Force flush if a shared buffer is used otherwise audioflinger
361        // will not stop before end of buffer is reached.
362        if (mSharedBuffer != 0) {
363            flush();
364        }
365        if (t != 0) {
366            t->requestExit();
367        } else {
368            setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
369        }
370    }
371
372    if (t != 0) {
373        t->mLock.unlock();
374    }
375}
376
377bool AudioTrack::stopped() const
378{
379    return !mActive;
380}
381
382void AudioTrack::flush()
383{
384    LOGV("flush");
385
386    // clear playback marker and periodic update counter
387    mMarkerPosition = 0;
388    mMarkerReached = false;
389    mUpdatePeriod = 0;
390
391
392    if (!mActive) {
393        mAudioTrack->flush();
394        // Release AudioTrack callback thread in case it was waiting for new buffers
395        // in AudioTrack::obtainBuffer()
396        mCblk->cv.signal();
397    }
398}
399
400void AudioTrack::pause()
401{
402    LOGV("pause");
403    if (android_atomic_and(~1, &mActive) == 1) {
404        mActive = 0;
405        mAudioTrack->pause();
406    }
407}
408
409void AudioTrack::mute(bool e)
410{
411    mAudioTrack->mute(e);
412    mMuted = e;
413}
414
415bool AudioTrack::muted() const
416{
417    return mMuted;
418}
419
420void AudioTrack::setVolume(float left, float right)
421{
422    mVolume[LEFT] = left;
423    mVolume[RIGHT] = right;
424
425    // write must be atomic
426    mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
427}
428
429void AudioTrack::getVolume(float* left, float* right)
430{
431    *left  = mVolume[LEFT];
432    *right = mVolume[RIGHT];
433}
434
435status_t AudioTrack::setSampleRate(int rate)
436{
437    int afSamplingRate;
438
439    if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
440        return NO_INIT;
441    }
442    // Resampler implementation limits input sampling rate to 2 x output sampling rate.
443    if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
444
445    mCblk->sampleRate = rate;
446    return NO_ERROR;
447}
448
449uint32_t AudioTrack::getSampleRate()
450{
451    return mCblk->sampleRate;
452}
453
454status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
455{
456    audio_track_cblk_t* cblk = mCblk;
457
458
459    Mutex::Autolock _l(cblk->lock);
460
461    if (loopCount == 0) {
462        cblk->loopStart = UINT_MAX;
463        cblk->loopEnd = UINT_MAX;
464        cblk->loopCount = 0;
465        mLoopCount = 0;
466        return NO_ERROR;
467    }
468
469    if (loopStart >= loopEnd ||
470        loopEnd - loopStart > mFrameCount) {
471        LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
472        return BAD_VALUE;
473    }
474
475    if ((mSharedBuffer != 0) && (loopEnd   > mFrameCount)) {
476        LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
477            loopStart, loopEnd, mFrameCount);
478        return BAD_VALUE;
479    }
480
481    cblk->loopStart = loopStart;
482    cblk->loopEnd = loopEnd;
483    cblk->loopCount = loopCount;
484    mLoopCount = loopCount;
485
486    return NO_ERROR;
487}
488
489status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
490{
491    if (loopStart != 0) {
492        *loopStart = mCblk->loopStart;
493    }
494    if (loopEnd != 0) {
495        *loopEnd = mCblk->loopEnd;
496    }
497    if (loopCount != 0) {
498        if (mCblk->loopCount < 0) {
499            *loopCount = -1;
500        } else {
501            *loopCount = mCblk->loopCount;
502        }
503    }
504
505    return NO_ERROR;
506}
507
508status_t AudioTrack::setMarkerPosition(uint32_t marker)
509{
510    if (mCbf == 0) return INVALID_OPERATION;
511
512    mMarkerPosition = marker;
513    mMarkerReached = false;
514
515    return NO_ERROR;
516}
517
518status_t AudioTrack::getMarkerPosition(uint32_t *marker)
519{
520    if (marker == 0) return BAD_VALUE;
521
522    *marker = mMarkerPosition;
523
524    return NO_ERROR;
525}
526
527status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
528{
529    if (mCbf == 0) return INVALID_OPERATION;
530
531    uint32_t curPosition;
532    getPosition(&curPosition);
533    mNewPosition = curPosition + updatePeriod;
534    mUpdatePeriod = updatePeriod;
535
536    return NO_ERROR;
537}
538
539status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
540{
541    if (updatePeriod == 0) return BAD_VALUE;
542
543    *updatePeriod = mUpdatePeriod;
544
545    return NO_ERROR;
546}
547
548status_t AudioTrack::setPosition(uint32_t position)
549{
550    Mutex::Autolock _l(mCblk->lock);
551
552    if (!stopped()) return INVALID_OPERATION;
553
554    if (position > mCblk->user) return BAD_VALUE;
555
556    mCblk->server = position;
557    mCblk->forceReady = 1;
558
559    return NO_ERROR;
560}
561
562status_t AudioTrack::getPosition(uint32_t *position)
563{
564    if (position == 0) return BAD_VALUE;
565
566    *position = mCblk->server;
567
568    return NO_ERROR;
569}
570
571status_t AudioTrack::reload()
572{
573    if (!stopped()) return INVALID_OPERATION;
574
575    flush();
576
577    mCblk->stepUser(mFrameCount);
578
579    return NO_ERROR;
580}
581
582// -------------------------------------------------------------------------
583
584status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
585{
586    int active;
587    int timeout = 0;
588    status_t result;
589    audio_track_cblk_t* cblk = mCblk;
590    uint32_t framesReq = audioBuffer->frameCount;
591    uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
592
593    audioBuffer->frameCount  = 0;
594    audioBuffer->size = 0;
595
596    uint32_t framesAvail = cblk->framesAvailable();
597
598    if (framesAvail == 0) {
599        Mutex::Autolock _l(cblk->lock);
600        goto start_loop_here;
601        while (framesAvail == 0) {
602            active = mActive;
603            if (UNLIKELY(!active)) {
604                LOGV("Not active and NO_MORE_BUFFERS");
605                return NO_MORE_BUFFERS;
606            }
607            if (UNLIKELY(!waitCount))
608                return WOULD_BLOCK;
609            timeout = 0;
610            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
611            if (__builtin_expect(result!=NO_ERROR, false)) {
612                cblk->waitTimeMs += waitTimeMs;
613                if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
614                    // timing out when a loop has been set and we have already written upto loop end
615                    // is a normal condition: no need to wake AudioFlinger up.
616                    if (cblk->user < cblk->loopEnd) {
617                        LOGW(   "obtainBuffer timed out (is the CPU pegged?) %p "
618                                "user=%08x, server=%08x", this, cblk->user, cblk->server);
619                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
620                        cblk->lock.unlock();
621                        mAudioTrack->start();
622                        cblk->lock.lock();
623                        timeout = 1;
624                    }
625                    cblk->waitTimeMs = 0;
626                }
627
628                if (--waitCount == 0) {
629                    return TIMED_OUT;
630                }
631            }
632            // read the server count again
633        start_loop_here:
634            framesAvail = cblk->framesAvailable_l();
635        }
636    }
637
638    cblk->waitTimeMs = 0;
639
640    if (framesReq > framesAvail) {
641        framesReq = framesAvail;
642    }
643
644    uint32_t u = cblk->user;
645    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
646
647    if (u + framesReq > bufferEnd) {
648        framesReq = bufferEnd - u;
649    }
650
651    LOGW_IF(timeout,
652        "*** SERIOUS WARNING *** obtainBuffer() timed out "
653        "but didn't need to be locked. We recovered, but "
654        "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
655
656    audioBuffer->flags       = mMuted ? Buffer::MUTE : 0;
657    audioBuffer->channelCount= mChannelCount;
658    audioBuffer->format      = AudioSystem::PCM_16_BIT;
659    audioBuffer->frameCount  = framesReq;
660    audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
661    audioBuffer->raw         = (int8_t *)cblk->buffer(u);
662    active = mActive;
663    return active ? status_t(NO_ERROR) : status_t(STOPPED);
664}
665
666void AudioTrack::releaseBuffer(Buffer* audioBuffer)
667{
668    audio_track_cblk_t* cblk = mCblk;
669    cblk->stepUser(audioBuffer->frameCount);
670}
671
672// -------------------------------------------------------------------------
673
674ssize_t AudioTrack::write(const void* buffer, size_t userSize)
675{
676
677    if (mSharedBuffer != 0) return INVALID_OPERATION;
678
679    if (ssize_t(userSize) < 0) {
680        // sanity-check. user is most-likely passing an error code.
681        LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
682                buffer, userSize, userSize);
683        return BAD_VALUE;
684    }
685
686    LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
687
688    ssize_t written = 0;
689    const int8_t *src = (const int8_t *)buffer;
690    Buffer audioBuffer;
691
692    do {
693        audioBuffer.frameCount = userSize/mChannelCount;
694        if (mFormat == AudioSystem::PCM_16_BIT) {
695            audioBuffer.frameCount >>= 1;
696        }
697        // Calling obtainBuffer() with a negative wait count causes
698        // an (almost) infinite wait time.
699        status_t err = obtainBuffer(&audioBuffer, -1);
700        if (err < 0) {
701            // out of buffers, return #bytes written
702            if (err == status_t(NO_MORE_BUFFERS))
703                break;
704            return ssize_t(err);
705        }
706
707        size_t toWrite;
708        if (mFormat == AudioSystem::PCM_8_BIT) {
709            // Divide capacity by 2 to take expansion into account
710            toWrite = audioBuffer.size>>1;
711            // 8 to 16 bit conversion
712            int count = toWrite;
713            int16_t *dst = (int16_t *)(audioBuffer.i8);
714            while(count--) {
715                *dst++ = (int16_t)(*src++^0x80) << 8;
716            }
717        }else {
718            toWrite = audioBuffer.size;
719            memcpy(audioBuffer.i8, src, toWrite);
720            src += toWrite;
721        }
722        userSize -= toWrite;
723        written += toWrite;
724
725        releaseBuffer(&audioBuffer);
726    } while (userSize);
727
728    return written;
729}
730
731// -------------------------------------------------------------------------
732
733bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
734{
735    Buffer audioBuffer;
736    uint32_t frames;
737    size_t writtenSize;
738
739    // Manage underrun callback
740    if (mActive && (mCblk->framesReady() == 0)) {
741        LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
742        if (mCblk->flowControlFlag == 0) {
743            mCbf(EVENT_UNDERRUN, mUserData, 0);
744            if (mCblk->server == mCblk->frameCount) {
745                mCbf(EVENT_BUFFER_END, mUserData, 0);
746            }
747            mCblk->flowControlFlag = 1;
748            if (mSharedBuffer != 0) return false;
749        }
750    }
751
752    // Manage loop end callback
753    while (mLoopCount > mCblk->loopCount) {
754        int loopCount = -1;
755        mLoopCount--;
756        if (mLoopCount >= 0) loopCount = mLoopCount;
757
758        mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
759    }
760
761    // Manage marker callback
762    if (!mMarkerReached && (mMarkerPosition > 0)) {
763        if (mCblk->server >= mMarkerPosition) {
764            mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
765            mMarkerReached = true;
766        }
767    }
768
769    // Manage new position callback
770    if(mUpdatePeriod > 0) {
771        while (mCblk->server >= mNewPosition) {
772            mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
773            mNewPosition += mUpdatePeriod;
774        }
775    }
776
777    // If Shared buffer is used, no data is requested from client.
778    if (mSharedBuffer != 0) {
779        frames = 0;
780    } else {
781        frames = mRemainingFrames;
782    }
783
784    do {
785
786        audioBuffer.frameCount = frames;
787
788        // Calling obtainBuffer() with a wait count of 1
789        // limits wait time to WAIT_PERIOD_MS. This prevents from being
790        // stuck here not being able to handle timed events (position, markers, loops).
791        status_t err = obtainBuffer(&audioBuffer, 1);
792        if (err < NO_ERROR) {
793            if (err != TIMED_OUT) {
794                LOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
795                return false;
796            }
797            break;
798        }
799        if (err == status_t(STOPPED)) return false;
800
801        // Divide buffer size by 2 to take into account the expansion
802        // due to 8 to 16 bit conversion: the callback must fill only half
803        // of the destination buffer
804        if (mFormat == AudioSystem::PCM_8_BIT) {
805            audioBuffer.size >>= 1;
806        }
807
808        size_t reqSize = audioBuffer.size;
809        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
810        writtenSize = audioBuffer.size;
811
812        // Sanity check on returned size
813        if (ssize_t(writtenSize) <= 0) {
814            // The callback is done filling buffers
815            // Keep this thread going to handle timed events and
816            // still try to get more data in intervals of WAIT_PERIOD_MS
817            // but don't just loop and block the CPU, so wait
818            usleep(WAIT_PERIOD_MS*1000);
819            break;
820        }
821        if (writtenSize > reqSize) writtenSize = reqSize;
822
823        if (mFormat == AudioSystem::PCM_8_BIT) {
824            // 8 to 16 bit conversion
825            const int8_t *src = audioBuffer.i8 + writtenSize-1;
826            int count = writtenSize;
827            int16_t *dst = audioBuffer.i16 + writtenSize-1;
828            while(count--) {
829                *dst-- = (int16_t)(*src--^0x80) << 8;
830            }
831            writtenSize <<= 1;
832        }
833
834        audioBuffer.size = writtenSize;
835        audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
836        frames -= audioBuffer.frameCount;
837
838        releaseBuffer(&audioBuffer);
839    }
840    while (frames);
841
842    if (frames == 0) {
843        mRemainingFrames = mNotificationFrames;
844    } else {
845        mRemainingFrames = frames;
846    }
847    return true;
848}
849
850status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
851{
852
853    const size_t SIZE = 256;
854    char buffer[SIZE];
855    String8 result;
856
857    result.append(" AudioTrack::dump\n");
858    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
859    result.append(buffer);
860    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
861    result.append(buffer);
862    snprintf(buffer, 255, "  sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
863    result.append(buffer);
864    snprintf(buffer, 255, "  active(%d), latency (%d)\n", mActive, mLatency);
865    result.append(buffer);
866    ::write(fd, result.string(), result.size());
867    return NO_ERROR;
868}
869
870// =========================================================================
871
872AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
873    : Thread(bCanCallJava), mReceiver(receiver)
874{
875}
876
877bool AudioTrack::AudioTrackThread::threadLoop()
878{
879    return mReceiver.processAudioBuffer(this);
880}
881
882status_t AudioTrack::AudioTrackThread::readyToRun()
883{
884    return NO_ERROR;
885}
886
887void AudioTrack::AudioTrackThread::onFirstRef()
888{
889}
890
891// =========================================================================
892
893audio_track_cblk_t::audio_track_cblk_t()
894    : lock(Mutex::SHARED), user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
895    loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
896{
897}
898
899uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
900{
901    uint32_t u = this->user;
902
903    u += frameCount;
904    // Ensure that user is never ahead of server for AudioRecord
905    if (out) {
906        // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
907        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
908            bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
909        }
910    } else if (u > this->server) {
911        LOGW("stepServer occured after track reset");
912        u = this->server;
913    }
914
915    if (u >= userBase + this->frameCount) {
916        userBase += this->frameCount;
917    }
918
919    this->user = u;
920
921    // Clear flow control error condition as new data has been written/read to/from buffer.
922    flowControlFlag = 0;
923
924    return u;
925}
926
927bool audio_track_cblk_t::stepServer(uint32_t frameCount)
928{
929    // the code below simulates lock-with-timeout
930    // we MUST do this to protect the AudioFlinger server
931    // as this lock is shared with the client.
932    status_t err;
933
934    err = lock.tryLock();
935    if (err == -EBUSY) { // just wait a bit
936        usleep(1000);
937        err = lock.tryLock();
938    }
939    if (err != NO_ERROR) {
940        // probably, the client just died.
941        return false;
942    }
943
944    uint32_t s = this->server;
945
946    s += frameCount;
947    if (out) {
948        // Mark that we have read the first buffer so that next time stepUser() is called
949        // we switch to normal obtainBuffer() timeout period
950        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
951            bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
952        }
953        // It is possible that we receive a flush()
954        // while the mixer is processing a block: in this case,
955        // stepServer() is called After the flush() has reset u & s and
956        // we have s > u
957        if (s > this->user) {
958            LOGW("stepServer occured after track reset");
959            s = this->user;
960        }
961    }
962
963    if (s >= loopEnd) {
964        LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
965        s = loopStart;
966        if (--loopCount == 0) {
967            loopEnd = UINT_MAX;
968            loopStart = UINT_MAX;
969        }
970    }
971    if (s >= serverBase + this->frameCount) {
972        serverBase += this->frameCount;
973    }
974
975    this->server = s;
976
977    cv.signal();
978    lock.unlock();
979    return true;
980}
981
982void* audio_track_cblk_t::buffer(uint32_t offset) const
983{
984    return (int16_t *)this->buffers + (offset-userBase)*this->channels;
985}
986
987uint32_t audio_track_cblk_t::framesAvailable()
988{
989    Mutex::Autolock _l(lock);
990    return framesAvailable_l();
991}
992
993uint32_t audio_track_cblk_t::framesAvailable_l()
994{
995    uint32_t u = this->user;
996    uint32_t s = this->server;
997
998    if (out) {
999        uint32_t limit = (s < loopStart) ? s : loopStart;
1000        return limit + frameCount - u;
1001    } else {
1002        return frameCount + u - s;
1003    }
1004}
1005
1006uint32_t audio_track_cblk_t::framesReady()
1007{
1008    uint32_t u = this->user;
1009    uint32_t s = this->server;
1010
1011    if (out) {
1012        if (u < loopEnd) {
1013            return u - s;
1014        } else {
1015            Mutex::Autolock _l(lock);
1016            if (loopCount >= 0) {
1017                return (loopEnd - loopStart)*loopCount + u - s;
1018            } else {
1019                return UINT_MAX;
1020            }
1021        }
1022    } else {
1023        return s - u;
1024    }
1025}
1026
1027// -------------------------------------------------------------------------
1028
1029}; // namespace android
1030
1031