• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
Pipe(size_t maxFrames,NBAIO_Format format)28 Pipe::Pipe(size_t maxFrames, NBAIO_Format format) :
29         NBAIO_Sink(format),
30         mMaxFrames(roundup(maxFrames)),
31         mBuffer(malloc(mMaxFrames * Format_frameSize(format))),
32         mRear(0),
33         mReaders(0)
34 {
35 }
36 
~Pipe()37 Pipe::~Pipe()
38 {
39     ALOG_ASSERT(android_atomic_acquire_load(&mReaders) == 0);
40     free(mBuffer);
41 }
42 
write(const void * buffer,size_t count)43 ssize_t Pipe::write(const void *buffer, size_t count)
44 {
45     // count == 0 is unlikely and not worth checking for
46     if (CC_UNLIKELY(!mNegotiated)) {
47         return NEGOTIATE;
48     }
49     // write() is not multi-thread safe w.r.t. itself, so no mutex or atomic op needed to read mRear
50     size_t rear = mRear & (mMaxFrames - 1);
51     size_t written = mMaxFrames - rear;
52     if (CC_LIKELY(written > count)) {
53         written = count;
54     }
55     memcpy((char *) mBuffer + (rear << mBitShift), buffer, written << mBitShift);
56     if (CC_UNLIKELY(rear + written == mMaxFrames)) {
57         if (CC_UNLIKELY((count -= written) > rear)) {
58             count = rear;
59         }
60         if (CC_LIKELY(count > 0)) {
61             memcpy(mBuffer, (char *) buffer + (written << mBitShift), count << mBitShift);
62             written += count;
63         }
64     }
65     android_atomic_release_store(written + mRear, &mRear);
66     mFramesWritten += written;
67     return written;
68 }
69 
70 }   // namespace android
71