RavEngine
Loading...
Searching...
No Matches
sample_type_conversion.h
1/*
2Copyright 2018 Google Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS-IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17#ifndef RESONANCE_AUDIO_UTILS_SAMPLE_TYPE_CONVERSION_H_
18#define RESONANCE_AUDIO_UTILS_SAMPLE_TYPE_CONVERSION_H_
19
20#include <algorithm>
21
22#include "base/integral_types.h"
23#include "base/logging.h"
24
25namespace vraudio {
26
27// Convert the given int16 to a float in the range [-1.0f, 1.0f].
28inline void ConvertSampleToFloatFormat(int16 input, float* output) {
29 DCHECK(output);
30 static const float kInt16Max = static_cast<float>(0x7FFF);
31 static const float kInt16ToFloat = 1.0f / kInt16Max;
32 *output = input * kInt16ToFloat;
33}
34
35// Overloaded input argument to support sample type templated methods.
36inline void ConvertSampleToFloatFormat(float input, float* output) {
37 DCHECK(output);
38 *output = input;
39}
40
41// Saturating if the float is not in [-1.0f, 1.0f].
42inline void ConvertSampleFromFloatFormat(float input, int16* output) {
43 DCHECK(output);
44 // Convert the given float to an int16 in the range
45 // [-32767 (0x7FFF), 32767 (0x7FFF)],
46 static const float kInt16Min = static_cast<float>(-0x7FFF);
47 static const float kInt16Max = static_cast<float>(0x7FFF);
48 static const float kFloatToInt16 = kInt16Max;
49 const float scaled_value = input * kFloatToInt16;
50 const float clamped_value =
51 std::min(kInt16Max, std::max(kInt16Min, scaled_value));
52 *output = static_cast<int16>(clamped_value);
53}
54
55// Overloaded output argument to support sample type templated methods.
56inline void ConvertSampleFromFloatFormat(float input, float* output) {
57 DCHECK(output);
58 *output = input;
59}
60
61// Convert a vector of int16 samples to float format in the range [-1.0f, 1.0f].
62void ConvertPlanarSamples(size_t length, const int16* input,
63 float* output);
64
65// Overloaded input argument to support sample type templated methods.
66void ConvertPlanarSamples(size_t length, const float* input,
67 float* output);
68
69// Overloaded method to support methods templated against the input sample type.
70void ConvertPlanarSamples(size_t length, const float* input,
71 int16* output);
72
73// Overloaded output argument to support sample type templated methods.
74void ConvertPlanarSamples(size_t length, const float* input,
75 float* output);
76
77} // namespace vraudio
78
79#endif // RESONANCE_AUDIO_UTILS_SAMPLE_TYPE_CONVERSION_H_