Mesen-SX/Utilities/LowPassFilter.h

43 lines
1.1 KiB
C
Raw Normal View History

2019-02-13 14:10:36 -05:00
#pragma once
#include "stdafx.h"
#include <assert.h>
#include <numeric>
class LowPassFilter
{
private:
uint8_t _prevSampleCounter = 0;
2020-12-19 23:32:47 +03:00
int16_t _prevSamplesLeft[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int16_t _prevSamplesRight[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2019-02-13 14:10:36 -05:00
2020-12-19 23:32:47 +03:00
void UpdateSample(int16_t* buffer, size_t index, int strength, double volume, int16_t* _prevSamples)
2019-02-13 14:10:36 -05:00
{
2020-12-19 23:32:47 +03:00
if (strength > 0)
{
2019-02-13 14:10:36 -05:00
int32_t sum = std::accumulate(_prevSamples, _prevSamples + strength, 0);
buffer[index] = (int16_t)((sum + buffer[index]) / (strength + 1) * volume);
_prevSamples[_prevSampleCounter] = buffer[index];
2020-12-19 23:32:47 +03:00
}
else
{
2019-02-13 14:10:36 -05:00
buffer[index] = (int16_t)(buffer[index] * volume);
}
}
public:
2020-12-19 23:32:47 +03:00
void ApplyFilter(int16_t* buffer, size_t sampleCount, int strength, double volume = 1.0f)
2019-02-13 14:10:36 -05:00
{
assert(strength <= 10);
2020-12-19 23:32:47 +03:00
for (size_t i = 0; i < sampleCount * 2; i += 2)
{
2019-02-13 14:10:36 -05:00
UpdateSample(buffer, i, strength, volume, _prevSamplesLeft);
2020-12-19 23:32:47 +03:00
UpdateSample(buffer, i + 1, strength, volume, _prevSamplesRight);
if (strength > 0)
{
2019-02-13 14:10:36 -05:00
_prevSampleCounter = (_prevSampleCounter + 1) % strength;
}
}
}
2020-12-19 23:32:47 +03:00
};