1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef VOLUME_TOOLS_H
17 #define VOLUME_TOOLS_H
18 #include "audio_info.h"
19 
20 namespace OHOS {
21 namespace AudioStandard {
22 static const size_t CHANNEL_MAX = 16; // same with CHANNEL_16
23 
24 static const int32_t INT32_VOLUME_MIN = 0; // 0, min volume
25 static const uint32_t VOLUME_SHIFT = 16;
26 static constexpr int32_t INT32_VOLUME_MAX = 1 << VOLUME_SHIFT; // 1 << 16 = 65536, max volume
27 struct ChannelVolumes {
28     AudioChannel channel = STEREO;
29     int32_t volStart[CHANNEL_MAX];
30     int32_t volEnd[CHANNEL_MAX];
31 };
32 
IsVolumeSame(const float & x,const float & y,const float & epsilon)33 static inline bool IsVolumeSame(const float& x, const float& y, const float& epsilon)
34 {
35     return (std::abs((x) - (y)) <= std::abs(epsilon));
36 }
37 
38 class VolumeTools {
39 public:
40     static double GetVolDb(AudioSampleFormat format, int32_t vol);
41     static bool IsVolumeValid(float volFloat); // 0.0 <= volFloat <= 1.0
42     static bool IsVolumeValid(int32_t volInt); // 0 <= volInt <= 65536
43     static bool IsVolumeValid(ChannelVolumes vols);
44     static size_t GetByteSize(AudioSampleFormat format);
45     static int32_t GetInt32Vol(float volFloat);
46     static ChannelVolumes GetChannelVolumes(AudioChannel channel, int32_t volStart, int32_t volEnd);
47     static ChannelVolumes GetChannelVolumes(AudioChannel channel, float volStart, float volEnd);
48 
49     // Data size should be rounded to each sample size
50     // There will be significant sound quality loss when process uint8_t samples.
51     static int32_t Process(const BufferDesc &buffer, AudioSampleFormat format, ChannelVolumes vols);
52 
53     // will count volume for each channel, vol sum will be kept in volStart
54     static ChannelVolumes CountVolumeLevel(const BufferDesc &buffer, AudioSampleFormat format, AudioChannel channel,
55         size_t split = 1);
56 };
57 } // namespace AudioStandard
58 } // namespace OHOS
59 #endif // VOLUME_TOOLS_H