Home | History | Annotate | Download | only in libmedia
      1 /*
      2  * Copyright (C) 2007 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "AudioTrackShared"
     18 //#define LOG_NDEBUG 0
     19 
     20 #include <private/media/AudioTrackShared.h>
     21 #include <utils/Log.h>
     22 
     23 #include <linux/futex.h>
     24 #include <sys/syscall.h>
     25 
     26 namespace android {
     27 
     28 // used to clamp a value to size_t.  TODO: move to another file.
     29 template <typename T>
     30 size_t clampToSize(T x) {
     31     return sizeof(T) > sizeof(size_t) && x > (T) SIZE_MAX ? SIZE_MAX : x < 0 ? 0 : (size_t) x;
     32 }
     33 
     34 // incrementSequence is used to determine the next sequence value
     35 // for the loop and position sequence counters.  It should return
     36 // a value between "other" + 1 and "other" + INT32_MAX, the choice of
     37 // which needs to be the "least recently used" sequence value for "self".
     38 // In general, this means (new_self) returned is max(self, other) + 1.
     39 
     40 static uint32_t incrementSequence(uint32_t self, uint32_t other) {
     41     int32_t diff = self - other;
     42     if (diff >= 0 && diff < INT32_MAX) {
     43         return self + 1; // we're already ahead of other.
     44     }
     45     return other + 1; // we're behind, so move just ahead of other.
     46 }
     47 
     48 audio_track_cblk_t::audio_track_cblk_t()
     49     : mServer(0), mFutex(0), mMinimum(0),
     50     mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0), mFlags(0)
     51 {
     52     memset(&u, 0, sizeof(u));
     53 }
     54 
     55 // ---------------------------------------------------------------------------
     56 
     57 Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
     58         bool isOut, bool clientInServer)
     59     : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
     60       mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
     61       mIsShutdown(false), mUnreleased(0)
     62 {
     63 }
     64 
     65 // ---------------------------------------------------------------------------
     66 
     67 ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
     68         size_t frameSize, bool isOut, bool clientInServer)
     69     : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer), mEpoch(0)
     70 {
     71 }
     72 
     73 const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
     74 const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
     75 
     76 #define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
     77 
     78 // To facilitate quicker recovery from server failure, this value limits the timeout per each futex
     79 // wait.  However it does not protect infinite timeouts.  If defined to be zero, there is no limit.
     80 // FIXME May not be compatible with audio tunneling requirements where timeout should be in the
     81 // order of minutes.
     82 #define MAX_SEC    5
     83 
     84 status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
     85         struct timespec *elapsed)
     86 {
     87     LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
     88     struct timespec total;          // total elapsed time spent waiting
     89     total.tv_sec = 0;
     90     total.tv_nsec = 0;
     91     bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
     92 
     93     status_t status;
     94     enum {
     95         TIMEOUT_ZERO,       // requested == NULL || *requested == 0
     96         TIMEOUT_INFINITE,   // *requested == infinity
     97         TIMEOUT_FINITE,     // 0 < *requested < infinity
     98         TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
     99     } timeout;
    100     if (requested == NULL) {
    101         timeout = TIMEOUT_ZERO;
    102     } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
    103         timeout = TIMEOUT_ZERO;
    104     } else if (requested->tv_sec == INT_MAX) {
    105         timeout = TIMEOUT_INFINITE;
    106     } else {
    107         timeout = TIMEOUT_FINITE;
    108         if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
    109             measure = true;
    110         }
    111     }
    112     struct timespec before;
    113     bool beforeIsValid = false;
    114     audio_track_cblk_t* cblk = mCblk;
    115     bool ignoreInitialPendingInterrupt = true;
    116     // check for shared memory corruption
    117     if (mIsShutdown) {
    118         status = NO_INIT;
    119         goto end;
    120     }
    121     for (;;) {
    122         int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
    123         // check for track invalidation by server, or server death detection
    124         if (flags & CBLK_INVALID) {
    125             ALOGV("Track invalidated");
    126             status = DEAD_OBJECT;
    127             goto end;
    128         }
    129         // check for obtainBuffer interrupted by client
    130         if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
    131             ALOGV("obtainBuffer() interrupted by client");
    132             status = -EINTR;
    133             goto end;
    134         }
    135         ignoreInitialPendingInterrupt = false;
    136         // compute number of frames available to write (AudioTrack) or read (AudioRecord)
    137         int32_t front;
    138         int32_t rear;
    139         if (mIsOut) {
    140             // The barrier following the read of mFront is probably redundant.
    141             // We're about to perform a conditional branch based on 'filled',
    142             // which will force the processor to observe the read of mFront
    143             // prior to allowing data writes starting at mRaw.
    144             // However, the processor may support speculative execution,
    145             // and be unable to undo speculative writes into shared memory.
    146             // The barrier will prevent such speculative execution.
    147             front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
    148             rear = cblk->u.mStreaming.mRear;
    149         } else {
    150             // On the other hand, this barrier is required.
    151             rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
    152             front = cblk->u.mStreaming.mFront;
    153         }
    154         ssize_t filled = rear - front;
    155         // pipe should not be overfull
    156         if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
    157             if (mIsOut) {
    158                 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
    159                         "shutting down", filled, mFrameCount);
    160                 mIsShutdown = true;
    161                 status = NO_INIT;
    162                 goto end;
    163             }
    164             // for input, sync up on overrun
    165             filled = 0;
    166             cblk->u.mStreaming.mFront = rear;
    167             (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
    168         }
    169         // don't allow filling pipe beyond the nominal size
    170         size_t avail = mIsOut ? mFrameCount - filled : filled;
    171         if (avail > 0) {
    172             // 'avail' may be non-contiguous, so return only the first contiguous chunk
    173             size_t part1;
    174             if (mIsOut) {
    175                 rear &= mFrameCountP2 - 1;
    176                 part1 = mFrameCountP2 - rear;
    177             } else {
    178                 front &= mFrameCountP2 - 1;
    179                 part1 = mFrameCountP2 - front;
    180             }
    181             if (part1 > avail) {
    182                 part1 = avail;
    183             }
    184             if (part1 > buffer->mFrameCount) {
    185                 part1 = buffer->mFrameCount;
    186             }
    187             buffer->mFrameCount = part1;
    188             buffer->mRaw = part1 > 0 ?
    189                     &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
    190             buffer->mNonContig = avail - part1;
    191             mUnreleased = part1;
    192             status = NO_ERROR;
    193             break;
    194         }
    195         struct timespec remaining;
    196         const struct timespec *ts;
    197         switch (timeout) {
    198         case TIMEOUT_ZERO:
    199             status = WOULD_BLOCK;
    200             goto end;
    201         case TIMEOUT_INFINITE:
    202             ts = NULL;
    203             break;
    204         case TIMEOUT_FINITE:
    205             timeout = TIMEOUT_CONTINUE;
    206             if (MAX_SEC == 0) {
    207                 ts = requested;
    208                 break;
    209             }
    210             // fall through
    211         case TIMEOUT_CONTINUE:
    212             // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
    213             if (!measure || requested->tv_sec < total.tv_sec ||
    214                     (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
    215                 status = TIMED_OUT;
    216                 goto end;
    217             }
    218             remaining.tv_sec = requested->tv_sec - total.tv_sec;
    219             if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
    220                 remaining.tv_nsec += 1000000000;
    221                 remaining.tv_sec++;
    222             }
    223             if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
    224                 remaining.tv_sec = MAX_SEC;
    225                 remaining.tv_nsec = 0;
    226             }
    227             ts = &remaining;
    228             break;
    229         default:
    230             LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
    231             ts = NULL;
    232             break;
    233         }
    234         int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
    235         if (!(old & CBLK_FUTEX_WAKE)) {
    236             if (measure && !beforeIsValid) {
    237                 clock_gettime(CLOCK_MONOTONIC, &before);
    238                 beforeIsValid = true;
    239             }
    240             errno = 0;
    241             (void) syscall(__NR_futex, &cblk->mFutex,
    242                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
    243             // update total elapsed time spent waiting
    244             if (measure) {
    245                 struct timespec after;
    246                 clock_gettime(CLOCK_MONOTONIC, &after);
    247                 total.tv_sec += after.tv_sec - before.tv_sec;
    248                 long deltaNs = after.tv_nsec - before.tv_nsec;
    249                 if (deltaNs < 0) {
    250                     deltaNs += 1000000000;
    251                     total.tv_sec--;
    252                 }
    253                 if ((total.tv_nsec += deltaNs) >= 1000000000) {
    254                     total.tv_nsec -= 1000000000;
    255                     total.tv_sec++;
    256                 }
    257                 before = after;
    258                 beforeIsValid = true;
    259             }
    260             switch (errno) {
    261             case 0:            // normal wakeup by server, or by binderDied()
    262             case EWOULDBLOCK:  // benign race condition with server
    263             case EINTR:        // wait was interrupted by signal or other spurious wakeup
    264             case ETIMEDOUT:    // time-out expired
    265                 // FIXME these error/non-0 status are being dropped
    266                 break;
    267             default:
    268                 status = errno;
    269                 ALOGE("%s unexpected error %s", __func__, strerror(status));
    270                 goto end;
    271             }
    272         }
    273     }
    274 
    275 end:
    276     if (status != NO_ERROR) {
    277         buffer->mFrameCount = 0;
    278         buffer->mRaw = NULL;
    279         buffer->mNonContig = 0;
    280         mUnreleased = 0;
    281     }
    282     if (elapsed != NULL) {
    283         *elapsed = total;
    284     }
    285     if (requested == NULL) {
    286         requested = &kNonBlocking;
    287     }
    288     if (measure) {
    289         ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
    290               requested->tv_sec, requested->tv_nsec / 1000000,
    291               total.tv_sec, total.tv_nsec / 1000000);
    292     }
    293     return status;
    294 }
    295 
    296 void ClientProxy::releaseBuffer(Buffer* buffer)
    297 {
    298     LOG_ALWAYS_FATAL_IF(buffer == NULL);
    299     size_t stepCount = buffer->mFrameCount;
    300     if (stepCount == 0 || mIsShutdown) {
    301         // prevent accidental re-use of buffer
    302         buffer->mFrameCount = 0;
    303         buffer->mRaw = NULL;
    304         buffer->mNonContig = 0;
    305         return;
    306     }
    307     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
    308     mUnreleased -= stepCount;
    309     audio_track_cblk_t* cblk = mCblk;
    310     // Both of these barriers are required
    311     if (mIsOut) {
    312         int32_t rear = cblk->u.mStreaming.mRear;
    313         android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
    314     } else {
    315         int32_t front = cblk->u.mStreaming.mFront;
    316         android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
    317     }
    318 }
    319 
    320 void ClientProxy::binderDied()
    321 {
    322     audio_track_cblk_t* cblk = mCblk;
    323     if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
    324         android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
    325         // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
    326         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
    327                 1);
    328     }
    329 }
    330 
    331 void ClientProxy::interrupt()
    332 {
    333     audio_track_cblk_t* cblk = mCblk;
    334     if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
    335         android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
    336         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
    337                 1);
    338     }
    339 }
    340 
    341 size_t ClientProxy::getMisalignment()
    342 {
    343     audio_track_cblk_t* cblk = mCblk;
    344     return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
    345             (mFrameCountP2 - 1);
    346 }
    347 
    348 size_t ClientProxy::getFramesFilled() {
    349     audio_track_cblk_t* cblk = mCblk;
    350     int32_t front;
    351     int32_t rear;
    352 
    353     if (mIsOut) {
    354         front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
    355         rear = cblk->u.mStreaming.mRear;
    356     } else {
    357         rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
    358         front = cblk->u.mStreaming.mFront;
    359     }
    360     ssize_t filled = rear - front;
    361     // pipe should not be overfull
    362     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
    363         ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
    364         return 0;
    365     }
    366     return (size_t)filled;
    367 }
    368 
    369 // ---------------------------------------------------------------------------
    370 
    371 void AudioTrackClientProxy::flush()
    372 {
    373     // This works for mFrameCountP2 <= 2^30
    374     size_t increment = mFrameCountP2 << 1;
    375     size_t mask = increment - 1;
    376     audio_track_cblk_t* cblk = mCblk;
    377     // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
    378     // Should newFlush = cblk->u.mStreaming.mRear?  Only problem is
    379     // if you want to flush twice to the same rear location after a 32 bit wrap.
    380     int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
    381                         ((cblk->u.mStreaming.mFlush & ~mask) + increment);
    382     android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
    383 }
    384 
    385 bool AudioTrackClientProxy::clearStreamEndDone() {
    386     return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
    387 }
    388 
    389 bool AudioTrackClientProxy::getStreamEndDone() const {
    390     return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
    391 }
    392 
    393 status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
    394 {
    395     struct timespec total;          // total elapsed time spent waiting
    396     total.tv_sec = 0;
    397     total.tv_nsec = 0;
    398     audio_track_cblk_t* cblk = mCblk;
    399     status_t status;
    400     enum {
    401         TIMEOUT_ZERO,       // requested == NULL || *requested == 0
    402         TIMEOUT_INFINITE,   // *requested == infinity
    403         TIMEOUT_FINITE,     // 0 < *requested < infinity
    404         TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
    405     } timeout;
    406     if (requested == NULL) {
    407         timeout = TIMEOUT_ZERO;
    408     } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
    409         timeout = TIMEOUT_ZERO;
    410     } else if (requested->tv_sec == INT_MAX) {
    411         timeout = TIMEOUT_INFINITE;
    412     } else {
    413         timeout = TIMEOUT_FINITE;
    414     }
    415     for (;;) {
    416         int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
    417         // check for track invalidation by server, or server death detection
    418         if (flags & CBLK_INVALID) {
    419             ALOGV("Track invalidated");
    420             status = DEAD_OBJECT;
    421             goto end;
    422         }
    423         if (flags & CBLK_STREAM_END_DONE) {
    424             ALOGV("stream end received");
    425             status = NO_ERROR;
    426             goto end;
    427         }
    428         // check for obtainBuffer interrupted by client
    429         if (flags & CBLK_INTERRUPT) {
    430             ALOGV("waitStreamEndDone() interrupted by client");
    431             status = -EINTR;
    432             goto end;
    433         }
    434         struct timespec remaining;
    435         const struct timespec *ts;
    436         switch (timeout) {
    437         case TIMEOUT_ZERO:
    438             status = WOULD_BLOCK;
    439             goto end;
    440         case TIMEOUT_INFINITE:
    441             ts = NULL;
    442             break;
    443         case TIMEOUT_FINITE:
    444             timeout = TIMEOUT_CONTINUE;
    445             if (MAX_SEC == 0) {
    446                 ts = requested;
    447                 break;
    448             }
    449             // fall through
    450         case TIMEOUT_CONTINUE:
    451             // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
    452             if (requested->tv_sec < total.tv_sec ||
    453                     (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
    454                 status = TIMED_OUT;
    455                 goto end;
    456             }
    457             remaining.tv_sec = requested->tv_sec - total.tv_sec;
    458             if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
    459                 remaining.tv_nsec += 1000000000;
    460                 remaining.tv_sec++;
    461             }
    462             if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
    463                 remaining.tv_sec = MAX_SEC;
    464                 remaining.tv_nsec = 0;
    465             }
    466             ts = &remaining;
    467             break;
    468         default:
    469             LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
    470             ts = NULL;
    471             break;
    472         }
    473         int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
    474         if (!(old & CBLK_FUTEX_WAKE)) {
    475             errno = 0;
    476             (void) syscall(__NR_futex, &cblk->mFutex,
    477                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
    478             switch (errno) {
    479             case 0:            // normal wakeup by server, or by binderDied()
    480             case EWOULDBLOCK:  // benign race condition with server
    481             case EINTR:        // wait was interrupted by signal or other spurious wakeup
    482             case ETIMEDOUT:    // time-out expired
    483                 break;
    484             default:
    485                 status = errno;
    486                 ALOGE("%s unexpected error %s", __func__, strerror(status));
    487                 goto end;
    488             }
    489         }
    490     }
    491 
    492 end:
    493     if (requested == NULL) {
    494         requested = &kNonBlocking;
    495     }
    496     return status;
    497 }
    498 
    499 // ---------------------------------------------------------------------------
    500 
    501 StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
    502         size_t frameCount, size_t frameSize)
    503     : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
    504       mMutator(&cblk->u.mStatic.mSingleStateQueue),
    505       mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
    506 {
    507     memset(&mState, 0, sizeof(mState));
    508     memset(&mPosLoop, 0, sizeof(mPosLoop));
    509 }
    510 
    511 void StaticAudioTrackClientProxy::flush()
    512 {
    513     LOG_ALWAYS_FATAL("static flush");
    514 }
    515 
    516 void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
    517 {
    518     // This can only happen on a 64-bit client
    519     if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
    520         // FIXME Should return an error status
    521         return;
    522     }
    523     mState.mLoopStart = (uint32_t) loopStart;
    524     mState.mLoopEnd = (uint32_t) loopEnd;
    525     mState.mLoopCount = loopCount;
    526     mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
    527     // set patch-up variables until the mState is acknowledged by the ServerProxy.
    528     // observed buffer position and loop count will freeze until then to give the
    529     // illusion of a synchronous change.
    530     getBufferPositionAndLoopCount(NULL, NULL);
    531     // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
    532     if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
    533         mPosLoop.mBufferPosition = mState.mLoopStart;
    534     }
    535     mPosLoop.mLoopCount = mState.mLoopCount;
    536     (void) mMutator.push(mState);
    537 }
    538 
    539 void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
    540 {
    541     // This can only happen on a 64-bit client
    542     if (position > UINT32_MAX) {
    543         // FIXME Should return an error status
    544         return;
    545     }
    546     mState.mPosition = (uint32_t) position;
    547     mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
    548     // set patch-up variables until the mState is acknowledged by the ServerProxy.
    549     // observed buffer position and loop count will freeze until then to give the
    550     // illusion of a synchronous change.
    551     if (mState.mLoopCount > 0) {  // only check if loop count is changing
    552         getBufferPositionAndLoopCount(NULL, NULL); // get last position
    553     }
    554     mPosLoop.mBufferPosition = position;
    555     if (position >= mState.mLoopEnd) {
    556         // no ongoing loop is possible if position is greater than loopEnd.
    557         mPosLoop.mLoopCount = 0;
    558     }
    559     (void) mMutator.push(mState);
    560 }
    561 
    562 void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
    563         size_t loopEnd, int loopCount)
    564 {
    565     setLoop(loopStart, loopEnd, loopCount);
    566     setBufferPosition(position);
    567 }
    568 
    569 size_t StaticAudioTrackClientProxy::getBufferPosition()
    570 {
    571     getBufferPositionAndLoopCount(NULL, NULL);
    572     return mPosLoop.mBufferPosition;
    573 }
    574 
    575 void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
    576         size_t *position, int *loopCount)
    577 {
    578     if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
    579          if (mPosLoopObserver.poll(mPosLoop)) {
    580              ; // a valid mPosLoop should be available if ackDone is true.
    581          }
    582     }
    583     if (position != NULL) {
    584         *position = mPosLoop.mBufferPosition;
    585     }
    586     if (loopCount != NULL) {
    587         *loopCount = mPosLoop.mLoopCount;
    588     }
    589 }
    590 
    591 // ---------------------------------------------------------------------------
    592 
    593 ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
    594         size_t frameSize, bool isOut, bool clientInServer)
    595     : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
    596       mAvailToClient(0), mFlush(0)
    597 {
    598 }
    599 
    600 status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
    601 {
    602     LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
    603     if (mIsShutdown) {
    604         goto no_init;
    605     }
    606     {
    607     audio_track_cblk_t* cblk = mCblk;
    608     // compute number of frames available to write (AudioTrack) or read (AudioRecord),
    609     // or use previous cached value from framesReady(), with added barrier if it omits.
    610     int32_t front;
    611     int32_t rear;
    612     // See notes on barriers at ClientProxy::obtainBuffer()
    613     if (mIsOut) {
    614         int32_t flush = cblk->u.mStreaming.mFlush;
    615         rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
    616         front = cblk->u.mStreaming.mFront;
    617         if (flush != mFlush) {
    618             // effectively obtain then release whatever is in the buffer
    619             const size_t overflowBit = mFrameCountP2 << 1;
    620             const size_t mask = overflowBit - 1;
    621             int32_t newFront = (front & ~mask) | (flush & mask);
    622             ssize_t filled = rear - newFront;
    623             if (filled >= (ssize_t)overflowBit) {
    624                 // front and rear offsets span the overflow bit of the p2 mask
    625                 // so rebasing newFront on the front offset is off by the overflow bit.
    626                 // adjust newFront to match rear offset.
    627                 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
    628                 newFront += overflowBit;
    629                 filled -= overflowBit;
    630             }
    631             // Rather than shutting down on a corrupt flush, just treat it as a full flush
    632             if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
    633                 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
    634                         "filled %zd=%#x",
    635                         mFlush, flush, front, rear,
    636                         (unsigned)mask, newFront, filled, (unsigned)filled);
    637                 newFront = rear;
    638             }
    639             mFlush = flush;
    640             android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
    641             // There is no danger from a false positive, so err on the side of caution
    642             if (true /*front != newFront*/) {
    643                 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
    644                 if (!(old & CBLK_FUTEX_WAKE)) {
    645                     (void) syscall(__NR_futex, &cblk->mFutex,
    646                             mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
    647                 }
    648             }
    649             front = newFront;
    650         }
    651     } else {
    652         front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
    653         rear = cblk->u.mStreaming.mRear;
    654     }
    655     ssize_t filled = rear - front;
    656     // pipe should not already be overfull
    657     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
    658         ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
    659         mIsShutdown = true;
    660     }
    661     if (mIsShutdown) {
    662         goto no_init;
    663     }
    664     // don't allow filling pipe beyond the nominal size
    665     size_t availToServer;
    666     if (mIsOut) {
    667         availToServer = filled;
    668         mAvailToClient = mFrameCount - filled;
    669     } else {
    670         availToServer = mFrameCount - filled;
    671         mAvailToClient = filled;
    672     }
    673     // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
    674     size_t part1;
    675     if (mIsOut) {
    676         front &= mFrameCountP2 - 1;
    677         part1 = mFrameCountP2 - front;
    678     } else {
    679         rear &= mFrameCountP2 - 1;
    680         part1 = mFrameCountP2 - rear;
    681     }
    682     if (part1 > availToServer) {
    683         part1 = availToServer;
    684     }
    685     size_t ask = buffer->mFrameCount;
    686     if (part1 > ask) {
    687         part1 = ask;
    688     }
    689     // is assignment redundant in some cases?
    690     buffer->mFrameCount = part1;
    691     buffer->mRaw = part1 > 0 ?
    692             &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
    693     buffer->mNonContig = availToServer - part1;
    694     // After flush(), allow releaseBuffer() on a previously obtained buffer;
    695     // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
    696     if (!ackFlush) {
    697         mUnreleased = part1;
    698     }
    699     return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
    700     }
    701 no_init:
    702     buffer->mFrameCount = 0;
    703     buffer->mRaw = NULL;
    704     buffer->mNonContig = 0;
    705     mUnreleased = 0;
    706     return NO_INIT;
    707 }
    708 
    709 void ServerProxy::releaseBuffer(Buffer* buffer)
    710 {
    711     LOG_ALWAYS_FATAL_IF(buffer == NULL);
    712     size_t stepCount = buffer->mFrameCount;
    713     if (stepCount == 0 || mIsShutdown) {
    714         // prevent accidental re-use of buffer
    715         buffer->mFrameCount = 0;
    716         buffer->mRaw = NULL;
    717         buffer->mNonContig = 0;
    718         return;
    719     }
    720     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
    721     mUnreleased -= stepCount;
    722     audio_track_cblk_t* cblk = mCblk;
    723     if (mIsOut) {
    724         int32_t front = cblk->u.mStreaming.mFront;
    725         android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
    726     } else {
    727         int32_t rear = cblk->u.mStreaming.mRear;
    728         android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
    729     }
    730 
    731     cblk->mServer += stepCount;
    732 
    733     size_t half = mFrameCount / 2;
    734     if (half == 0) {
    735         half = 1;
    736     }
    737     size_t minimum = (size_t) cblk->mMinimum;
    738     if (minimum == 0) {
    739         minimum = mIsOut ? half : 1;
    740     } else if (minimum > half) {
    741         minimum = half;
    742     }
    743     // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
    744     if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
    745         ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
    746         int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
    747         if (!(old & CBLK_FUTEX_WAKE)) {
    748             (void) syscall(__NR_futex, &cblk->mFutex,
    749                     mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
    750         }
    751     }
    752 
    753     buffer->mFrameCount = 0;
    754     buffer->mRaw = NULL;
    755     buffer->mNonContig = 0;
    756 }
    757 
    758 // ---------------------------------------------------------------------------
    759 
    760 size_t AudioTrackServerProxy::framesReady()
    761 {
    762     LOG_ALWAYS_FATAL_IF(!mIsOut);
    763 
    764     if (mIsShutdown) {
    765         return 0;
    766     }
    767     audio_track_cblk_t* cblk = mCblk;
    768 
    769     int32_t flush = cblk->u.mStreaming.mFlush;
    770     if (flush != mFlush) {
    771         // FIXME should return an accurate value, but over-estimate is better than under-estimate
    772         return mFrameCount;
    773     }
    774     // the acquire might not be necessary since not doing a subsequent read
    775     int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
    776     ssize_t filled = rear - cblk->u.mStreaming.mFront;
    777     // pipe should not already be overfull
    778     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
    779         ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
    780         mIsShutdown = true;
    781         return 0;
    782     }
    783     //  cache this value for later use by obtainBuffer(), with added barrier
    784     //  and racy if called by normal mixer thread
    785     // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
    786     return filled;
    787 }
    788 
    789 bool  AudioTrackServerProxy::setStreamEndDone() {
    790     audio_track_cblk_t* cblk = mCblk;
    791     bool old =
    792             (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
    793     if (!old) {
    794         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
    795                 1);
    796     }
    797     return old;
    798 }
    799 
    800 void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
    801 {
    802     audio_track_cblk_t* cblk = mCblk;
    803     cblk->u.mStreaming.mUnderrunFrames += frameCount;
    804 
    805     // FIXME also wake futex so that underrun is noticed more quickly
    806     (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
    807 }
    808 
    809 AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
    810 {   // do not call from multiple threads without holding lock
    811     mPlaybackRateObserver.poll(mPlaybackRate);
    812     return mPlaybackRate;
    813 }
    814 
    815 // ---------------------------------------------------------------------------
    816 
    817 StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
    818         size_t frameCount, size_t frameSize)
    819     : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
    820       mObserver(&cblk->u.mStatic.mSingleStateQueue),
    821       mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
    822       mFramesReadySafe(frameCount), mFramesReady(frameCount),
    823       mFramesReadyIsCalledByMultipleThreads(false)
    824 {
    825     memset(&mState, 0, sizeof(mState));
    826 }
    827 
    828 void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
    829 {
    830     mFramesReadyIsCalledByMultipleThreads = true;
    831 }
    832 
    833 size_t StaticAudioTrackServerProxy::framesReady()
    834 {
    835     // Can't call pollPosition() from multiple threads.
    836     if (!mFramesReadyIsCalledByMultipleThreads) {
    837         (void) pollPosition();
    838     }
    839     return mFramesReadySafe;
    840 }
    841 
    842 status_t StaticAudioTrackServerProxy::updateStateWithLoop(
    843         StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
    844 {
    845     if (localState->mLoopSequence != update.mLoopSequence) {
    846         bool valid = false;
    847         const size_t loopStart = update.mLoopStart;
    848         const size_t loopEnd = update.mLoopEnd;
    849         size_t position = localState->mPosition;
    850         if (update.mLoopCount == 0) {
    851             valid = true;
    852         } else if (update.mLoopCount >= -1) {
    853             if (loopStart < loopEnd && loopEnd <= mFrameCount &&
    854                     loopEnd - loopStart >= MIN_LOOP) {
    855                 // If the current position is greater than the end of the loop
    856                 // we "wrap" to the loop start. This might cause an audible pop.
    857                 if (position >= loopEnd) {
    858                     position = loopStart;
    859                 }
    860                 valid = true;
    861             }
    862         }
    863         if (!valid || position > mFrameCount) {
    864             return NO_INIT;
    865         }
    866         localState->mPosition = position;
    867         localState->mLoopCount = update.mLoopCount;
    868         localState->mLoopEnd = loopEnd;
    869         localState->mLoopStart = loopStart;
    870         localState->mLoopSequence = update.mLoopSequence;
    871     }
    872     return OK;
    873 }
    874 
    875 status_t StaticAudioTrackServerProxy::updateStateWithPosition(
    876         StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
    877 {
    878     if (localState->mPositionSequence != update.mPositionSequence) {
    879         if (update.mPosition > mFrameCount) {
    880             return NO_INIT;
    881         } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
    882             localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
    883         }
    884         localState->mPosition = update.mPosition;
    885         localState->mPositionSequence = update.mPositionSequence;
    886     }
    887     return OK;
    888 }
    889 
    890 ssize_t StaticAudioTrackServerProxy::pollPosition()
    891 {
    892     StaticAudioTrackState state;
    893     if (mObserver.poll(state)) {
    894         StaticAudioTrackState trystate = mState;
    895         bool result;
    896         const int32_t diffSeq = state.mLoopSequence - state.mPositionSequence;
    897 
    898         if (diffSeq < 0) {
    899             result = updateStateWithLoop(&trystate, state) == OK &&
    900                     updateStateWithPosition(&trystate, state) == OK;
    901         } else {
    902             result = updateStateWithPosition(&trystate, state) == OK &&
    903                     updateStateWithLoop(&trystate, state) == OK;
    904         }
    905         if (!result) {
    906             mObserver.done();
    907             // caution: no update occurs so server state will be inconsistent with client state.
    908             ALOGE("%s client pushed an invalid state, shutting down", __func__);
    909             mIsShutdown = true;
    910             return (ssize_t) NO_INIT;
    911         }
    912         mState = trystate;
    913         if (mState.mLoopCount == -1) {
    914             mFramesReady = INT64_MAX;
    915         } else if (mState.mLoopCount == 0) {
    916             mFramesReady = mFrameCount - mState.mPosition;
    917         } else if (mState.mLoopCount > 0) {
    918             // TODO: Later consider fixing overflow, but does not seem needed now
    919             // as will not overflow if loopStart and loopEnd are Java "ints".
    920             mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
    921                     + mFrameCount - mState.mPosition;
    922         }
    923         mFramesReadySafe = clampToSize(mFramesReady);
    924         // This may overflow, but client is not supposed to rely on it
    925         StaticAudioTrackPosLoop posLoop;
    926 
    927         posLoop.mLoopCount = (int32_t) mState.mLoopCount;
    928         posLoop.mBufferPosition = (uint32_t) mState.mPosition;
    929         mPosLoopMutator.push(posLoop);
    930         mObserver.done(); // safe to read mStatic variables.
    931     }
    932     return (ssize_t) mState.mPosition;
    933 }
    934 
    935 status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush __unused)
    936 {
    937     if (mIsShutdown) {
    938         buffer->mFrameCount = 0;
    939         buffer->mRaw = NULL;
    940         buffer->mNonContig = 0;
    941         mUnreleased = 0;
    942         return NO_INIT;
    943     }
    944     ssize_t positionOrStatus = pollPosition();
    945     if (positionOrStatus < 0) {
    946         buffer->mFrameCount = 0;
    947         buffer->mRaw = NULL;
    948         buffer->mNonContig = 0;
    949         mUnreleased = 0;
    950         return (status_t) positionOrStatus;
    951     }
    952     size_t position = (size_t) positionOrStatus;
    953     size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
    954     size_t avail;
    955     if (position < end) {
    956         avail = end - position;
    957         size_t wanted = buffer->mFrameCount;
    958         if (avail < wanted) {
    959             buffer->mFrameCount = avail;
    960         } else {
    961             avail = wanted;
    962         }
    963         buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
    964     } else {
    965         avail = 0;
    966         buffer->mFrameCount = 0;
    967         buffer->mRaw = NULL;
    968     }
    969     // As mFramesReady is the total remaining frames in the static audio track,
    970     // it is always larger or equal to avail.
    971     LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
    972     buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
    973     mUnreleased = avail;
    974     return NO_ERROR;
    975 }
    976 
    977 void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
    978 {
    979     size_t stepCount = buffer->mFrameCount;
    980     LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
    981     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
    982     if (stepCount == 0) {
    983         // prevent accidental re-use of buffer
    984         buffer->mRaw = NULL;
    985         buffer->mNonContig = 0;
    986         return;
    987     }
    988     mUnreleased -= stepCount;
    989     audio_track_cblk_t* cblk = mCblk;
    990     size_t position = mState.mPosition;
    991     size_t newPosition = position + stepCount;
    992     int32_t setFlags = 0;
    993     if (!(position <= newPosition && newPosition <= mFrameCount)) {
    994         ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
    995                 mFrameCount);
    996         newPosition = mFrameCount;
    997     } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
    998         newPosition = mState.mLoopStart;
    999         if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
   1000             setFlags = CBLK_LOOP_CYCLE;
   1001         } else {
   1002             setFlags = CBLK_LOOP_FINAL;
   1003         }
   1004     }
   1005     if (newPosition == mFrameCount) {
   1006         setFlags |= CBLK_BUFFER_END;
   1007     }
   1008     mState.mPosition = newPosition;
   1009     if (mFramesReady != INT64_MAX) {
   1010         mFramesReady -= stepCount;
   1011     }
   1012     mFramesReadySafe = clampToSize(mFramesReady);
   1013 
   1014     cblk->mServer += stepCount;
   1015     // This may overflow, but client is not supposed to rely on it
   1016     StaticAudioTrackPosLoop posLoop;
   1017     posLoop.mBufferPosition = mState.mPosition;
   1018     posLoop.mLoopCount = mState.mLoopCount;
   1019     mPosLoopMutator.push(posLoop);
   1020     if (setFlags != 0) {
   1021         (void) android_atomic_or(setFlags, &cblk->mFlags);
   1022         // this would be a good place to wake a futex
   1023     }
   1024 
   1025     buffer->mFrameCount = 0;
   1026     buffer->mRaw = NULL;
   1027     buffer->mNonContig = 0;
   1028 }
   1029 
   1030 void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount __unused)
   1031 {
   1032     // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
   1033     // we don't have a location to count underrun frames.  The underrun frame counter
   1034     // only exists in AudioTrackSharedStreaming.  Fortunately, underruns are not
   1035     // possible for static buffer tracks other than at end of buffer, so this is not a loss.
   1036 
   1037     // FIXME also wake futex so that underrun is noticed more quickly
   1038     (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
   1039 }
   1040 
   1041 // ---------------------------------------------------------------------------
   1042 
   1043 }   // namespace android
   1044