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