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