1 /*
2 * Copyright 2020 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 #ifndef FLOWGRAPH_UTILITIES_H
18 #define FLOWGRAPH_UTILITIES_H
19
20 #include <math.h>
21 #include <unistd.h>
22
23 using namespace FLOWGRAPH_OUTER_NAMESPACE::flowgraph;
24
25 class FlowgraphUtilities {
26 public:
27 // This was copied from audio_utils/primitives.h
28 /**
29 * Convert a single-precision floating point value to a Q0.31 integer value.
30 * Rounds to nearest, ties away from 0.
31 *
32 * Values outside the range [-1.0, 1.0) are properly clamped to -2147483648 and 2147483647,
33 * including -Inf and +Inf. NaN values are considered undefined, and behavior may change
34 * depending on hardware and future implementation of this function.
35 */
clamp32FromFloat(float f)36 static int32_t clamp32FromFloat(float f)
37 {
38 static const float scale = (float)(1UL << 31);
39 static const float limpos = 1.;
40 static const float limneg = -1.;
41
42 if (f <= limneg) {
43 return INT32_MIN;
44 } else if (f >= limpos) {
45 return INT32_MAX;
46 }
47 f *= scale;
48 /* integer conversion is through truncation (though int to float is not).
49 * ensure that we round to nearest, ties away from 0.
50 */
51 return f > 0 ? f + 0.5 : f - 0.5;
52 }
53
54 /**
55 * Convert a single-precision floating point value to a Q0.23 integer value, stored in a
56 * 32 bit signed integer (technically stored as Q8.23, but clamped to Q0.23).
57 *
58 * Values outside the range [-1.0, 1.0) are properly clamped to -8388608 and 8388607,
59 * including -Inf and +Inf. NaN values are considered undefined, and behavior may change
60 * depending on hardware and future implementation of this function.
61 */
clamp24FromFloat(float f)62 static int32_t clamp24FromFloat(float f)
63 {
64 static const float scale = 1 << 23;
65 return (int32_t) lroundf(fmaxf(fminf(f * scale, scale - 1.f), -scale));
66 }
67
68 };
69
70 #endif // FLOWGRAPH_UTILITIES_H
71