1 /*
2 * Copyright (C) 2017 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 #include "byte_buffer.h"
18
19 #include <stdatomic.h>
20 #include <string.h>
21
22 typedef _Atomic int32_t writer_pos_t;
23
byteBuffer_write(byte_buffer_t byteBuffer,size_t byteBufferSize,const char * srcBuffer,size_t frameCount,int channels)24 ssize_t byteBuffer_write(byte_buffer_t byteBuffer, size_t byteBufferSize,
25 const char *srcBuffer, size_t frameCount, int channels) {
26 // bytebufferSize is in bytes
27 const size_t dataSectionSize = byteBufferSize - sizeof(writer_pos_t);
28 writer_pos_t *rear_ptr = (writer_pos_t*)(byteBuffer + dataSectionSize);
29 writer_pos_t rear = *rear_ptr;
30 // rear should not exceed 2^31 - 1, or else overflow will happen
31
32 size_t frameSize = channels * sizeof(short); // only one channel
33 int32_t maxLengthInShort = dataSectionSize / frameSize;
34 // mask the upper bits to get the correct position in the pipe
35 writer_pos_t tempRear = rear & (maxLengthInShort - 1);
36 size_t part1 = maxLengthInShort - tempRear;
37
38 if (part1 > frameCount) {
39 part1 = frameCount;
40 }
41
42 if (part1 > 0) {
43 memcpy(byteBuffer + (tempRear * frameSize), srcBuffer,
44 part1 * frameSize);
45
46 size_t part2 = frameCount - part1;
47 if (part2 > 0) {
48 memcpy(byteBuffer, (srcBuffer + (part1 * frameSize)),
49 part2 * frameSize);
50 }
51 }
52
53 // increase value of rear using the strongest memory ordering
54 // (since it's being read by Java we can't control the ordering
55 // used by the other side).
56 atomic_store(rear_ptr, rear + frameCount);
57 return frameCount;
58 }
59