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