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