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