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 <atomic>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <audio_utils/fifo_writer_T.h>
21
22 template <typename T>
memcpyWords(T * dst,const T * src,uint32_t count)23 static inline void memcpyWords(T *dst, const T *src, uint32_t count)
24 {
25 switch (count) {
26 case 0: break;
27 // TODO templatize here also, but first confirm no performance regression compared to current
28 #define _(n) \
29 case n: { \
30 struct s##n { T a[n]; }; \
31 *(struct s##n *)dst = *(const struct s##n *)src; \
32 break; \
33 }
34 _(1) _(2) _(3) _(4) _(5) _(6) _(7) _(8) _(9) _(10) _(11) _(12) _(13) _(14) _(15) _(16)
35 #undef _
36 default:
37 memcpy(dst, src, count * sizeof(T));
38 break;
39 }
40 }
41
42 template <typename T>
audio_utils_fifo_writer_T(audio_utils_fifo & fifo)43 audio_utils_fifo_writer_T<T>::audio_utils_fifo_writer_T(audio_utils_fifo& fifo) :
44 mLocalRear(0), mFrameCountP2(fifo.mFrameCountP2), mBuffer((T *) fifo.mBuffer),
45 mWriterRear(fifo.mWriterRear)
46 {
47 if (fifo.mFrameSize != sizeof(T) || fifo.mFudgeFactor != 0) {
48 abort();
49 }
50 }
51
52 template <typename T>
~audio_utils_fifo_writer_T()53 audio_utils_fifo_writer_T<T>::~audio_utils_fifo_writer_T()
54 {
55 }
56
57 template <typename T>
write(const T * buffer,uint32_t count)58 void audio_utils_fifo_writer_T<T>::write(const T *buffer, uint32_t count)
59 __attribute__((no_sanitize("integer"))) // mLocalRear += can wrap
60 {
61 uint32_t availToWrite = mFrameCountP2;
62 if (availToWrite > count) {
63 availToWrite = count;
64 }
65 uint32_t rearOffset = mLocalRear & (mFrameCountP2 - 1);
66 uint32_t part1 = mFrameCountP2 - rearOffset;
67 if (part1 > availToWrite) {
68 part1 = availToWrite;
69 }
70 memcpyWords(&mBuffer[rearOffset], buffer, part1);
71 // TODO apply this simplification to other copies of the code
72 uint32_t part2 = availToWrite - part1;
73 memcpyWords(&mBuffer[0], &buffer[part1], part2);
74 mLocalRear += availToWrite;
75 }
76
77 // Instantiate for the specific types we need, which is currently just int32_t and int64_t.
78
79 template class audio_utils_fifo_writer_T<int32_t>;
80 template class audio_utils_fifo_writer_T<int64_t>;
81