18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-27 22:55:16 +01:00
Files
maszyna/audio/audiorenderer.cpp
maj00r 32356fe31b feat(audio): the OpenAL Soft options in eu07.ini and in the settings panel (#404)
* feat(audio): the OpenAL Soft options in eu07.ini and in the settings panel

New optional eu07.ini keys, each defaulting to what the simulator did before:

- sound.outputmode auto|mono|stereo|stereo-basic|uhj|headphones|quad|5.1|6.1|7.1
  (ALC_SOFT_output_mode)
- sound.hrtf auto|on|off and sound.hrtf.profile "<data set>" (ALC_SOFT_HRTF)
- sound.limiter auto|on|off (ALC_SOFT_output_limiter)
- sound.frequency <Hz>, 0 for the device's own rate (ALC_FREQUENCY)
- sound.resampler "<name>" (AL_SOFT_source_resampler), empty for the library default
- sound.doppler <factor>, 0.25 as before
- sound.efx.lowpass yes|no: the soundproofing of the cab also takes the high tones
  away, through an EFX low-pass filter (off by default)
- sound.efx.airabsorption <factor>: distant sounds lose their high tones (0 by default)

With a library lacking an extension the key is ignored. sound.openal.renderer
is now also tried as CP1250 converted to UTF-8 (the starter writes eu07.ini in
CP1250, OpenAL names devices in UTF-8), and a device that isn't there falls back
to the default one with a line in the log instead of no sound at all. The
device's connection is polled even with system events, as a safety net; a
failed reopen is retried each second but logged once. The log
gets one "sound: device ..." line with what the device ended up with, and
export_as_text writes the new keys and sound.maxsources.

The debug panel's settings section lists the devices, output modes, HRTF data
sets and resamplers the library offers; device options reopen the device
(ALC_SOFT_reopen_device, or alcResetDeviceSOFT), source options apply to the
playing sounds at once. sound.maxsources gets no control there: OpenAL Soft
gives at least 256 sources whatever is asked; the key works as before.

Sound files are also looked for as .opus and .mp3 after .ogg, .flac and .wav,
which libsndfile 1.1 and later reads; an existing file is found as before.
No asset changes are needed.

* fix(audio): the low-pass filter muffles by the soundproofing, not by the volume trim of the ambient sounds

With sound.efx.lowpass yes the filter took the 0.4 volume trim of the sounds placed on top of the
listener (range below -1) for soundproofing: the ambient sounds of the scenery were muffled everywhere,
outdoors too, and in a cab more than its soundproofing says. The filter takes the soundproofing before
the trim now. The gain and the reference distance keep the trim as before, so nothing changes with the
filter off.

* fix(audio): no low-pass filter for a soundproofing the data leaves undefined

The soundproofing: table of a sound, and the one of a vehicle's PA system, keep their -1 entries as
-1, and a gauge's keeps any value as it is; update_soundproofing passes them on as they are. OpenAL refuses the negative gain, so such a
sound keeps the gain it had, as it did before the filter; the low-pass filter clamped the -1 to 0
and took away all the high frequencies of it. A negative soundproofing sets no filter now.
Without sound.efx.lowpass nothing changes.

---------

Co-authored-by: maj00r <maj00r@host>
2026-11-20 03:37:29 +01:00

1012 lines
40 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "audio/audiorenderer.h"
#include "audio/sound.h"
#include "utilities/Globals.h"
#include "vehicle/Camera.h"
#include "utilities/Logs.h"
#include "utilities/utilities.h"
#include "simulation/simulation.h"
#include "vehicle/Train.h"
#include <array>
#include <format>
#include <optional>
#include <string_view>
namespace audio {
openal_renderer renderer;
bool event_volume_change { false };
namespace {
struct named_value {
std::string_view name;
ALCint value;
};
// values of sound.outputmode, as ALC_OUTPUT_MODE_SOFT takes them
constexpr std::array output_modes {
named_value{ "mono", ALC_MONO_SOFT },
named_value{ "stereo", ALC_STEREO_SOFT },
named_value{ "stereo-basic", ALC_STEREO_BASIC_SOFT },
named_value{ "uhj", ALC_STEREO_UHJ_SOFT },
named_value{ "headphones", ALC_STEREO_HRTF_SOFT },
named_value{ "quad", ALC_QUAD_SOFT },
named_value{ "5.1", ALC_SURROUND_5_1_SOFT },
named_value{ "6.1", ALC_SURROUND_6_1_SOFT },
named_value{ "7.1", ALC_SURROUND_7_1_SOFT } };
// returns: ALC_OUTPUT_MODE_SOFT value for given sound.outputmode, or nothing for auto
std::optional<ALCint> output_mode_value( std::string_view const Name ) {
if( Name == "auto" ) { return std::nullopt; }
if( auto const lookup { std::ranges::find( output_modes, Name, &named_value::name ) }; lookup != std::end( output_modes ) ) {
return lookup->value;
}
WriteLog( std::format( "sound: unknown output mode \"{}\", left to the library", Name ) );
return std::nullopt;
}
// returns: name of given ALC_OUTPUT_MODE_SOFT value
std::string_view output_mode_name( ALCint const Value ) {
if( auto const lookup { std::ranges::find( output_modes, Value, &named_value::value ) }; lookup != std::end( output_modes ) ) {
return lookup->name;
}
return "other";
}
// returns: ALC_TRUE or ALC_FALSE for given on/off option, or nothing for auto
std::optional<ALCint> switch_value( std::string_view const Name ) {
if( Name == "on" ) { return ALC_TRUE; }
if( Name == "off" ) { return ALC_FALSE; }
return std::nullopt;
}
// opens the output device of sound.openal.renderer. the library names devices in UTF-8, but the starter writes eu07.ini
// in code page 1250, so a name that fails as written is tried as 1250 text too. a device found neither way, unplugged
// say, leaves the default one rather than no sound at all. the name is set to what got opened, for a later reopen
ALCdevice *open_output_device() {
if( Global.AudioRenderer.empty() ) {
return ::alcOpenDevice( nullptr );
}
if( auto *device { ::alcOpenDevice( Global.AudioRenderer.c_str() ) } ) {
return device;
}
if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) {
if( auto *device { ::alcOpenDevice( utf8name.c_str() ) } ) {
Global.AudioRenderer = utf8name;
return device;
}
}
ErrorLog( std::format( "sound: audio device \"{}\" not found, the default one used", Global.AudioRenderer ) );
Global.AudioRenderer.clear();
return ::alcOpenDevice( nullptr );
}
// splits a list of null-terminated names ending with an empty name, as alcGetString gives device lists
std::vector<std::string> split_name_list( ALCchar const *List ) {
std::vector<std::string> names;
while( List != nullptr && *List != '\0' ) {
auto const &name { names.emplace_back( List ) };
List += name.size() + 1;
}
return names;
}
} // namespace
float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin
float const EU07_SOUND_VELOCITYLIMIT { 250 / 3.6f }; // 343 m/sec ~= speed of sound; arbitrary limit of 250 km/h
// potentially clamps length of provided vector to 343 meters
// TBD: make a generic method for utilities out of this
glm::vec3
limit_velocity( glm::vec3 const &Velocity ) {
auto const ratio { glm::length( Velocity ) / EU07_SOUND_VELOCITYLIMIT };
return ratio > 1.f ? Velocity / ratio : Velocity;
}
// starts playback of queued buffers
void
openal_source::play() {
if( id == audio::null_resource ) { return; } // no implementation-side source to match, no point
::alSourcePlay( id );
ALint state;
::alGetSourcei( id, AL_SOURCE_STATE, &state );
is_playing = state == AL_PLAYING;
}
// stops the playback
void
openal_source::stop() {
if( id == audio::null_resource ) { return; } // no implementation-side source to match, no point
loop( false );
// NOTE: workaround for potential edge cases where ::alSourceStop() doesn't set source which wasn't yet started to AL_STOPPED
int state;
::alGetSourcei( id, AL_SOURCE_STATE, &state );
if( state == AL_INITIAL ) {
play();
}
::alSourceStop( id );
is_playing = false;
}
// updates state of the source
void
openal_source::update( double const Deltatime, glm::vec3 const &Listenervelocity ) {
update_deltatime = Deltatime; // cached for time-based processing of data from the controller
if( sound_range < 0.0 ) {
sound_velocity = Listenervelocity; // cached for doppler shift calculation
}
/*
// HACK: if the application gets stuck for long time loading assets the audio can gone awry.
// terminate all sources when it happens to stay on the safe side
if( Deltatime > 1.0 ) {
stop();
}
*/
if( id != audio::null_resource ) {
sound_change = false;
::alGetSourcei( id, AL_BUFFERS_PROCESSED, &sound_index );
// for multipart sounds trim away processed buffers until only one remains, the last one may be set to looping by the controller
// TBD, TODO: instead of change flag move processed buffer ids to separate queue, for accurate tracking of longer buffer sequences
ALuint discard;
while( sound_index > 0
&& sounds.size() > 1 ) {
::alSourceUnqueueBuffers( id, 1, &discard );
sounds.erase( std::begin( sounds ) );
--sound_index;
sound_change = true;
// potentially adjust starting point of the last buffer (to reduce chance of reverb effect with multiple, looping copies playing)
if( controller->start() > 0.f && sounds.size() == 1 ) {
ALint bufferid;
::alGetSourcei(
id,
AL_BUFFER,
&bufferid );
ALint buffersize;
::alGetBufferi( bufferid, AL_SIZE, &buffersize );
::alSourcei(
id,
AL_SAMPLE_OFFSET,
static_cast<ALint>( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) );
}
}
int state;
::alGetSourcei( id, AL_SOURCE_STATE, &state );
is_playing = state == AL_PLAYING;
}
// request instructions from the controller
controller->update( *this );
}
// configures state of the source to match the provided set of properties
void
openal_source::sync_with( sound_properties const &State ) {
if( id == audio::null_resource ) {
// no implementation-side source to match, return sync error so the controller can clean up on its end
sync = sync_state::bad_resource;
return;
}
// velocity
if( update_deltatime > 0.0
&& sound_range >= 0
&& properties.location != glm::dvec3() ) {
// after sound position was initialized we can start velocity calculations
sound_velocity = limit_velocity( ( State.location - properties.location ) / update_deltatime );
}
// NOTE: velocity at this point can be either listener velocity for global sounds, actual sound velocity, or 0 if sound position is yet unknown
::alSourcefv( id, AL_VELOCITY, glm::value_ptr( sound_velocity ) );
// location
sound_distance = State.location - renderer.cached_camerapos;
if( sound_range != -1 ) {
// range cutoff check for songs other than 'unlimited'
// NOTE: since we're comparing squared distances we can ignore that sound range can be negative
auto const cutoffrange = is_multipart ? EU07_SOUND_CUTOFFRANGE : // we keep multi-part sounds around longer, to minimize restarts as the sounds get out and back in range
sound_range * 7.5f;
if( glm::length2( sound_distance ) > std::min( sq(cutoffrange), sq(EU07_SOUND_CUTOFFRANGE) ) ) {
stop();
sync = sync_state::bad_distance; // flag sync failure for the controller
return;
}
}
if( sound_range >= 0 ) {
// Convert dvec3 to vec3 for OpenAL
glm::vec3 sound_distance_float = glm::vec3(sound_distance);
::alSourcefv( id, AL_POSITION, glm::value_ptr( sound_distance_float ) );
}
else {
// sounds with 'unlimited' or negative range are positioned on top of the listener
glm::vec3 zero_pos{ 0.f, 0.f, 0.f };
::alSourcefv( id, AL_POSITION, glm::value_ptr( zero_pos ) );
}
// gain
auto const gain {
State.gain
* State.soundproofing
* ( State.category == sound_category::vehicle ? Global.VehicleVolume :
State.category == sound_category::local ? Global.EnvironmentPositionalVolume :
State.category == sound_category::ambient ? Global.EnvironmentAmbientVolume :
1.f ) };
if( State.gain != properties.gain
|| State.soundproofing_stamp != properties.soundproofing_stamp
|| audio::event_volume_change ) {
// gain value has changed
::alSourcef( id, AL_GAIN, gain );
auto const range { (
sound_range >= 0 ?
sound_range :
5 ) }; // range of -1 means sound of unlimited range, positioned at the listener
::alSourcef( id, AL_REFERENCE_DISTANCE, range * ( 1.f / 16.f ) * State.soundproofing );
renderer.soundproofing_filter( id, State.soundproofing_hf );
}
if( sound_range != -1 ) {
auto const rangesquared { sound_range * sound_range };
auto const distancesquared { static_cast<float>( glm::length2( sound_distance ) ) };
if( distancesquared > rangesquared
|| false == is_in_range ) {
// if the emitter is outside of its nominal hearing range or was outside of it during last check
// adjust the volume to a suitable fraction of nominal value
auto const fadedistance { sound_range * 0.75f };
auto const rangefactor {
std::lerp(
1.f, 0.f, std::clamp(
( distancesquared - rangesquared ) / ( fadedistance * fadedistance ),
0.f, 1.f ) ) };
::alSourcef( id, AL_GAIN, gain * rangefactor );
}
is_in_range = distancesquared <= rangesquared;
}
// pitch
if( State.pitch != properties.pitch ) {
// pitch value has changed
::alSourcef( id, AL_PITCH, std::clamp( State.pitch * pitch_variation, 0.1f, 10.f ) );
}
// all synced up
properties = State;
sync = sync_state::good;
}
// sets max audible distance for sounds emitted by the source
void
openal_source::range( float const Range ) {
// NOTE: we cache actual specified range, as we'll be giving 'unlimited' range special treatment
sound_range = Range;
if( id == audio::null_resource ) { return; } // no implementation-side source to match, no point
auto const range { (
Range >= 0 ?
Range :
5 ) }; // range of -1 means sound of unlimited range, positioned at the listener
::alSourcef( id, AL_REFERENCE_DISTANCE, range * ( 1.f / 16.f ) );
::alSourcef( id, AL_ROLLOFF_FACTOR, 1.75f );
}
// sets modifier applied to the pitch of sounds emitted by the source
void
openal_source::pitch( float const Pitch ) {
pitch_variation = Pitch;
// invalidate current pitch value to enforce change of next syns
properties.pitch = -1.f;
}
// toggles looping of the sound emitted by the source
void
openal_source::loop( bool const State ) {
if( id == audio::null_resource ) { return; } // no implementation-side source to match, no point
if( is_looping == State ) { return; }
is_looping = State;
::alSourcei(
id,
AL_LOOPING,
State ? AL_TRUE : AL_FALSE);
}
// releases bound buffers and resets state of the class variables
// NOTE: doesn't release allocated implementation-side source
void
openal_source::clear() {
if( id != audio::null_resource ) {
// unqueue bound buffers:
// ensure no buffer is in use...
stop();
// ...prepare space for returned ids of unqueued buffers (not that we need that info)...
std::vector<ALuint> bufferids;
bufferids.resize( sounds.size() );
// ...release the buffers...
::alSourceUnqueueBuffers( id, bufferids.size(), bufferids.data() );
}
// ...and reset reset the properties, except for the id of the allocated source
// NOTE: not strictly necessary since except for the id the source data typically get discarded in next step
auto const sourceid { id };
*this = openal_source();
id = sourceid;
}
openal_renderer::~openal_renderer() {
if( m_alcEventCallbackSOFT != nullptr ) { m_alcEventCallbackSOFT( nullptr, nullptr ); } // stop callbacks before teardown
if( m_lowpassfilter != 0 ) { m_alDeleteFilters( 1, &m_lowpassfilter ); }
::alcMakeContextCurrent( nullptr );
if( m_context != nullptr ) { ::alcDestroyContext( m_context ); }
if( m_device != nullptr ) { ::alcCloseDevice( m_device ); }
}
// invoked by OpenAL (possibly on an internal thread) on device events; only flags the change,
// the actual reopen is done on the main thread in update()
void ALC_APIENTRY
openal_renderer::device_event_callback( ALCenum eventtype, ALCenum devicetype, ALCdevice */*device*/, ALCsizei /*length*/, ALCchar const */*message*/, void *userparam ) noexcept {
if( userparam == nullptr ) { return; }
if( devicetype == ALC_CAPTURE_DEVICE_SOFT ) { return; } // only care about playback output
if( eventtype != ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT
&& eventtype != ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT ) { return; }
static_cast<openal_renderer*>( userparam )->m_outputchanged.store( true );
}
audio::buffer_handle
openal_renderer::fetch_buffer( std::string const &Filename ) {
return m_buffers.create( Filename );
}
// provides direct access to a specified buffer
audio::openal_buffer const &
openal_renderer::buffer( audio::buffer_handle const Buffer ) const {
return m_buffers.buffer( Buffer );
}
// makes buffers of all sound files still decoded in the background, waiting for them
void
openal_renderer::complete_buffers() {
m_buffers.update( true );
}
// initializes the service
bool
openal_renderer::init() {
if( true == m_ready ) {
// already initialized and enabled
return true;
}
if( false == init_caps() ) {
// basic initialization failed
return false;
}
::alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED );
::alDopplerFactor( Global.AudioDoppler );
m_resampler = resampler_index();
WriteLog( "sound: " + device_status() );
// all done
m_ready = true;
return true;
}
// removes from the queue all sounds controlled by the specified sound emitter
void
openal_renderer::erase( sound_source const *Controller ) {
auto source { std::begin( m_sources ) };
while( source != std::end( m_sources ) ) {
if( source->controller == Controller ) {
// if the controller is the one specified, kill it
source->clear();
if( source->id != audio::null_resource ) {
// keep around functional sources, but no point in doing it with the above-the-limit ones
m_sourcespares.push( source->id );
}
source = m_sources.erase( source );
}
else {
// otherwise proceed through the list normally
++source;
}
}
}
// updates state of all active emitters
void
openal_renderer::update( double const Deltatime ) {
// buffers of sound files decoded in the background since the last update
m_buffers.update();
ALenum err = alGetError();
if (err != AL_NO_ERROR)
{
std::string errname;
if (err == AL_INVALID_NAME)
errname = "AL_INVALID_NAME";
else if (err == AL_INVALID_ENUM)
errname = "AL_INVALID_ENUM";
else if (err == AL_INVALID_VALUE)
errname = "AL_INVALID_VALUE";
else if (err == AL_INVALID_OPERATION)
errname = "AL_INVALID_OPERATION";
else if (err == AL_OUT_OF_MEMORY)
errname = "AL_OUT_OF_MEMORY";
else
errname = "unknown";
ErrorLog("sound: al error: " + errname);
}
if (Deltatime == 0.0)
{
if (m_alcDevicePauseSOFT)
m_alcDevicePauseSOFT(m_device);
return;
}
if (m_alcDeviceResumeSOFT)
m_alcDeviceResumeSOFT(m_device);
// keep audio on the correct output (OpenAL won't re-route on its own). Reopen playback on the
// current default output when the active device is lost (headphones unplugged) or the system
// default output changes (headphones plugged back in, or default switched in Windows). NULL
// device name selects the current default; context and sources are preserved.
if( m_alcReopenDeviceSOFT != nullptr && Global.AudioRenderer.empty() ) {
bool needsreopen{ false };
if( m_usedeviceevents ) {
// event-driven: the callback (any thread) flags default-output / device-removal changes
needsreopen = m_outputchanged.exchange( false );
}
if( false == needsreopen && m_candetectdisconnect ) {
// poll for a hard disconnect at ~1 Hz: the fallback without ALC_SOFT_system_events, and a safety net
// with it, as not every backend reports the removal of a device
m_devicechecktime += Deltatime;
if( m_devicechecktime >= 1.0 ) {
m_devicechecktime = 0.0;
ALCint connected{ ALC_TRUE };
::alcGetIntegerv( m_device, ALC_CONNECTED, 1, &connected );
needsreopen = ( connected == ALC_FALSE );
}
}
if( needsreopen ) {
if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes.data() ) == ALC_TRUE ) {
auto const *nowon { (char const *)::alcGetString( nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER ) };
WriteLog( "sound: audio output changed, reopened playback on \"" + std::string{ nowon ? nowon : "?" } + "\"" );
m_reopenfailed = false;
}
else if( false == m_reopenfailed ) {
// with no output left the poll retries each second; the log gets it once
ErrorLog( "sound: audio output changed but reopening on the default device failed (will retry)" );
m_reopenfailed = true;
}
}
}
// update listener
// gain
::alListenerf( AL_GAIN, Global.AudioVolume );
// orientation
glm::dmat4 cameramatrix;
Global.pCamera.SetMatrix( cameramatrix );
auto cameraposition = Global.pCamera.Pos + glm::dvec3(Global.viewport_move * glm::mat3(cameramatrix));
cameramatrix = glm::dmat4(glm::inverse(Global.viewport_rotate)) * cameramatrix;
auto rotationmatrix { glm::mat3{ cameramatrix } };
// AL_ORIENTATION expects 6 tightly-packed floats (at, then up). Do NOT reinterpret a
// glm::vec3[2] here: with GLM_FORCE_DEFAULT_ALIGNED_GENTYPES a glm::vec3 is 16 bytes
// (padded), so the array is not 6 contiguous floats and the 'up' vector gets read from
// padding as garbage, corrupting the listener basis (left/right swapped).
auto const at { glm::vec3{ 0, 0,-1 } * rotationmatrix };
auto const up { glm::vec3{ 0, 1, 0 } * rotationmatrix };
ALfloat const orientation[ 6 ] = { at.x, at.y, at.z, up.x, up.y, up.z };
::alListenerfv( AL_ORIENTATION, orientation );
// velocity
if( Deltatime > 0 ) {
auto cameramove { cameraposition - cached_camerapos };
cached_camerapos = cameraposition;
// intercept sudden user-induced camera jumps...
// ...from free fly mode change
if( m_freeflymode != FreeFlyModeFlag ) {
m_freeflymode = FreeFlyModeFlag;
cameramove = glm::dvec3{ 0.0 };
}
// ...from jump between cab and window/mirror view
if( m_windowopen != Global.CabWindowOpen ) {
m_windowopen = Global.CabWindowOpen;
cameramove = glm::dvec3{ 0.0 };
}
// ... from cab change
if( simulation::Train != nullptr && simulation::Train->iCabn != m_activecab ) {
m_activecab = simulation::Train->iCabn;
cameramove = glm::dvec3{ 0.0 };
}
// ... from camera jump to another location
if( glm::length2( cameramove ) > sq(100.0)) { // length2 is better than length for comparing because it does not require sqrt function
cameramove = glm::dvec3{ 0.0 };
}
m_listenervelocity = limit_velocity( cameramove / Deltatime );
::alListenerfv( AL_VELOCITY, reinterpret_cast<ALfloat const *>( glm::value_ptr( m_listenervelocity ) ) );
}
// update active emitters
auto source { std::begin( m_sources ) };
while( source != std::end( m_sources ) ) {
// update each source
source->update( Deltatime, m_listenervelocity );
// if after the update the source isn't playing, put it away on the spare stack, it's done
if( false == source->is_playing ) {
source->clear();
if( source->id != audio::null_resource ) {
// keep around functional sources, but no point in doing it with the above-the-limit ones
m_sourcespares.push( source->id );
}
source = m_sources.erase( source );
}
else {
// otherwise proceed through the list normally
++source;
}
}
// reset potentially used volume change flag
audio::event_volume_change = false;
if (m_alProcessUpdatesSOFT && m_alDeferUpdatesSOFT)
{
m_alProcessUpdatesSOFT();
m_alDeferUpdatesSOFT();
}
}
// returns an instance of implementation-side part of the sound emitter
audio::openal_source
openal_renderer::fetch_source() {
audio::openal_source newsource;
if( false == m_sourcespares.empty() ) {
// reuse (a copy of) already allocated source
newsource.id = m_sourcespares.top();
m_sourcespares.pop();
}
if( newsource.id == audio::null_resource ) {
// if there's no source to reuse, try to generate a new one
::alGenSources( 1, &newsource.id );
// Check for errors
ALenum err = alGetError();
if (err != AL_NO_ERROR) {
ErrorLog("sound: failed to generate source, error: " + std::to_string(err));
newsource.id = audio::null_resource;
}
}
if( newsource.id == audio::null_resource ) {
// if we still don't have a working source, see if we can sacrifice an already active one
// under presumption it's more important to play new sounds than keep the old ones going
// TBD, TODO: for better results we could use range and/or position for the new sound
// to better weight whether the new sound is really more important
auto leastimportantsource { std::end( m_sources ) };
auto leastimportantweight { std::numeric_limits<float>::max() };
for( auto source { std::begin( m_sources ) }; source != std::cend( m_sources ); ++source ) {
if( source->id == audio::null_resource
|| true == source->is_multipart
|| false == source->is_playing ) {
continue;
}
auto const sourceweight { (
source->sound_range != -1 ?
source->sound_range * source->sound_range / ( static_cast<float>( glm::length2( source->sound_distance ) ) + 1 ) :
std::numeric_limits<float>::max() ) };
if( sourceweight < leastimportantweight ) {
leastimportantsource = source;
leastimportantweight = sourceweight;
}
}
if( leastimportantsource != std::end(m_sources)
&& leastimportantweight < 1.f ) {
// only accept the candidate if it's outside of its nominal hearing range
leastimportantsource->stop();
// HACK: dt of 0 is a roundabout way to notify the controller its emitter has stopped
leastimportantsource->update( 0, m_listenervelocity );
leastimportantsource->clear();
// we should be now free to grab the id and get rid of the remains
newsource.id = leastimportantsource->id;
m_sources.erase( leastimportantsource );
}
}
if( newsource.id != audio::null_resource ) {
// for sources with functional emitter reset emitter parameters from potential last use
::alSourcef( newsource.id, AL_PITCH, 1.f );
::alSourcef( newsource.id, AL_GAIN, 1.f );
glm::vec3 zero_pos{ 0.f, 0.f, 0.f };
::alSourcefv( newsource.id, AL_POSITION, glm::value_ptr( zero_pos ) );
::alSourcefv( newsource.id, AL_VELOCITY, glm::value_ptr( zero_pos ) );
configure_source( newsource.id );
}
return newsource;
}
bool
openal_renderer::init_caps() {
if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATION_EXT" ) == AL_TRUE ) {
// enumeration supported
WriteLog( "available audio devices:" );
// device list is a sequence of null-terminated names, ending with an empty name
auto const *device { ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) };
while( device != nullptr && *device != '\0' ) {
std::string const devicename { device };
WriteLog( devicename );
device += devicename.size() + 1;
}
}
// NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device
m_device = open_output_device();
if( m_device == nullptr ) {
ErrorLog( "Failed to obtain audio device" );
return false;
}
ALCint versionmajor, versionminor;
::alcGetIntegerv( m_device, ALC_MAJOR_VERSION, 1, &versionmajor );
::alcGetIntegerv( m_device, ALC_MINOR_VERSION, 1, &versionminor );
auto const oalversion { std::to_string( versionmajor ) + "." + std::to_string( versionminor ) };
std::string al_renderer((char *)::alcGetString( m_device, ALC_DEVICE_SPECIFIER ));
crashreport_add_info("openal_renderer", al_renderer);
crashreport_add_info("openal_version", oalversion);
WriteLog(
"Audio Renderer: " + al_renderer
+ " OpenAL API spec: " + oalversion ); // ALC spec level, always 1.1; not the library version
WriteLog( "Supported extensions: " + std::string{ (char *)::alcGetString( m_device, ALC_EXTENSIONS ) } );
// the device options (output mode, HRTF and the like) are known once the device is open
m_hasoutputmode = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_mode" ) == ALC_TRUE );
m_haslimiter = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_limiter" ) == ALC_TRUE );
if( alcIsExtensionPresent( m_device, "ALC_SOFT_HRTF" ) == ALC_TRUE ) {
m_alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress( m_device, "alcGetStringiSOFT" );
m_alcResetDeviceSOFT = (LPALCRESETDEVICESOFT)alcGetProcAddress( m_device, "alcResetDeviceSOFT" );
}
m_contextattributes = device_attributes(); // cached for device reopen
m_context = ::alcCreateContext( m_device, m_contextattributes.data() );
if( m_context == nullptr ) {
ErrorLog( "Failed to create audio context" );
return false;
}
if (!alcMakeContextCurrent(m_context))
{
ErrorLog("sound: cannot select context");
return false;
}
// the version reported above is the OpenAL API spec level (always 1.1); the real implementation
// version string (e.g. "1.1 ALSOFT 1.24.2") is only queryable once a context is current
if( auto const *libversion { (char const *)::alGetString( AL_VERSION ) } ) {
crashreport_add_info( "openal_lib_version", libversion );
WriteLog( "sound: library version: " + std::string{ libversion } );
}
// Initialize all extension function pointers
if (alIsExtensionPresent("AL_SOFT_deferred_updates"))
{
m_alDeferUpdatesSOFT = (LPALDEFERUPDATESSOFT)alGetProcAddress("alDeferUpdatesSOFT");
m_alProcessUpdatesSOFT = (LPALPROCESSUPDATESSOFT)alGetProcAddress("alProcessUpdatesSOFT");
}
if (!m_alDeferUpdatesSOFT || !m_alProcessUpdatesSOFT)
WriteLog("sound: warning: extension AL_SOFT_deferred_updates not found");
if (alcIsExtensionPresent(m_device, "ALC_SOFT_pause_device"))
{
m_alcDevicePauseSOFT = (LPALCDEVICEPAUSESOFT)alcGetProcAddress(m_device, "alcDevicePauseSOFT");
m_alcDeviceResumeSOFT = (LPALCDEVICERESUMESOFT)alcGetProcAddress(m_device, "alcDeviceResumeSOFT");
}
if (!m_alcDevicePauseSOFT || !m_alcDeviceResumeSOFT)
WriteLog("sound: warning: extension ALC_SOFT_pause_device not found");
m_candetectdisconnect = ( alcIsExtensionPresent( m_device, "ALC_EXT_disconnect" ) == ALC_TRUE );
if( alcIsExtensionPresent( m_device, "ALC_SOFT_reopen_device" ) == ALC_TRUE )
m_alcReopenDeviceSOFT = (LPALCREOPENDEVICESOFT)alcGetProcAddress( m_device, "alcReopenDeviceSOFT" );
if( !m_alcReopenDeviceSOFT )
WriteLog( "sound: warning: extension ALC_SOFT_reopen_device not found; audio output device changes won't be followed" );
// prefer event-driven output following (ALC_SOFT_system_events) over polling: it reliably
// catches both device removal and default-output changes, incl. re-plugging headphones
if( m_alcReopenDeviceSOFT != nullptr
&& alcIsExtensionPresent( m_device, "ALC_SOFT_system_events" ) == ALC_TRUE ) {
m_alcEventControlSOFT = (LPALCEVENTCONTROLSOFT)alcGetProcAddress( m_device, "alcEventControlSOFT" );
m_alcEventCallbackSOFT = (LPALCEVENTCALLBACKSOFT)alcGetProcAddress( m_device, "alcEventCallbackSOFT" );
if( m_alcEventControlSOFT != nullptr && m_alcEventCallbackSOFT != nullptr ) {
m_alcEventCallbackSOFT( &openal_renderer::device_event_callback, this );
ALCenum const events[]{ ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT, ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT };
m_alcEventControlSOFT( 2, events, ALC_TRUE );
m_usedeviceevents = true;
WriteLog( "sound: following audio output device changes via ALC_SOFT_system_events" );
}
}
init_extensions();
return true;
}
// resolves the entry points of the context extensions the settings use: source resampler, EFX filters
void
openal_renderer::init_extensions() {
if( alIsExtensionPresent( "AL_SOFT_source_resampler" ) == AL_TRUE ) {
m_alGetStringiSOFT = (LPALGETSTRINGISOFT)alGetProcAddress( "alGetStringiSOFT" );
}
if( alcIsExtensionPresent( m_device, "ALC_EXT_EFX" ) == ALC_TRUE ) {
m_alGenFilters = (LPALGENFILTERS)alGetProcAddress( "alGenFilters" );
m_alDeleteFilters = (LPALDELETEFILTERS)alGetProcAddress( "alDeleteFilters" );
m_alFilteri = (LPALFILTERI)alGetProcAddress( "alFilteri" );
m_alFilterf = (LPALFILTERF)alGetProcAddress( "alFilterf" );
m_hasefx = ( m_alGenFilters != nullptr && m_alDeleteFilters != nullptr && m_alFilteri != nullptr && m_alFilterf != nullptr );
}
if( false == m_hasefx ) {
return;
}
::alGetError();
m_alGenFilters( 1, &m_lowpassfilter );
m_alFilteri( m_lowpassfilter, AL_FILTER_TYPE, AL_FILTER_LOWPASS );
if( ::alGetError() != AL_NO_ERROR ) {
WriteLog( "sound: warning: EFX low-pass filter not available" );
m_lowpassfilter = 0;
}
}
// returns: attributes of the device and the context made from the settings. with the defaults they are as before the
// settings existed, which leaves output mode, HRTF, limiter and mixing rate to the library
std::vector<ALCint>
openal_renderer::device_attributes() const {
// sound.maxsources, kept for an OpenAL other than OpenAL Soft: that one gives at least 256 sources whatever is asked
std::vector<ALCint> attributes { ALC_MONO_SOURCES, Global.audio_max_sources };
auto const add { [ &attributes ]( ALCint const Key, ALCint const Value ) {
attributes.push_back( Key );
attributes.push_back( Value ); } };
if( auto const mode { output_mode_value( Global.AudioOutputMode ) }; mode && m_hasoutputmode ) {
add( ALC_OUTPUT_MODE_SOFT, *mode );
}
if( m_alcGetStringiSOFT != nullptr ) {
if( auto const hrtf { switch_value( Global.AudioHrtf ) } ) {
add( ALC_HRTF_SOFT, *hrtf );
}
if( auto const index { hrtf_index( Global.AudioHrtfProfile ) }; index >= 0 ) {
add( ALC_HRTF_ID_SOFT, index );
}
}
if( auto const limiter { switch_value( Global.AudioLimiter ) }; limiter && m_haslimiter ) {
add( ALC_OUTPUT_LIMITER_SOFT, *limiter );
}
if( Global.AudioFrequency > 0 ) {
add( ALC_FREQUENCY, Global.AudioFrequency );
}
attributes.push_back( 0 );
return attributes;
}
// returns: index of the named HRTF data set, or -1 if the name is empty or unknown
int
openal_renderer::hrtf_index( std::string const &Name ) const {
if( Name.empty() ) { return -1; }
auto const profiles { hrtf_profiles() };
if( auto const lookup { std::ranges::find( profiles, Name ) }; lookup != std::end( profiles ) ) {
return static_cast<int>( std::distance( std::begin( profiles ), lookup ) );
}
WriteLog( std::format( "sound: unknown HRTF data set \"{}\", left to the library", Name ) );
return -1;
}
// returns: index of the resampler of the settings, the library's default with none set, or -1 without the extension
ALint
openal_renderer::resampler_index() const {
if( m_alGetStringiSOFT == nullptr ) { return -1; }
if( false == Global.AudioResampler.empty() ) {
auto const names { resamplers() };
if( auto const lookup { std::ranges::find( names, Global.AudioResampler ) }; lookup != std::end( names ) ) {
return static_cast<ALint>( std::distance( std::begin( names ), lookup ) );
}
WriteLog( std::format( "sound: unknown resampler \"{}\", the library's default used", Global.AudioResampler ) );
}
return ::alGetInteger( AL_DEFAULT_RESAMPLER_SOFT );
}
// sets the options of the settings on a source
void
openal_renderer::configure_source( ALuint const Source ) const {
if( m_resampler >= 0 ) {
::alSourcei( Source, AL_SOURCE_RESAMPLER_SOFT, m_resampler );
}
if( m_hasefx ) {
::alSourcef( Source, AL_AIR_ABSORPTION_FACTOR, Global.AudioAirAbsorption );
}
}
// sets the EFX low-pass filter of a source for given soundproofing: the stronger the soundproofing, the more muffled
void
openal_renderer::soundproofing_filter( ALuint const Source, float const Soundproofing ) const {
if( m_lowpassfilter == 0 ) { return; }
// a soundproofing left undefined by the data (-1, which OpenAL doesn't take as the gain either) isn't muffled
if( false == Global.AudioLowpass || Soundproofing < 0.f || Soundproofing >= 1.f ) {
::alSourcei( Source, AL_DIRECT_FILTER, AL_FILTER_NULL );
return;
}
// the level is set by the gain already, the filter takes away only the high frequencies
m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAIN, 1.f );
m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAINHF, std::clamp( Soundproofing, 0.f, 1.f ) );
::alSourcei( Source, AL_DIRECT_FILTER, static_cast<ALint>( m_lowpassfilter ) );
}
// returns: names of the output devices
std::vector<std::string>
openal_renderer::output_devices() const {
if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ) {
return split_name_list( ::alcGetString( nullptr, ALC_ALL_DEVICES_SPECIFIER ) );
}
return split_name_list( ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) );
}
// returns: names of the HRTF data sets of the device
std::vector<std::string>
openal_renderer::hrtf_profiles() const {
std::vector<std::string> names;
if( m_device == nullptr || m_alcGetStringiSOFT == nullptr ) { return names; }
ALCint count { 0 };
::alcGetIntegerv( m_device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &count );
for( ALCint index = 0; index < count; ++index ) {
auto const *name { m_alcGetStringiSOFT( m_device, ALC_HRTF_SPECIFIER_SOFT, index ) };
names.emplace_back( name != nullptr ? name : "" );
}
return names;
}
// returns: names of the resamplers
std::vector<std::string>
openal_renderer::resamplers() const {
std::vector<std::string> names;
if( m_alGetStringiSOFT == nullptr ) { return names; }
auto const count { ::alGetInteger( AL_NUM_RESAMPLERS_SOFT ) };
for( ALint index = 0; index < count; ++index ) {
auto const *name { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, index ) };
names.emplace_back( name != nullptr ? name : "" );
}
return names;
}
// returns: what the device ended up with
std::string
openal_renderer::device_status() const {
if( m_device == nullptr ) { return "no audio device"; }
auto const namequery { ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ? ALC_ALL_DEVICES_SPECIFIER : ALC_DEVICE_SPECIFIER };
auto const *devicename { ::alcGetString( m_device, namequery ) };
ALCint frequency { 0 };
::alcGetIntegerv( m_device, ALC_FREQUENCY, 1, &frequency );
auto status { std::format( "device \"{}\", {} Hz", devicename != nullptr ? devicename : "?", frequency ) };
if( m_hasoutputmode ) {
ALCint mode { 0 };
::alcGetIntegerv( m_device, ALC_OUTPUT_MODE_SOFT, 1, &mode );
status += std::format( ", output {}", output_mode_name( mode ) );
}
if( m_alcGetStringiSOFT != nullptr ) {
ALCint hrtf { ALC_FALSE };
::alcGetIntegerv( m_device, ALC_HRTF_SOFT, 1, &hrtf );
if( hrtf == ALC_TRUE ) {
auto const *hrtfname { ::alcGetString( m_device, ALC_HRTF_SPECIFIER_SOFT ) };
status += std::format( ", HRTF \"{}\"", hrtfname != nullptr ? hrtfname : "?" );
}
else {
status += ", HRTF off";
}
}
if( m_resampler >= 0 ) {
auto const *resamplername { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, m_resampler ) };
status += std::format( ", resampler {}", resamplername != nullptr ? resamplername : "?" );
}
if( m_lowpassfilter != 0 ) {
status += ", EFX";
}
return status;
}
// applies changed device options without a restart: reopens the device, or resets it with an older library
bool
openal_renderer::apply_device_settings() {
if( false == m_ready ) { return false; }
m_contextattributes = device_attributes();
auto applied { false };
if( m_alcReopenDeviceSOFT != nullptr ) {
auto const *devicename { Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() };
applied = ( m_alcReopenDeviceSOFT( m_device, devicename, m_contextattributes.data() ) == ALC_TRUE );
}
else if( m_alcResetDeviceSOFT != nullptr ) {
// without ALC_SOFT_reopen_device another output device takes a restart
applied = ( m_alcResetDeviceSOFT( m_device, m_contextattributes.data() ) == ALC_TRUE );
if( applied ) {
WriteLog( "sound: this audio library can't switch the output device while running, a changed device takes a restart" );
}
}
if( applied ) {
WriteLog( "sound: audio settings applied, " + device_status() );
}
else {
ErrorLog( "sound: the audio device settings take a restart to apply" );
}
return applied;
}
// applies changed source options to every source; spare sources get them when taken
void
openal_renderer::apply_source_settings() {
if( false == m_ready ) { return; }
::alDopplerFactor( Global.AudioDoppler );
m_resampler = resampler_index();
for( auto const &source : m_sources ) {
if( source.id != audio::null_resource ) {
configure_source( source.id );
}
}
// the filters follow with the gain, which this flag makes every source set anew
audio::event_volume_change = true;
}
} // audio