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