blob: 28a034c9c5ecbaa9a280cfcb12d26ea322bee907 [file] [log] [blame]
Glenn Kasten01066232012-02-27 11:50:44 -08001/*
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>
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070023#include <media/nbaio/Pipe.h>
24#include <media/nbaio/roundup.h>
Glenn Kasten01066232012-02-27 11:50:44 -080025
26namespace android {
27
Glenn Kasten72e54af2014-01-31 09:37:35 -080028Pipe::Pipe(size_t maxFrames, const NBAIO_Format& format) :
Glenn Kasten01066232012-02-27 11:50:44 -080029 NBAIO_Sink(format),
30 mMaxFrames(roundup(maxFrames)),
31 mBuffer(malloc(mMaxFrames * Format_frameSize(format))),
32 mRear(0),
33 mReaders(0)
34{
35}
36
37Pipe::~Pipe()
38{
39 ALOG_ASSERT(android_atomic_acquire_load(&mReaders) == 0);
40 free(mBuffer);
41}
42
43ssize_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 }
Glenn Kasten4d693d62014-03-06 07:53:11 -080055 memcpy((char *) mBuffer + (rear * mFrameSize), buffer, written * mFrameSize);
Glenn Kasten01066232012-02-27 11:50:44 -080056 if (CC_UNLIKELY(rear + written == mMaxFrames)) {
57 if (CC_UNLIKELY((count -= written) > rear)) {
58 count = rear;
59 }
60 if (CC_LIKELY(count > 0)) {
Glenn Kasten4d693d62014-03-06 07:53:11 -080061 memcpy(mBuffer, (char *) buffer + (written * mFrameSize), count * mFrameSize);
Glenn Kasten01066232012-02-27 11:50:44 -080062 written += count;
63 }
64 }
65 android_atomic_release_store(written + mRear, &mRear);
66 mFramesWritten += written;
67 return written;
68}
69
70} // namespace android