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 <audio_utils/roundup.h>
25
26 namespace android {
27
Pipe(size_t maxFrames,const NBAIO_Format & format,void * buffer)28 Pipe::Pipe(size_t maxFrames, const NBAIO_Format& format, void *buffer) :
29 NBAIO_Sink(format),
30 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
31 mMaxFrames(roundup(maxFrames)),
32 mBuffer(buffer == NULL ? malloc(mMaxFrames * Format_frameSize(format)) : buffer),
33 mFifo(mMaxFrames, Format_frameSize(format), mBuffer, false /*throttlesWriter*/),
34 mFifoWriter(mFifo),
35 mReaders(0),
36 mFreeBufferInDestructor(buffer == NULL)
37 {
38 }
39
~Pipe()40 Pipe::~Pipe()
41 {
42 ALOG_ASSERT(android_atomic_acquire_load(&mReaders) == 0);
43 if (mFreeBufferInDestructor) {
44 free(mBuffer);
45 }
46 }
47
write(const void * buffer,size_t count)48 ssize_t Pipe::write(const void *buffer, size_t count)
49 {
50 // count == 0 is unlikely and not worth checking for
51 if (CC_UNLIKELY(!mNegotiated)) {
52 return NEGOTIATE;
53 }
54 ssize_t actual = mFifoWriter.write(buffer, count);
55 ALOG_ASSERT(actual <= count);
56 if (actual <= 0) {
57 return actual;
58 }
59 mFramesWritten += (size_t) actual;
60 return actual;
61 }
62
63 } // namespace android
64