Skip to content

Commit

Permalink
Smooth gain for normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
emcifuntik committed Oct 25, 2023
1 parent 07b6cb4 commit 227976f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
32 changes: 23 additions & 9 deletions src/CSoundInput.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -288,29 +288,43 @@ bool CSoundInput::IsNormalizationEnabled() const
return normalizationEnabled;
}

void CSoundInput::Normalize(void* buffer, DWORD length)
void CSoundInput::Normalize(void* buffer, DWORD sampleCount)
{
short maxFrame = 0;
for (int i = 0; i < length; ++i)
for (int i = 0; i < sampleCount; ++i)
{
short s = abs(((short*)buffer)[i]);
if (s > maxFrame)
maxFrame = s;
}

if (normalizeMax == 0.f || maxFrame > normalizeMax || normalizeMax / maxFrame < 0.5)
// Update normalizeMax using a running average or directly based on conditions
if (normalizeMax == 0.f || maxFrame > normalizeMax || normalizeMax / maxFrame < 0.5) {
normalizeMax = maxFrame;
else
}
else {
normalizeMax = (normalizeMax * (NORMALIZE_FRAME_COUNT - 1) + maxFrame) / NORMALIZE_FRAME_COUNT;
}

if (normalizeMax <= 1.f)
if (normalizeMax <= 1.f) {
return;
}

float desiredGain = MAXSHORT / normalizeMax / 2;
desiredGain = std::fmin(desiredGain, 10.0f);

float gain = MAXSHORT / normalizeMax / 2;
gain = std::fmin<float, float>(gain, 10);
// Smooth the transition of gain
static float currentGain = 1.0f;
float smoothingFactor = 0.05f;
currentNormalizationGain = (1 - smoothingFactor) * currentNormalizationGain + smoothingFactor * desiredGain;

for (int i = 0; i < length; ++i)
((short*)buffer)[i] *= gain;
const auto shortSamples = static_cast<short*>(buffer);

for (int i = 0; i < sampleCount; ++i)
{
float processedSample = (float)shortSamples[i] * currentGain;
shortSamples[i] = static_cast<int16_t>(clampFloatSample(processedSample));
}
}

void CSoundInput::NormalizeDSP(HDSP handle, DWORD channel, void* buffer, DWORD length, void* user)
Expand Down
1 change: 1 addition & 0 deletions src/CSoundInput.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class CSoundInput : public ISoundInput
float volume = 1.f;
float micLevel = 0.f;
float micLevelDb = 0.f;
float currentNormalizationGain = 1.f;
bool noiseSuppressionEnabled = false;

bool normalizationEnabled = false;
Expand Down

0 comments on commit 227976f

Please sign in to comment.