GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
filters.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_AUDIO_FILTERS_HPP
5#define GREM_AUDIO_FILTERS_HPP
6
8
18
19namespace grem::audio {
20
21class Sound; // Forward declaration, to avoid a circular include of Sound.hpp.
22class SoundStage; // Forward declaration, to avoid a circular include of SoundStage.hpp.
23
24namespace detail {
25
26//==============================================================================
27
28// Example user-defined filter options (see ExampleFilter).
29struct ExampleFilterOptions {
30 float gain = 1.0f; // See ExampleFilter::Parameters::gain.
31};
32
33// Example user-defined filter definition, showing how custom filter types can be defined.
34// Also used to test the audio::filter concept.
35// This example implements a basic amplification filter with a configurable gain parameter.
36class ExampleFilter {
37public:
38 // Dynamic filter parameters that can be set/faded at any time during playback.
39 // If present, this must be a public field with the exact name "parameters" of an aggregate struct type.
40 // The struct type can have any name, but "Parameters" is recommended for consistency with the built-in filters.
41 // The following parameter types are supported:
42 // - bool
43 // - int8_t
44 // - int16_t
45 // - int32_t
46 // - uint8_t
47 // - uint16_t
48 // - uint32_t
49 // - float32_t (float)
50 struct Parameters {
51 float gain; // Example filter parameter. Controls gain in this example, i.e. how much the filter should amplify the sound.
52 } parameters;
53
54 // Constructor for initializing the filter parameters, which can have any signature (or be omitted).
55 // This pattern of taking a separate "options" struct is not required, but is recommended for extensibility and ease of use.
56 explicit ExampleFilter(const ExampleFilterOptions& options)
57 : parameters{.gain = options.gain} {}
58
59 // Main filter callback. Must be public and have this exact function signature.
60 void filter(Span<float> samples, size_t channelCount, size_t sampleCountPerChannel, float sampleRate, double time) const {
61 // Arguments provided by the sound engine:
62 // - samples: Writable view over the sound samples to apply the filter to, consisting of `sampleCountPerChannel` contiguous samples for each channel in `channelCount`.
63 // - channelCount: Number of separate channels that the `samples` buffer is split into.
64 // - sampleCountPerChannel: Number of samples per channel in `samples`. Always equal to `samples.size() / channelCount`.
65 // - sampleRate: Sample rate of the sound, in Hertz (samples per second).
66 // - time: Current playback time point in the sound stream, in seconds.
67
68 // This basic filter doesn't need to use any arguments besides `samples` since it just applies uniformly to all samples across all channels.
69 (void)channelCount;
70 (void)sampleCountPerChannel;
71 (void)sampleRate;
72 (void)time;
73
74 // Example filter behavior: Amplify each sample by the specified gain parameter.
75 for (float& sample : samples) {
76 sample *= parameters.gain;
77 }
78 }
79};
80
81//==============================================================================
82
83enum class FilterParameterType : uint32_t { // NOLINT(performance-enum-size)
84 BOOL,
85 INT8,
86 INT16,
87 INT32,
88 UINT8,
89 UINT16,
90 UINT32,
91 FLOAT32,
92};
93
94struct FilterParameterDescription {
95 FilterParameterType type;
96 uint32_t byteOffset;
97};
98
99struct FilterParameterInfo {
100 CStringView name;
101 float minValue;
102 float maxValue;
103};
104
105template <typename FilterParameterStruct>
106[[nodiscard]] constexpr auto getFilterParameterDescriptions() {
107 static_assert(aggregate<FilterParameterStruct>);
108 static_assert(standard_layout<FilterParameterStruct>);
110 size_t byteOffset = 0;
111 meta::forEachIndexedFieldType<FilterParameterStruct>([&]<typename T>(auto index, meta::Type<T>) -> void {
112 FilterParameterType type{};
113 if constexpr (same_as<T, bool>) {
114 type = FilterParameterType::BOOL;
115 } else if constexpr (enumeration<T>) {
116 if constexpr (sizeof(T) == 1) {
117 type = FilterParameterType::UINT8;
118 } else if constexpr (sizeof(T) == 2) {
119 type = FilterParameterType::UINT16;
120 } else if constexpr (sizeof(T) == 4) {
121 type = FilterParameterType::UINT32;
122 } else {
123 unreachable();
124 }
125 } else if constexpr (integral<T>) {
126 if constexpr (signed_integral<T>) {
127 if constexpr (sizeof(T) == 1) {
128 type = FilterParameterType::INT8;
129 } else if constexpr (sizeof(T) == 2) {
130 type = FilterParameterType::INT16;
131 } else if constexpr (sizeof(T) == 4) {
132 type = FilterParameterType::INT32;
133 } else {
134 unreachable();
135 }
136 } else {
137 if constexpr (sizeof(T) == 1) {
138 type = FilterParameterType::UINT8;
139 } else if constexpr (sizeof(T) == 2) {
140 type = FilterParameterType::UINT16;
141 } else if constexpr (sizeof(T) == 4) {
142 type = FilterParameterType::UINT32;
143 } else {
144 unreachable();
145 }
146 }
147 } else if constexpr (floating_point<T>) {
148 if constexpr (sizeof(T) == 4) {
149 type = FilterParameterType::FLOAT32;
150 } else {
151 unreachable();
152 }
153 } else {
154 unreachable();
155 }
156
157 byteOffset = roundUpToMultiple(byteOffset, alignof(T));
158
159 GREM_ASSERT(byteOffset <= size_t{Limits<uint32_t>::MAX});
160
161 result[index] = {
162 .type = type,
163 .byteOffset = static_cast<uint32_t>(byteOffset),
164 };
165 byteOffset += sizeof(T);
166 });
167 return result;
168}
169
170template <typename FilterParameterStruct>
171[[nodiscard]] constexpr auto getFilterParameterInfos() {
172 static_assert(aggregate<FilterParameterStruct>);
173 static_assert(standard_layout<FilterParameterStruct>);
175 meta::forEachIndexedFieldType<FilterParameterStruct>([&]<typename T>(auto index, meta::Type<T>) -> void {
176 float minValue = 0.0f;
177 float maxValue = 0.0f;
178 if constexpr (same_as<T, bool>) {
179 minValue = 0.0f;
180 maxValue = 1.0f;
181 } else if constexpr (enumeration<T>) {
182 if constexpr (sizeof(T) == 1) {
183 minValue = 0.0f;
184 maxValue = float{Limits<uint8_t>::MAX};
185 } else if constexpr (sizeof(T) == 2) {
186 minValue = 0.0f;
187 maxValue = float{Limits<uint16_t>::MAX};
188 } else if constexpr (sizeof(T) == 4) {
189 minValue = 0.0f;
190 maxValue = Limits<float>::MAX;
191 } else {
192 unreachable();
193 }
194 } else if constexpr (floating_point<T>) {
195 minValue = Limits<float>::MIN;
196 maxValue = Limits<float>::MAX;
197 } else if constexpr (integral<T>) {
198 if constexpr (int64_t{Limits<T>::MIN} <= int64_t{Limits<int32_t>::MIN}) {
199 minValue = Limits<float>::MIN;
200 } else {
201 minValue = float{Limits<T>::MIN};
202 }
203 if constexpr (uint64_t{Limits<T>::MAX} >= uint64_t{Limits<int32_t>::MAX}) {
204 maxValue = Limits<float>::MAX;
205 } else {
206 maxValue = float{Limits<T>::MAX};
207 }
208 } else {
209 unreachable();
210 }
211
212 result[index] = {
214 .minValue = minValue,
215 .maxValue = maxValue,
216 };
217 });
218 return result;
219}
220
221template <typename FilterParameterStruct>
222inline constexpr auto FILTER_PARAMETER_DESCRIPTIONS = getFilterParameterDescriptions<FilterParameterStruct>();
223
224template <typename FilterParameterStruct>
225inline constexpr auto FILTER_PARAMETER_INFOS = getFilterParameterInfos<FilterParameterStruct>();
226
227using FilterFunction = void (*)(byte* data, Span<float> samples, size_t channelCount, size_t sampleCountPerChannel, float sampleRate, double time);
228
229struct FilterDeleter {
230 GREM_API(audio) void operator()(void* handle) const noexcept;
231};
232
233using Filter = UniqueHandle<void*, FilterDeleter>;
234
235[[nodiscard]] GREM_API(audio) void* createCustomFilter(Span<const byte> initialData, size_t parametersOffset, Span<const FilterParameterDescription> parameterDescriptions,
236 Span<const FilterParameterInfo> parameterInfos, FilterFunction doFilter);
237
238} // namespace detail
239
245template <typename T>
246concept filter = trivially_copyable<T> && ((requires(const void* data) {
247 T::GREM_private_createBuiltinFilter(data);
248}) || (requires(T t, const Span<float> samples, const size_t channelCount, const size_t sampleCountPerChannel, const float sampleRate, const double time) {
249 t.filter(samples, channelCount, sampleCountPerChannel, sampleRate, time);
250}));
251
252static_assert(filter<detail::ExampleFilter>); // Make sure the example filter is considered valid.
253
257enum class BiquadResonantFilterType : int { // NOLINT(performance-enum-size)
261};
262
290
296public:
297 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
298
302 struct Parameters {
303 float wet = 1.0f;
305 float resonance;
307
314 : parameters{
315 .cutoffFrequency = options.cutoffFrequency,
316 .resonance = options.resonance,
317 }
318 , type(options.type) {}
319
320private:
322};
323
333 float delay = 0.5f; // (0, inf)
334
340 float decay = 0.7f;
341
347 float filter = 0.0f;
348};
349
355public:
356 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
357
363 explicit EchoFilter(const EchoFilterOptions& options)
364 : options(options) {}
365
366private:
367 EchoFilterOptions options;
368};
369
379 float sampleRate = 11000.0f;
380
386 float bitDepth = 4.0f;
387};
388
394public:
395 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
396
400 struct Parameters {
401 float wet = 1.0f;
403 float bitDepth;
405
411 explicit LoFiFilter(const LoFiFilterOptions& options)
412 : parameters{
413 .sampleRate = options.sampleRate,
414 .bitDepth = options.bitDepth,
415 } {}
416};
417
427 float delay = 0.05f;
428
434 float frequency = 10.0f;
435};
436
443public:
444 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
445
449 struct Parameters {
450 float wet = 1.0f;
451 float delay;
452 float frequency;
454
460 explicit FlangerFilter(const FlangerFilterOptions& options)
461 : parameters{
462 .delay = options.delay,
463 .frequency = options.frequency,
464 } {}
465};
466
476 float length = 0.1f;
477};
478
487public:
488 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
489
496 : options(options) {}
497
498private:
500};
501
511 bool freeze = false;
512
518 float roomSize = 0.5f;
519
525 float damping = 0.5f;
526
532 float width = 1.0f;
533};
534
539public:
540 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
541
545 struct Parameters {
546 float wet = 1.0f;
547 bool freeze;
548 float roomSize;
549 float damping;
550 float width;
552
558 explicit FreeverbFilter(const FreeverbFilterOptions& options)
559 : parameters{
560 .freeze = options.freeze,
561 .roomSize = options.roomSize,
562 .damping = options.damping,
563 .width = options.width,
564 } {}
565};
566
576 float band1Volume = 1.0f;
577
583 float band2Volume = 1.0f;
584
590 float band3Volume = 1.0f;
591
597 float band4Volume = 1.0f;
598
604 float band5Volume = 1.0f;
605
611 float band6Volume = 1.0f;
612
618 float band7Volume = 1.0f;
619
625 float band8Volume = 1.0f;
626};
627
633public:
634 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
635
647
654 : parameters{
655 .band1Volume = options.band1Volume,
656 .band2Volume = options.band2Volume,
657 .band3Volume = options.band3Volume,
658 .band4Volume = options.band4Volume,
659 .band5Volume = options.band5Volume,
660 .band6Volume = options.band6Volume,
661 .band7Volume = options.band7Volume,
662 .band8Volume = options.band8Volume,
663 } {}
664};
665
675 float onRamp = 0.05f;
676
682 float offRamp = 0.5f;
683
689 float level = 0.5f;
690};
691
697public:
698 [[nodiscard]] GREM_API(audio) static void* GREM_private_createBuiltinFilter(const void* data); // Internal function. Do not call in user code.
699
707 explicit DuckingFilter(SoundStage& soundStage, SoundInstanceID listenTo, const DuckingFilterOptions& options)
708 : soundStage(&soundStage)
709 , listenTo(listenTo)
710 , options(options) {}
711
712private:
713 SoundStage* soundStage;
714 SoundInstanceID listenTo;
715 DuckingFilterOptions options;
716};
717
718} // namespace grem::audio
719
720#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Definition Span.hpp:146
BiquadResonantFilter(const BiquadResonantFilterOptions &options)
Construct a biquadratic resonant filter.
Definition filters.hpp:313
struct grem::audio::BiquadResonantFilter::Parameters parameters
DCRemovalFilter(const DCRemovalFilterOptions &options)
Construct a DC removal filter.
Definition filters.hpp:495
DuckingFilter(SoundStage &soundStage, SoundInstanceID listenTo, const DuckingFilterOptions &options)
Construct a ducking filter.
Definition filters.hpp:707
EchoFilter(const EchoFilterOptions &options)
Construct an echo filter.
Definition filters.hpp:363
struct grem::audio::EqualizationFilter::Parameters parameters
EqualizationFilter(const EqualizationFilterOptions &options)
Construct an equalization filter.
Definition filters.hpp:653
FlangerFilter(const FlangerFilterOptions &options)
Construct a flanger filter.
Definition filters.hpp:460
struct grem::audio::FlangerFilter::Parameters parameters
FreeverbFilter(const FreeverbFilterOptions &options)
Construct a Freeverb filter.
Definition filters.hpp:558
struct grem::audio::FreeverbFilter::Parameters parameters
LoFiFilter(const LoFiFilterOptions &options)
Construct a lo-fi filter.
Definition filters.hpp:411
struct grem::audio::LoFiFilter::Parameters parameters
Persistent system for playing sound in a simulated 3D arena to the default audio device.
Definition SoundStage.hpp:122
Container for a particular sound wave that can be played in a SoundStage.
Definition Sound.hpp:233
Concept that checks if a type is a valid sound filter type.
Definition filters.hpp:246
Definition concepts.hpp:187
Definition Error.hpp:12
BiquadResonantFilterType
Filter type of a BiquadResonantFilter.
Definition filters.hpp:257
@ BANDPASS
Preserve the sound frequencies near the cutoff frequency, filter those above and below.
Definition filters.hpp:260
@ HIGHPASS
Preserve the sound frequencies above the cutoff frequency, filter those below.
Definition filters.hpp:259
@ LOWPASS
Preserve the sound frequencies below the cutoff frequency, filter those above.
Definition filters.hpp:258
@ T
't'
Definition keyboard.hpp:90
constexpr auto aggregate_field_name_v
Name of the field at a given index of an aggregate type.
Definition metaprogramming.hpp:1568
constexpr void forEachIndexedFieldType(auto fn)
Execute a function for each field type of an aggregate, also including the field index.
Definition metaprogramming.hpp:1160
Array(T, Us...) -> Array< T, 1+sizeof...(Us)>
GREM_ALWAYS_INLINE constexpr UnsignedInteger roundUpToMultiple(UnsignedInteger value, UnsignedInteger n)
Get the smallest multiple of n that is not greater than a given value.
Definition fundamentals.hpp:822
Span(R &&range) -> Span< std::remove_reference_t< decltype(*std::data(range))> >
void unreachable()
Definition assertions.hpp:125
auto sample(forward_range auto &&range, auto outputIterator, auto n, auto &&uniformRandomBitGenerator)
Definition algorithms.hpp:629
CStringViewBase< char, std::char_traits< char > > CStringView
Definition CStringView.hpp:635
static constexpr T MAX
Definition fundamentals.hpp:29
static constexpr T MIN
Definition fundamentals.hpp:28
Configuration options for a BiquadResonantFilter.
Definition filters.hpp:266
float resonance
Resonance/sharpness parameter of the filter.
Definition filters.hpp:288
BiquadResonantFilterType type
Filter type that determines which sound frequencies to preserve/filter.
Definition filters.hpp:270
float cutoffFrequency
Cutoff frequency of the filter, in Hertz.
Definition filters.hpp:279
Dynamic filter parameters that can be set/faded on-the-fly.
Definition filters.hpp:302
float resonance
See BiquadResonantFilterOptions::resonance.
Definition filters.hpp:305
float cutoffFrequency
See BiquadResonantFilterOptions::cutoffFrequency.
Definition filters.hpp:304
float wet
Filter active amount (0 for unfiltered, 1 for fully filtered).
Definition filters.hpp:303
Configuration options for a DCRemovalFilter.
Definition filters.hpp:470
float length
Length of the averaging buffer, in seconds.
Definition filters.hpp:476
Configuration options for a DuckingFilter.
Definition filters.hpp:669
float onRamp
On-ramp parameter.
Definition filters.hpp:675
float level
Level parameter.
Definition filters.hpp:689
float offRamp
Off-ramp parameter.
Definition filters.hpp:682
Configuration options for an EchoFilter.
Definition filters.hpp:327
float decay
Echo decay multiplier.
Definition filters.hpp:340
float delay
Echo delay in seconds.
Definition filters.hpp:333
Configuration options for an EqualizationFilter.
Definition filters.hpp:570
float band5Volume
Volume/gain of frequency band 5 of 8.
Definition filters.hpp:604
float band2Volume
Volume/gain of frequency band 2 of 8.
Definition filters.hpp:583
float band3Volume
Volume/gain of frequency band 3 of 8.
Definition filters.hpp:590
float band1Volume
Volume/gain of frequency band 1 of 8.
Definition filters.hpp:576
float band4Volume
Volume/gain of frequency band 4 of 8.
Definition filters.hpp:597
float band8Volume
Volume/gain of frequency band 8 of 8.
Definition filters.hpp:625
float band6Volume
Volume/gain of frequency band 6 of 8.
Definition filters.hpp:611
float band7Volume
Volume/gain of frequency band 7 of 8.
Definition filters.hpp:618
float band2Volume
See EqualizationFilterOptions::band2Volume.
Definition filters.hpp:639
float band6Volume
See EqualizationFilterOptions::band6Volume.
Definition filters.hpp:643
float band1Volume
See EqualizationFilterOptions::band1Volume.
Definition filters.hpp:638
float wet
Filter active amount (0 for unfiltered, 1 for fully filtered).
Definition filters.hpp:637
float band5Volume
See EqualizationFilterOptions::band5Volume.
Definition filters.hpp:642
float band7Volume
See EqualizationFilterOptions::band7Volume.
Definition filters.hpp:644
float band3Volume
See EqualizationFilterOptions::band3Volume.
Definition filters.hpp:640
float band8Volume
See EqualizationFilterOptions::band8Volume.
Definition filters.hpp:645
float band4Volume
See EqualizationFilterOptions::band4Volume.
Definition filters.hpp:641
Configuration options for a FlangerFilter.
Definition filters.hpp:421
float frequency
Frequency of the flanger effect, in Hertz.
Definition filters.hpp:434
float delay
Delay of the flanger effect, in seconds.
Definition filters.hpp:427
Dynamic filter parameters that can be set/faded on-the-fly.
Definition filters.hpp:449
float wet
Filter active amount (0 for unfiltered, 1 for fully filtered).
Definition filters.hpp:450
float delay
See FlangerFilterOptions::delay.
Definition filters.hpp:451
float frequency
See FlangerFilterOptions::frequency.
Definition filters.hpp:452
Configuration options for a FreeverbFilter.
Definition filters.hpp:505
float damping
Freeverb damping parameter.
Definition filters.hpp:525
float width
Freeverb width parameter.
Definition filters.hpp:532
float roomSize
Freeverb room size parameter.
Definition filters.hpp:518
bool freeze
Freeverb mode parameter.
Definition filters.hpp:511
Dynamic filter parameters that can be set/faded on-the-fly.
Definition filters.hpp:545
bool freeze
See FreeverbFilterOptions::freeze.
Definition filters.hpp:547
float damping
See FreeverbFilterOptions::damping.
Definition filters.hpp:549
float wet
Filter active amount (0 for unfiltered, 1 for fully filtered).
Definition filters.hpp:546
float width
See FreeverbFilterOptions::width.
Definition filters.hpp:550
float roomSize
See FreeverbFilterOptions::roomSize.
Definition filters.hpp:548
Configuration options for a LoFiFilter.
Definition filters.hpp:373
float sampleRate
Sample rate of the filter, in Hertz.
Definition filters.hpp:379
float bitDepth
Bit depth of the filter.
Definition filters.hpp:386
Dynamic filter parameters that can be set/faded on-the-fly.
Definition filters.hpp:400
float sampleRate
See LoFiFilterOptions::sampleRate.
Definition filters.hpp:402
float wet
Filter active amount (0 for unfiltered, 1 for fully filtered).
Definition filters.hpp:401
float bitDepth
See LoFiFilterOptions::bitDepth.
Definition filters.hpp:403
Opaque handle to a specific instance of a sound or sound mix playing in a sound stage or sound mix.
Definition SoundInstanceID.hpp:23