1 /*
2 * Copyright (c) 2025 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 #ifndef LOG_TAG
16 #define LOG_TAG "AudioLimiter"
17 #endif
18
19 #include "audio_errors.h"
20 #include "audio_limiter.h"
21 #include "audio_common_log.h"
22 #include "audio_utils.h"
23
24 #include "securec.h"
25
26 namespace OHOS {
27 namespace AudioStandard {
28
29 const float NEXT_LEVEL = 0.5f;
30 const float THRESHOLD = 0.92f;
31 const float LEVEL_ATTACK = 0.3f;
32 const float LEVEL_RELEASE = 0.7f;
33 const float GAIN_ATTACK = 0.1f;
34 const float GAIN_RELEASE = 0.6f;
35 const int32_t AUDIO_FORMAT_PCM_FLOAT = 4;
36 const int32_t PROC_COUNT = 4; // process 4 times
37 const int32_t AUDIO_LMT_ALGO_CHANNEL = 2; // 2 channel for stereo
38
AudioLimiter(int32_t sinkIndex)39 AudioLimiter::AudioLimiter(int32_t sinkIndex)
40 {
41 sinkIndex_ = sinkIndex;
42 nextLev_ = NEXT_LEVEL;
43 threshold_ = THRESHOLD;
44 levelAttack_ = LEVEL_ATTACK;
45 levelRelease_ = LEVEL_RELEASE;
46 gainAttack_ = GAIN_ATTACK;
47 gainRelease_ = GAIN_RELEASE;
48 format_ = AUDIO_FORMAT_PCM_FLOAT;
49 latency_ = 0;
50 algoFrameLen_ = 0;
51 curMaxLev_ = 0.0f;
52 gain_ = 0.0f;
53 bufHis_ = nullptr;
54 channels_ = 0;
55 sampleRate_ = 0;
56 AUDIO_INFO_LOG("AudioLimiter");
57 }
58
~AudioLimiter()59 AudioLimiter::~AudioLimiter()
60 {
61 ReleaseBuffer();
62 DumpFileUtil::CloseDumpFile(&dumpFileInput_);
63 DumpFileUtil::CloseDumpFile(&dumpFileOutput_);
64 AUDIO_INFO_LOG("~AudioLimiter");
65 }
66
ReleaseBuffer()67 void AudioLimiter::ReleaseBuffer()
68 {
69 if (bufHis_ != nullptr) {
70 delete[] bufHis_;
71 bufHis_ = nullptr;
72 }
73 return;
74 }
75
SetConfig(int32_t maxRequest,int32_t biteSize,int32_t sampleRate,int32_t channels)76 int32_t AudioLimiter::SetConfig(int32_t maxRequest, int32_t biteSize, int32_t sampleRate, int32_t channels)
77 {
78 CHECK_AND_RETURN_RET_LOG(maxRequest > 0 && biteSize > 0 && sampleRate > 0 && channels == AUDIO_LMT_ALGO_CHANNEL,
79 ERROR, "Invalid input parameters");
80 algoFrameLen_ = maxRequest / (biteSize * PROC_COUNT);
81 latency_ = static_cast<uint32_t>(algoFrameLen_ * AUDIO_MS_PER_S / (sampleRate * channels));
82 AUDIO_INFO_LOG("maxRequest = %{public}d, biteSize = %{public}d, sampleRate = %{public}d, channels = %{public}d,"
83 "algoFrameLen_ = %{public}d, latency_ = %{public}d",
84 maxRequest, biteSize, sampleRate, channels, algoFrameLen_, latency_);
85 bufHis_ = new (std::nothrow) float[algoFrameLen_ + 1]();
86 CHECK_AND_RETURN_RET_LOG(bufHis_ != nullptr, ERROR, "allocate limit algorithm buffer failed");
87 sampleRate_ = static_cast<uint32_t>(sampleRate);
88 channels_ = static_cast<uint32_t>(channels);
89 dumpFileNameIn_ = std::to_string(sinkIndex_) + "_limiter_in_" + GetTime() + "_" + std::to_string(sampleRate) + "_"
90 + std::to_string(channels) + "_" + std::to_string(format_) + ".pcm";
91 DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileNameIn_, &dumpFileInput_);
92 dumpFileNameOut_ = std::to_string(sinkIndex_) + "_limiter_out_" + GetTime() + "_" + std::to_string(sampleRate) + "_"
93 + std::to_string(channels) + "_" + std::to_string(format_) + ".pcm";
94 DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileNameOut_, &dumpFileOutput_);
95
96 return SUCCESS;
97 }
98
Process(int32_t frameLen,float * inBuffer,float * outBuffer)99 int32_t AudioLimiter::Process(int32_t frameLen, float *inBuffer, float *outBuffer)
100 {
101 CHECK_AND_RETURN_RET_LOG(algoFrameLen_ * PROC_COUNT == frameLen, ERROR,
102 "error, algoFrameLen_ = %{public}d, frameLen = %{public}d", algoFrameLen_, frameLen);
103 int32_t ptrIndex = 0;
104 if (dumpFileInput_ == nullptr) {
105 dumpFileNameIn_ = std::to_string(sinkIndex_) + "_limiter_in_" + GetTime() + "_" +
106 std::to_string(sampleRate_) + "_" + std::to_string(channels_) + "_" + std::to_string(format_) + ".pcm";
107 DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileNameIn_, &dumpFileInput_);
108 AUDIO_DEBUG_LOG("Reopen dump file: %{public}s", dumpFileNameIn_.c_str());
109 }
110 if (dumpFileOutput_ == nullptr) {
111 dumpFileNameOut_ = std::to_string(sinkIndex_) + "_limiter_out_" + GetTime() + "_" +
112 std::to_string(sampleRate_) + "_" + std::to_string(channels_) + "_" + std::to_string(format_) + ".pcm";
113 DumpFileUtil::OpenDumpFile(DumpFileUtil::DUMP_SERVER_PARA, dumpFileNameOut_, &dumpFileOutput_);
114 AUDIO_DEBUG_LOG("Reopen dump file: %{public}s", dumpFileNameOut_.c_str());
115 }
116 DumpFileUtil::WriteDumpFile(dumpFileInput_, static_cast<void *>(inBuffer), frameLen * sizeof(float));
117 for (int32_t i = 0; i < PROC_COUNT; i++) {
118 ProcessAlgo(algoFrameLen_, inBuffer + ptrIndex, outBuffer + ptrIndex);
119 ptrIndex += algoFrameLen_;
120 }
121 DumpFileUtil::WriteDumpFile(dumpFileOutput_, static_cast<void *>(outBuffer), frameLen * sizeof(float));
122 return SUCCESS;
123 }
124
ProcessAlgo(int algoFrameLen,float * inBuffer,float * outBuffer)125 void AudioLimiter::ProcessAlgo(int algoFrameLen, float *inBuffer, float *outBuffer)
126 {
127 // calculate envelope energy
128 CHECK_AND_RETURN_LOG(algoFrameLen > 0, "algoFrameLen is invalid");
129 float maxEnvelopeLevel = 0.0f;
130 for (int32_t i = 0; i < algoFrameLen - 1; i += AUDIO_LMT_ALGO_CHANNEL) {
131 float tempBufInLeft = inBuffer[i];
132 float tempBufInRight = inBuffer[i + 1];
133 float tempLevel = std::max(std::abs(tempBufInLeft), std::abs(tempBufInRight));
134 float coeff = tempLevel > nextLev_ ? levelAttack_ : levelRelease_;
135 nextLev_ = coeff * nextLev_ + (1 - coeff) * tempLevel;
136 maxEnvelopeLevel = std::max(maxEnvelopeLevel, nextLev_);
137 }
138
139 // calculate gain
140 float tempMaxLevel = std::max(maxEnvelopeLevel, curMaxLev_);
141 curMaxLev_ = maxEnvelopeLevel;
142 float targetGain = 1.0f;
143 if (tempMaxLevel != 0) {
144 targetGain = tempMaxLevel > threshold_ ? threshold_ / tempMaxLevel : targetGain;
145 }
146 float lastGain = gain_;
147 float coeff = gain_ > targetGain ? gainAttack_ : gainRelease_;
148 gain_ = coeff * gain_ + (1 - coeff) * targetGain;
149 float deltaGain = (gain_ - lastGain) * AUDIO_LMT_ALGO_CHANNEL / algoFrameLen;
150
151 // apply gain
152 if (algoFrameLen % AUDIO_LMT_ALGO_CHANNEL == 0) {
153 for (int32_t i = 0; i < algoFrameLen; i += AUDIO_LMT_ALGO_CHANNEL) {
154 lastGain += deltaGain;
155 outBuffer[i] = bufHis_[i] * lastGain;
156 outBuffer[i + 1] = bufHis_[i + 1] * lastGain;
157 bufHis_[i] = inBuffer[i];
158 bufHis_[i + 1] = inBuffer[i + 1];
159 }
160 } else {
161 outBuffer[0] = bufHis_[0];
162 bufHis_[0] = bufHis_[algoFrameLen];
163 for (int32_t i = 1; i < algoFrameLen - 1; i += AUDIO_LMT_ALGO_CHANNEL) {
164 lastGain += deltaGain;
165 outBuffer[i] = bufHis_[i] * lastGain;
166 outBuffer[i + 1] = bufHis_[i + 1] * lastGain;
167 bufHis_[i] = inBuffer[i - 1];
168 bufHis_[i + 1] = inBuffer[i];
169 }
170 bufHis_[algoFrameLen] = inBuffer[algoFrameLen - 1];
171 }
172 }
173
GetLatency()174 uint32_t AudioLimiter::GetLatency()
175 {
176 return latency_;
177 }
178 } // namespace AudioStandard
179 } // namespace OHOS
180