Home | History | Annotate | Download | only in libnbaio
      1 /*
      2  * Copyright (C) 2012 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 "Pipe"
     18 //#define LOG_NDEBUG 0
     19 
     20 #include <cutils/atomic.h>
     21 #include <cutils/compiler.h>
     22 #include <utils/Log.h>
     23 #include <media/nbaio/Pipe.h>
     24 #include <media/nbaio/roundup.h>
     25 
     26 namespace android {
     27 
     28 Pipe::Pipe(size_t maxFrames, const NBAIO_Format& format, void *buffer) :
     29         NBAIO_Sink(format),
     30         mMaxFrames(roundup(maxFrames)),
     31         mBuffer(buffer == NULL ? malloc(mMaxFrames * Format_frameSize(format)) : buffer),
     32         mRear(0),
     33         mReaders(0),
     34         mFreeBufferInDestructor(buffer == NULL)
     35 {
     36 }
     37 
     38 Pipe::~Pipe()
     39 {
     40     ALOG_ASSERT(android_atomic_acquire_load(&mReaders) == 0);
     41     if (mFreeBufferInDestructor) {
     42         free(mBuffer);
     43     }
     44 }
     45 
     46 ssize_t Pipe::write(const void *buffer, size_t count)
     47 {
     48     // count == 0 is unlikely and not worth checking for
     49     if (CC_UNLIKELY(!mNegotiated)) {
     50         return NEGOTIATE;
     51     }
     52     // write() is not multi-thread safe w.r.t. itself, so no mutex or atomic op needed to read mRear
     53     size_t rear = mRear & (mMaxFrames - 1);
     54     size_t written = mMaxFrames - rear;
     55     if (CC_LIKELY(written > count)) {
     56         written = count;
     57     }
     58     memcpy((char *) mBuffer + (rear * mFrameSize), buffer, written * mFrameSize);
     59     if (CC_UNLIKELY(rear + written == mMaxFrames)) {
     60         if (CC_UNLIKELY((count -= written) > rear)) {
     61             count = rear;
     62         }
     63         if (CC_LIKELY(count > 0)) {
     64             memcpy(mBuffer, (char *) buffer + (written * mFrameSize), count * mFrameSize);
     65             written += count;
     66         }
     67     }
     68     android_atomic_release_store(written + mRear, &mRear);
     69     mFramesWritten += written;
     70     return written;
     71 }
     72 
     73 }   // namespace android
     74