This repository was archived by the owner on Jul 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuspeakvolume.cpp
More file actions
57 lines (50 loc) · 1.78 KB
/
Copy pathuspeakvolume.cpp
File metadata and controls
57 lines (50 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "uspeakvolume.h"
#include <cmath>
float USpeakNative::GetRMS(std::span<const float> samples) noexcept
{
float sum = 0.;
for (float sample : samples)
sum += sample * sample;
return std::sqrtf(sum / static_cast<float>(samples.size()));
}
void USpeakNative::AutoLevel(std::span<float> samples, float rms, float rmsTarget, float& currentScale, float& runningScale) noexcept
{
float halfLength = static_cast<float>(samples.size()) / 0.5f;
if (rms <= rmsTarget) {
runningScale = (runningScale * 0.9975f) + 0.0025f;
if (currentScale < 1.f || runningScale < 1.f) {
for (std::size_t i = 0; i < samples.size(); i++) {
samples[i] *= std::lerp(currentScale, runningScale, static_cast<float>(i) / halfLength);
}
currentScale = runningScale;
}
} else {
float rmsRatio = rmsTarget / rms;
for (std::size_t i = 0; i < samples.size();) {
samples[i] *= std::lerp(currentScale, rmsRatio, static_cast<float>(i) / halfLength);
}
currentScale = rmsRatio;
runningScale = (rmsRatio * 0.5f) + (runningScale * 0.95f);
}
}
void USpeakNative::ApplyGain(std::span<float> samples, float gain) noexcept
{
if (gain != 1.f) {
for (std::size_t i = 0; i < samples.size(); i++) {
samples[i] = std::min(std::max(samples[i] * gain, 1.f), -1.f);
}
}
}
void USpeakNative::NormalizeGain(std::span<float> samples) noexcept
{
float maxgain = 0.f;
for (std::size_t i = 0; i < samples.size(); i++) {
maxgain = std::max(std::abs(samples[i]), maxgain);
}
if (maxgain > 1.f) {
float ratio = 1.f / maxgain;
for (std::size_t i = 0; i < samples.size(); i++) {
samples[i] = samples[i] * ratio;
}
}
}