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 "MonoPipeReader"
18//#define LOG_NDEBUG 0
19
20#include <cutils/compiler.h>
21#include <utils/Log.h>
22#include <media/nbaio/MonoPipeReader.h>
23
24namespace android {
25
26MonoPipeReader::MonoPipeReader(MonoPipe* pipe) :
27        NBAIO_Source(pipe->mFormat),
28        mPipe(pipe)
29{
30}
31
32MonoPipeReader::~MonoPipeReader()
33{
34}
35
36ssize_t MonoPipeReader::availableToRead()
37{
38    if (CC_UNLIKELY(!mNegotiated)) {
39        return NEGOTIATE;
40    }
41    ssize_t ret = android_atomic_acquire_load(&mPipe->mRear) - mPipe->mFront;
42    ALOG_ASSERT((0 <= ret) && ((size_t) ret <= mPipe->mMaxFrames));
43    return ret;
44}
45
46ssize_t MonoPipeReader::read(void *buffer, size_t count)
47{
48    // count == 0 is unlikely and not worth checking for explicitly; will be handled automatically
49    ssize_t red = availableToRead();
50    if (CC_UNLIKELY(red <= 0)) {
51        return red;
52    }
53    if (CC_LIKELY((size_t) red > count)) {
54        red = count;
55    }
56    size_t front = mPipe->mFront & (mPipe->mMaxFrames - 1);
57    size_t part1 = mPipe->mMaxFrames - front;
58    if (part1 > (size_t) red) {
59        part1 = red;
60    }
61    if (CC_LIKELY(part1 > 0)) {
62        memcpy(buffer, (char *) mPipe->mBuffer + (front * mFrameSize), part1 * mFrameSize);
63        if (CC_UNLIKELY(front + part1 == mPipe->mMaxFrames)) {
64            size_t part2 = red - part1;
65            if (CC_LIKELY(part2 > 0)) {
66                memcpy((char *) buffer + (part1 * mFrameSize), mPipe->mBuffer, part2 * mFrameSize);
67            }
68        }
69        android_atomic_release_store(red + mPipe->mFront, &mPipe->mFront);
70        mFramesRead += red;
71    }
72    return red;
73}
74
75void MonoPipeReader::onTimestamp(const ExtendedTimestamp &timestamp)
76{
77    mPipe->mTimestampMutator.push(timestamp);
78}
79
80}   // namespace android
81