GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
Sound.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_SOUND_HPP
5#define GREM_AUDIO_SOUND_HPP
6
8
18
19#include <new> // std::launder
20#include <type_traits> // std::remove_cvref_t
21#include <utility> // std::move
22
23namespace grem::audio {
24
28enum class SoundAttenuationModel : uint8_t { // NOLINT(performance-enum-size)
34
53
71
90};
91
105
114 float volume = 1.0f;
115
129 float minDistance = 1.0f;
130
146
161 float rolloffFactor = 1.0f;
162
171 float dopplerFactor = 1.0f;
172
181 bool useDistanceDelay = false;
182
190 bool listenerRelative = false;
191
196 bool looping = false;
197
205 bool singleInstance = false;
206
214 bool streamed = false;
215
223 [[nodiscard]] constexpr bool operator==(const SoundOptions& other) const = default;
224};
225
233class Sound {
234public:
238 static constexpr size_t MAX_FILTER_COUNT = 8;
239
243 Sound() noexcept = default;
244
266 GREM_API(audio) Sound(const Filesystem& filesystem, CStringView filepath, const SoundOptions& options = {});
267
284 GREM_API(audio) explicit Sound(Span<const byte> fileContents, const SoundOptions& options = {});
285
300 GREM_API(audio) Sound(Span<const uint8_t> samples, float sampleRate, size_t channelCount = 1, const SoundOptions& options = {});
301
316 GREM_API(audio) Sound(Span<const int16_t> samples, float sampleRate, size_t channelCount = 1, const SoundOptions& options = {});
317
332 GREM_API(audio) Sound(Span<const float32_t> samples, float sampleRate, size_t channelCount = 1, const SoundOptions& options = {});
333
339 explicit operator bool() const noexcept {
340 return static_cast<bool>(sourceHandle);
341 }
342
366 template <filter F>
367 void setFilter(size_t filterSlotIndex, const F& newFilter) {
368 if constexpr (requires(const void* data) { F::GREM_private_createBuiltinFilter(data); }) {
369 detail::Filter filter{F::GREM_private_createBuiltinFilter(static_cast<const void*>(static_cast<const F*>(&newFilter)))};
370 setFilterImplementation(filterSlotIndex, std::move(filter));
371 } else {
372 static_assert(trivially_copyable<F>);
373 static constexpr detail::FilterFunction doFilter =
374 [](byte* data, Span<float> samples, size_t channelCount, size_t sampleCountPerChannel, float sampleRate, double time) -> void {
375 std::launder(reinterpret_cast<F*>(data))->filter(samples, channelCount, sampleCountPerChannel, sampleRate, time);
376 };
377 if constexpr (requires { newFilter.parameters; }) {
378 using Parameters = std::remove_cvref_t<decltype(newFilter.parameters)>;
379 const size_t parametersOffset = std::launder(reinterpret_cast<const byte*>(&newFilter.parameters)) - std::launder(reinterpret_cast<const byte*>(&newFilter));
380 detail::Filter filter{
381 detail::createCustomFilter(asBytes(Span{static_cast<const F*>(&newFilter), 1}), parametersOffset, detail::FILTER_PARAMETER_DESCRIPTIONS<Parameters>,
382 detail::FILTER_PARAMETER_INFOS<Parameters>, doFilter),
383 };
384 setFilterImplementation(filterSlotIndex, std::move(filter));
385 } else {
386 detail::Filter filter{detail::createCustomFilter(asBytes(Span{static_cast<const F*>(&newFilter), 1}), 0, {}, doFilter)};
387 setFilterImplementation(filterSlotIndex, std::move(filter));
388 }
389 }
390 }
391
398 GREM_API(audio) void removeFilter(size_t filterSlotIndex) noexcept;
399
406 [[nodiscard]] GREM_API(audio) Duration getDuration() const noexcept;
407
418 [[nodiscard]] void* get() noexcept { // NOLINT(readability-make-member-function-const)
419 return sourceHandle.get();
420 }
421
432 [[nodiscard]] const void* get() const noexcept {
433 return sourceHandle.get();
434 }
435
436protected:
437 GREM_API(audio) Sound(void* handle, const SoundOptions& options);
438
439private:
440 struct SoundFileDeleter {
441 GREM_API(audio) void operator()(void* handle) const noexcept;
442 };
443
444 using SoundFileHandle = UniqueHandle<void*, SoundFileDeleter>;
445
446 struct SourceDeleter {
447 GREM_API(audio) void operator()(void* handle) const noexcept;
448 };
449
450 using SourceHandle = UniqueHandle<void*, SourceDeleter>;
451
452 GREM_API(audio) void setFilterImplementation(size_t filterSlotIndex, detail::Filter filter);
453
454 SoundFileHandle soundFileHandle{};
455 SourceHandle sourceHandle{};
456 UniquePointer<detail::Filter[]> filters{};
457 bool streamed;
458};
459
460} // namespace grem::audio
461
462#endif
Base interface for a filesystem.
Definition Filesystem.hpp:25
Definition Span.hpp:146
Generic nullable RAII resource handle with exclusive ownership of a resource that is automatically de...
Definition UniqueHandle.hpp:26
const void * get() const noexcept
Get an opaque handle to the internal representation of the sound.
Definition Sound.hpp:432
Duration getDuration() const noexcept
Get the duration of the sound.
void setFilter(size_t filterSlotIndex, const F &newFilter)
Set the filter at a particular filter slot of the sound.
Definition Sound.hpp:367
Sound(Span< const byte > fileContents, const SoundOptions &options={})
Load a sound from an in-memory file.
Sound(void *handle, const SoundOptions &options)
Sound() noexcept=default
Construct an invalid sound that must be reassigned before use.
Sound(Span< const int16_t > samples, float sampleRate, size_t channelCount=1, const SoundOptions &options={})
Construct a sound wave from a raw array of samples.
void removeFilter(size_t filterSlotIndex) noexcept
Remove the filter at a particular filter slot of the sound.
Sound(Span< const float32_t > samples, float sampleRate, size_t channelCount=1, const SoundOptions &options={})
Construct a sound wave from a raw array of samples.
static constexpr size_t MAX_FILTER_COUNT
Maximum number of filters that can be applied simultaneously to a sound.
Definition Sound.hpp:238
Sound(Span< const uint8_t > samples, float sampleRate, size_t channelCount=1, const SoundOptions &options={})
Construct a sound wave from a raw array of samples.
void * get() noexcept
Get an opaque handle to the internal representation of the sound.
Definition Sound.hpp:418
Concept that checks if a type is a valid sound filter type.
Definition filters.hpp:246
Definition concepts.hpp:187
Definition Error.hpp:12
SoundAttenuationModel
Distance attenuation/falloff model for 3D positional audio.
Definition Sound.hpp:28
@ INVERSE_DISTANCE
Attenuate the amplitude of the sound by the inverse distance between the sound instance and the liste...
Definition Sound.hpp:52
@ EXPONENTIAL_DISTANCE
Attenuate the amplitude of the sound by the exponential distance between the sound instance and the l...
Definition Sound.hpp:89
@ LINEAR_DISTANCE
Attenuate the amplitude of the sound by the linear distance between the sound instance and the listen...
Definition Sound.hpp:70
@ NO_ATTENUATION
No distance attenuation; sound has the same volume regardless of distance between the sound instance ...
Definition Sound.hpp:33
Clock::duration Duration
Definition Clock.hpp:25
auto asBytes(Span< T, N > s) noexcept
Definition Span.hpp:359
CStringViewBase< char, std::char_traits< char > > CStringView
Definition CStringView.hpp:635
static constexpr T MAX
Definition fundamentals.hpp:29
Configuration options for a Sound.
Definition Sound.hpp:95
float dopplerFactor
Strength of the doppler effect for this sound.
Definition Sound.hpp:171
float minDistance
Minimum distance of the range where the distance between the sound instance and listener changes the ...
Definition Sound.hpp:129
bool singleInstance
Override any instances of this sound that are already playing when a new instance is played.
Definition Sound.hpp:205
bool looping
Default to playing instances of this sound on repeat instead of just playing them once.
Definition Sound.hpp:196
SoundAttenuationModel attenuationModel
Which distance attenuation/falloff model to use for 3D positional audio when playing this sound.
Definition Sound.hpp:104
float maxDistance
Maximum distance of the range where the distance between the sound instance and listener changes soun...
Definition Sound.hpp:145
float volume
Default volume of instances of this sound, which is used if no volume override is specified when the ...
Definition Sound.hpp:114
bool useDistanceDelay
Simulate the delay due to the speed of sound between the sound being played and the sound being heard...
Definition Sound.hpp:181
constexpr bool operator==(const SoundOptions &other) const =default
Compare these options to another set of options for equality.
bool listenerRelative
Don't take the listener's sound stage position into account when playing this sound in 3D.
Definition Sound.hpp:190
float rolloffFactor
Rolloff factor to use in the attenuation/falloff calculation for this sound.
Definition Sound.hpp:161
bool streamed
Stream in the contents of the sound file gradually as the sound plays instead of loading the whole fi...
Definition Sound.hpp:214