diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 16b24072b..2323c6b82 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -75,11 +75,21 @@ std::optional switch_value( std::string_view const Name ) { return std::nullopt; } +// returns: name of an output device without the prefix OpenAL Soft may put before the names of the devices it lists on +// Windows. it opens a device named either way, so the name in eu07.ini can come with it or without +std::string_view bare_output_name( std::string_view const Name ) { + + constexpr std::string_view prefix { "OpenAL Soft on " }; + return Name.starts_with( prefix ) ? Name.substr( prefix.size() ) : Name; +} + // 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() { +// say, leaves the default one rather than no sound at all: Fallback is set then, and the name stays as it is, for +// follow_output() to go back to that device once it's there again. the name is set to what got opened, for a later reopen +ALCdevice *open_output_device( bool &Fallback ) { + Fallback = false; if( Global.AudioRenderer.empty() ) { return ::alcOpenDevice( nullptr ); } @@ -92,8 +102,8 @@ ALCdevice *open_output_device() { return device; } } - ErrorLog( std::format( "sound: audio device \"{}\" not found, the default one used", Global.AudioRenderer ) ); - Global.AudioRenderer.clear(); + ErrorLog( std::format( "sound: audio device \"{}\" set in eu07.ini isn't available, using the default one", Global.AudioRenderer ) ); + Fallback = true; return ::alcOpenDevice( nullptr ); } @@ -108,6 +118,25 @@ std::vector split_name_list( ALCchar const *List ) { return names; } +// returns: the file the OpenAL library the game plays through was loaded from, in UTF-8, or nothing where that can't +// be told. the game takes OpenAL32.dll from its own folder before the one of the system, so this shows which one it got +std::optional openal_library_path() { +#ifdef _WIN32 + auto *module { ::GetModuleHandleW( L"OpenAL32.dll" ) }; + if( module == nullptr ) { return std::nullopt; } + std::wstring path( 4096, wchar_t{} ); + auto const length { static_cast( ::GetModuleFileNameW( module, path.data(), static_cast( path.size() ) ) ) }; + if( ( length <= 0 ) || ( length >= static_cast( path.size() ) ) ) { return std::nullopt; } + auto const size { ::WideCharToMultiByte( CP_UTF8, 0, path.data(), length, nullptr, 0, nullptr, nullptr ) }; + if( size <= 0 ) { return std::nullopt; } + std::string result( static_cast( size ), char{} ); + ::WideCharToMultiByte( CP_UTF8, 0, path.data(), length, result.data(), size, nullptr, nullptr ); + return result; +#else + return std::nullopt; +#endif +} + } // namespace float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin @@ -371,16 +400,151 @@ openal_renderer::~openal_renderer() { 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() +// invoked by OpenAL (possibly on an internal thread) on device events; only notes what happened, +// the device is checked and opened again on the main thread, in follow_output() 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( userparam )->m_outputchanged.store( true ); + auto event { 0u }; + switch( eventtype ) { + case ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT: { event = output_follower::default_changed; break; } + case ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT: { event = output_follower::device_removed; break; } + case ALC_EVENT_TYPE_DEVICE_ADDED_SOFT: { event = output_follower::device_added; break; } + default: { return; } + } + static_cast( userparam )->m_outputevents.fetch_or( event ); +} + +// true unless the device is known to have lost its output +bool +openal_renderer::output_connected() const { + + if( false == m_candetectdisconnect ) { return true; } + ALCint connected { ALC_TRUE }; + ::alcGetIntegerv( m_device, ALC_CONNECTED, 1, &connected ); + return connected != ALC_FALSE; +} + +// name of the output the device plays on +std::string +openal_renderer::output_name() const { + + auto const *name { ::alcGetString( m_device, ALC_DEVICE_SPECIFIER ) }; + return name != nullptr ? name : "?"; +} + +// moves the playback to the specified output, null being the default one of the system. the context, the buffers +// and the sources stay as they are. returns true when the device plays on that output afterwards +bool +openal_renderer::reopen_output_on( ALCchar const *Devicename ) { + + auto const reopened { m_alcReopenDeviceSOFT( m_device, Devicename, m_contextattributes.data() ) == ALC_TRUE }; + ::alcGetError( m_device ); // a failure is handled here, don't leave its error code behind + // NOTE: the library reports success also when the new output was opened but failed to start, + // leaving the device disconnected. the result alone can't be trusted + return reopened && output_connected(); +} + +// returns: the name under which the library lists the device set in eu07.ini, or nothing if it isn't listed. the name +// is matched as written and read as code page 1250 text (the starter writes eu07.ini in it), with or without the prefix +// of the library. every attempt to open a device stops the playback for a moment, even one that fails, so a device that +// isn't there isn't tried +std::optional +openal_renderer::find_preferred_output() const { + + if( Global.AudioRenderer.empty() ) { return std::nullopt; } + auto const devices { output_devices() }; + auto const listed = [&devices]( std::string_view const Name ) -> std::optional { + auto const match { std::ranges::find_if( devices, [Name]( std::string_view const Device ) { + return bare_output_name( Device ) == bare_output_name( Name ); } ) }; + if( match == std::end( devices ) ) { return std::nullopt; } + return *match; + }; + if( auto name { listed( Global.AudioRenderer ) } ) { return name; } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + return listed( utf8name ); + } + return std::nullopt; +} + +// opens the output anew: the device set in eu07.ini if there is one and it works, the default one of the system otherwise +void +openal_renderer::reopen_output( output_follower::clock::time_point const Now ) { + + auto const pinned { false == Global.AudioRenderer.empty() }; + if( pinned ) { + auto name { find_preferred_output() }; + if( false == name.has_value() && false == output_connected() ) { + // not listed under a name that matches, but there is no sound to break anyway: the library may know it still + name = Global.AudioRenderer; + } + if( name.has_value() && reopen_output_on( name->c_str() ) ) { + Global.AudioRenderer = *name; + m_output.succeeded( false, Now ); + WriteLog( std::format( "sound: audio output changed, reopened playback on \"{}\"", output_name() ) ); + return; + } + } + reopen_default_output( pinned, Now ); +} + +// opens the default output of the system. Pinned: it stands in for the device set in eu07.ini +void +openal_renderer::reopen_default_output( bool const Pinned, output_follower::clock::time_point const Now ) { + + if( reopen_output_on( nullptr ) ) { + m_output.succeeded( Pinned, Now ); + WriteLog( std::format( "sound: audio output changed, reopened playback on \"{}\"{}", output_name(), + Pinned ? " (the default output; the device set in eu07.ini isn't available)" : "" ) ); + return; + } + if( m_output.failed( Now ) ) { + // logged once, the following attempts are silent until one works + ErrorLog( "sound: audio output lost and no output could be opened, retrying until one works" ); + } +} + +// while the default output plays in place of the device set in eu07.ini: moves back to that device if it is listed again +void +openal_renderer::restore_preferred_output( output_follower::clock::time_point const Now ) { + + auto const name { find_preferred_output() }; + if( false == name.has_value() ) { + // some other device came, or the one set isn't listed yet: nothing tried, the playback goes on undisturbed + m_output.restore_failed( Now ); + return; + } + if( reopen_output_on( name->c_str() ) ) { + Global.AudioRenderer = *name; + m_output.succeeded( false, Now ); + WriteLog( std::format( "sound: the audio device set in eu07.ini is available again, reopened playback on \"{}\"", output_name() ) ); + return; + } + WriteLog( std::format( "sound: warning: the audio device \"{}\" set in eu07.ini is listed again but doesn't play, staying on the default output", *name ) ); + if( false == output_connected() ) { + // the device opened but didn't start. the library had let go of the default output before it tried, so that's gone too + reopen_default_output( true, Now ); + } + m_output.restore_failed( Now ); +} + +// keeps the sound on an output that works. OpenAL neither moves to another output on its own nor recovers one it lost: +// a device whose output is gone stops all its sources and stays silent, even after the very same output comes back, +// until it is opened again +void +openal_renderer::follow_output() { + + if( m_alcReopenDeviceSOFT == nullptr ) { return; } + + auto const now { output_follower::clock::now() }; + auto const events { m_outputevents.exchange( 0u ) }; + switch( m_output.update( events, now, [this]() { return output_connected(); } ) ) { + case output_follower::action::reopen: { reopen_output( now ); break; } + case output_follower::action::restore_preferred: { restore_preferred_output( now ); break; } + default: { break; } + } } audio::buffer_handle @@ -483,40 +647,8 @@ openal_renderer::update( double const Deltatime ) { 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; - } - } - } + // keep the sound on an output that works + follow_output(); // update listener // gain @@ -686,7 +818,9 @@ openal_renderer::init_caps() { } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = open_output_device(); + auto const pinned { false == Global.AudioRenderer.empty() }; + auto fallback { false }; + m_device = open_output_device( fallback ); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; @@ -730,9 +864,11 @@ openal_renderer::init_caps() { // 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 + std::string libraryversion; if( auto const *libversion { (char const *)::alGetString( AL_VERSION ) } ) { crashreport_add_info( "openal_lib_version", libversion ); WriteLog( "sound: library version: " + std::string{ libversion } ); + libraryversion = libversion; } // Initialize all extension function pointers @@ -758,26 +894,53 @@ openal_renderer::init_caps() { 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 + // have the system report the changes of the outputs (ALC_SOFT_system_events) where it can. this goes next to + // the periodic check of the connection done by follow_output(), as not every loss of the output is reported 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 ); + std::array const events { ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT, ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT, ALC_EVENT_TYPE_DEVICE_ADDED_SOFT }; + m_alcEventControlSOFT( static_cast( events.size() ), events.data(), ALC_TRUE ); m_usedeviceevents = true; WriteLog( "sound: following audio output device changes via ALC_SOFT_system_events" ); } } + if( m_alcReopenDeviceSOFT != nullptr && false == m_usedeviceevents ) { + WriteLog( "sound: warning: extension ALC_SOFT_system_events not found; a lost audio output is recovered, a change of the default one and the return of the device set in eu07.ini aren't followed" ); + } + m_output.start( pinned, fallback, output_follower::clock::now() ); + log_output_following( libraryversion, pinned ); init_extensions(); return true; } +// says in one line which OpenAL library the game got and whether the sound follows the output device with it. an old +// library (OpenAL Soft before 1.23, as the one the game came with) is left as it is: the sound plays on the device opened +// at the start, as it always did, and only the log says why it doesn't move +void +openal_renderer::log_output_following( std::string_view const Version, bool const Pinned ) const { + + auto const library { openal_library_path() }; + auto const name { std::format( "\"{}\"{}", Version.empty() ? std::string_view{ "unknown" } : Version, + library.has_value() ? std::format( " from \"{}\"", *library ) : std::string{} ) }; + if( ( m_alcReopenDeviceSOFT == nullptr ) || ( false == m_usedeviceevents ) ) { + WriteLog( std::format( "sound: warning: the OpenAL library {} is too old to follow a change of the audio output; " + "the sound stays on the device opened at the start. OpenAL Soft 1.23 or newer, as OpenAL32.dll in the game folder, follows it", name ) ); + return; + } + if( Pinned ) { + WriteLog( std::format( "sound: the OpenAL library {} follows the audio output: the device set in eu07.ini (sound.openal.renderer), " + "the default output of the system while that one isn't there", name ) ); + return; + } + WriteLog( std::format( "sound: the OpenAL library {} follows the audio output: the default output of the system", name ) ); +} + // resolves the entry points of the context extensions the settings use: source resampler, EFX filters void openal_renderer::init_extensions() { @@ -978,8 +1141,22 @@ openal_renderer::apply_device_settings() { 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 ); + auto const pinned { false == Global.AudioRenderer.empty() }; + if( pinned ) { + // the playback is opened anew here anyway, so a name the list doesn't match is tried too + auto const name { find_preferred_output().value_or( Global.AudioRenderer ) }; + applied = reopen_output_on( name.c_str() ); + if( applied ) { Global.AudioRenderer = name; } + } + auto const fallback { pinned && false == applied }; + if( false == applied ) { + // no device set, or the one set isn't there: the default one, which follow_output() leaves once the other is back + applied = reopen_output_on( nullptr ); + } + if( applied ) { + // the device may have been changed in the settings: the output is followed by what is set now + m_output.start( pinned, fallback, output_follower::clock::now() ); + } } else if( m_alcResetDeviceSOFT != nullptr ) { // without ALC_SOFT_reopen_device another output device takes a restart diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index f6e247104..afa73ee93 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "audio/audio.h" +#include "audio/outputfollow.h" #include "audio/fmradio.h" #include "audio/startsample.h" #include "model/ResourceManager.h" @@ -20,6 +21,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include // Definicje dla OpenAL 1.25 jeśli brakuje #ifndef ALC_CONNECTED @@ -151,10 +154,20 @@ private: bool init_caps(); void init_extensions(); + void log_output_following( std::string_view Version, bool Pinned ) const; std::vector device_attributes() const; int hrtf_index( std::string const &Name ) const; ALint resampler_index() const; void configure_source( ALuint const Source ) const; + // keeps the sound on an output that works, see audio::output_follower + void follow_output(); + void reopen_output( output_follower::clock::time_point const Now ); + void restore_preferred_output( output_follower::clock::time_point const Now ); + void reopen_default_output( bool const Pinned, output_follower::clock::time_point const Now ); + std::optional find_preferred_output() const; + bool reopen_output_on( ALCchar const *Devicename ); + bool output_connected() const; + std::string output_name() const; audio::openal_source fetch_source(); ALCdevice *m_device { nullptr }; @@ -192,16 +205,15 @@ private: bool m_candetectdisconnect { false }; std::vector m_contextattributes; // cached for device reopen - double m_devicechecktime { 0.0 }; - bool m_reopenfailed { false }; // a failed reopen is retried each second, but logged once + output_follower m_output; // decides when the device is opened again - // ALC_SOFT_system_events: event-driven following of output-device / default-output changes. - // Preferred over polling because it reliably catches both device removal and default changes - // (e.g. re-plugging headphones), which alcGetString(DEFAULT_ALL_DEVICES) does not report live. + // ALC_SOFT_system_events: the system reports output devices coming, going and the default one changing. + // Used next to the periodic check of the connection, not in place of it: the events catch a change of the + // default output at once (e.g. re-plugging headphones), the check catches the losses the system doesn't report. LPALCEVENTCONTROLSOFT m_alcEventControlSOFT { nullptr }; LPALCEVENTCALLBACKSOFT m_alcEventCallbackSOFT { nullptr }; bool m_usedeviceevents { false }; - std::atomic m_outputchanged { false }; // set from the (possibly off-thread) event callback + std::atomic m_outputevents { 0u }; // bits of output_follower::event, set from the (possibly off-thread) event callback static void ALC_APIENTRY device_event_callback( ALCenum eventtype, ALCenum devicetype, ALCdevice *device, ALCsizei length, ALCchar const *message, void *userparam ) noexcept; }; diff --git a/audio/outputfollow.h b/audio/outputfollow.h new file mode 100644 index 000000000..46d36dff7 --- /dev/null +++ b/audio/outputfollow.h @@ -0,0 +1,154 @@ +/* +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/. +*/ + +#pragma once + +#include +#include + +namespace audio { + +// decides when the playback device has to be opened again, so the sound follows the output of the system: +// headphones pulled out or plugged in, another default output chosen, the device taken away and given back. +// holds no OpenAL state of its own: the renderer feeds it the events of the system and the state of the device, +// and does what it answers. kept apart from the renderer so the unit tests can run it +class output_follower { + +public: + using clock = std::chrono::steady_clock; + + // what the system reported since the last update, combined as bits + enum event : unsigned { + default_changed = 1u << 0, // another output became the default one + device_removed = 1u << 1, // an output is gone, possibly the one in use + device_added = 1u << 2 // an output appeared, possibly the one set in eu07.ini + }; + + enum class action { + none, + reopen, // open the output anew: the one set in eu07.ini if there is one and it works, the default one otherwise + restore_preferred // playing on the default output in place of the one set in eu07.ini: see whether that one is back + }; + + // how often a working device is asked whether it is still connected. the system doesn't report every loss of the + // output (a stream invalidated without the device being removed), so the events alone leave the game silent + static constexpr std::chrono::milliseconds check_interval { 1000 }; + // delays between the attempts to open an output while there is none that works. every attempt runs on the main + // thread and may take tens of milliseconds, so after the first minute without an output they thin out + static constexpr std::chrono::milliseconds retry_min { 500 }; + static constexpr std::chrono::milliseconds retry_max { 4000 }; + static constexpr std::chrono::milliseconds retry_late_after { 60000 }; + static constexpr std::chrono::milliseconds retry_late { 30000 }; + // while there is no output an event of the system has the next attempt made at once, but not sooner than this after + // the last one: a device coming (a bluetooth headset, say) reports a burst of events over a few frames + static constexpr std::chrono::milliseconds event_retry_min { 250 }; + // the device set in eu07.ini can be reported before it is ready to play. a move back to it that didn't work out is + // tried again after 1, 2 and 4 s; then the next arrival of a device is waited for, so a device that never works + // (taken in exclusive mode by another program, say) doesn't break the sound every few seconds + static constexpr std::chrono::milliseconds restore_retry_min { 1000 }; + static constexpr int restore_retries { 3 }; + + // Pinned: a device is set in eu07.ini (sound.openal.renderer); Fallback: it couldn't be opened and the default one plays instead + void + start( bool const Pinned, bool const Fallback, clock::time_point const Now ) { + m_pinned = Pinned; + m_fallback = Pinned && Fallback; + m_lost = false; + m_retrydelay = retry_min; + m_nextcheck = Now + check_interval; + m_restorefailures = 0; + } + + // Events: bits of event; Connected: callable telling whether the device still works, called only when a check is due + template + action + update( unsigned const Events, clock::time_point const Now, Probe_ const &Connected ) { + if( m_lost ) { + // no working output: whatever the system reports may be the output coming back, so it brings the next attempt + // forward. otherwise it comes after a growing delay + if( Events != 0u ) { m_nextcheck = std::min( m_nextcheck, m_lastattempt + event_retry_min ); } + return ( Now >= m_nextcheck ) ? action::reopen : action::none; + } + if( ( Now >= m_nextcheck ) || ( ( Events & device_removed ) != 0u ) ) { + m_nextcheck = Now + check_interval; + if( false == Connected() ) { return action::reopen; } + } + if( follows_default() && ( ( Events & default_changed ) != 0u ) ) { return action::reopen; } + if( m_fallback ) { + if( ( Events & device_added ) != 0u ) { + // a device that appears may be the one set: a fresh round of attempts + m_restorefailures = 0; + return action::restore_preferred; + } + if( ( m_restorefailures > 0 ) && ( m_restorefailures <= restore_retries ) && ( Now >= m_nextrestore ) ) { + return action::restore_preferred; + } + } + return action::none; + } + + // an output was opened and works. Fallback: it is the default one, in place of the one set in eu07.ini + void + succeeded( bool const Fallback, clock::time_point const Now ) { + m_fallback = m_pinned && Fallback; + m_lost = false; + m_retrydelay = retry_min; + m_nextcheck = Now + check_interval; + // the default output standing in again doesn't end the round of attempts to move back to the device set + if( false == m_fallback ) { m_restorefailures = 0; } + } + + // no output could be opened. returns true for the first failure in a row, the one worth a line in the log + bool + failed( clock::time_point const Now ) { + auto const first { false == m_lost }; + if( first ) { + m_loststart = Now; + m_retrydelay = retry_min; + } + else if( Now - m_loststart >= retry_late_after ) { + m_retrydelay = retry_late; + } + else { + m_retrydelay = std::min( m_retrydelay * 2, retry_max ); + } + m_lost = true; + m_lastattempt = Now; + m_nextcheck = Now + m_retrydelay; + return first; + } + + // the move back to the device set in eu07.ini didn't work out: the device isn't listed, or it didn't open or start. + // schedules the next attempt of the round, if there is one left + void + restore_failed( clock::time_point const Now ) { + ++m_restorefailures; + if( m_restorefailures <= restore_retries ) { + m_nextrestore = Now + restore_retry_min * ( 1 << ( m_restorefailures - 1 ) ); + } + } + + bool lost() const { return m_lost; } + bool fallback() const { return m_fallback; } + // a device set in eu07.ini is left alone for as long as it works; otherwise the sound goes where the system sends it + bool follows_default() const { return false == m_pinned || m_fallback; } + +private: + bool m_pinned { false }; + bool m_fallback { false }; + bool m_lost { false }; // the output is gone and none could be opened so far + std::chrono::milliseconds m_retrydelay { retry_min }; + clock::time_point m_nextcheck {}; // of the connection while the output works, the next attempt to open one while it doesn't + clock::time_point m_loststart {}; // the first failed attempt of the current loss + clock::time_point m_lastattempt {}; // the last failed attempt, while the output is lost + int m_restorefailures { 0 }; // failed moves back to the device set since it last appeared, 0 when none is due + clock::time_point m_nextrestore {}; +}; + +} // namespace audio diff --git a/tests/unit/test_audio_output.cpp b/tests/unit/test_audio_output.cpp new file mode 100644 index 000000000..a2319b960 --- /dev/null +++ b/tests/unit/test_audio_output.cpp @@ -0,0 +1,259 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "audio/outputfollow.h" + +// the following of the audio output: when the renderer is told to open its playback device again + +namespace +{ + +using audio::output_follower; +using action = audio::output_follower::action; +using std::chrono::milliseconds; + +// a follower with a device that answers the checks of its connection as told, and counts them +struct output_rig +{ + output_follower follower; + output_follower::clock::time_point now{}; + bool connected{true}; + int checks{0}; + + explicit output_rig(bool const Pinned = false, bool const Fallback = false) + { + follower.start(Pinned, Fallback, now); + } + action step(milliseconds const Elapsed, unsigned const Events = 0u) + { + now += Elapsed; + return follower.update(Events, now, [this]() { + ++checks; + return connected; + }); + } +}; + +} // namespace + +TEST_CASE("audio output: a working device is left alone and checked about once a second") +{ + output_rig rig; + for (int frame = 0; frame < 300; ++frame) // 3 s at 100 fps + CHECK(rig.step(milliseconds{10}) == action::none); + CHECK(rig.checks == 3); +} + +TEST_CASE("audio output: a lost connection is found without any event from the system") +{ + // the stream invalidated, the device not removed and the default output unchanged: nothing is reported + output_rig rig; + rig.connected = false; + CHECK(rig.step(milliseconds{500}) == action::none); // not yet checked + CHECK(rig.step(milliseconds{500}) == action::reopen); + CHECK(rig.checks == 1); +} + +TEST_CASE("audio output: a removed device has the connection checked at once") +{ + output_rig rig; + CHECK(rig.step(milliseconds{10}, output_follower::device_removed) == action::none); // another device was removed + CHECK(rig.checks == 1); + rig.connected = false; + CHECK(rig.step(milliseconds{10}, output_follower::device_removed) == action::reopen); +} + +TEST_CASE("audio output: a change of the default output is followed, the arrival of some device is not") +{ + output_rig rig; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::reopen); + CHECK(rig.checks == 0); +} + +TEST_CASE("audio output: opening that failed is tried again, with growing delays and at once on any event") +{ + output_rig rig; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); // the first failure in a row is the one to log + CHECK(rig.follower.lost()); + + // the following attempts come after 0.5, 1, 2, 4 and then every 4 s + for (auto const delay : {500, 1000, 2000, 4000, 4000}) + { + CHECK(rig.step(milliseconds{delay - 1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + CHECK_FALSE(rig.follower.failed(rig.now)); + } + // whatever the system reports may be the output coming back: the next attempt at once, but not sooner than + // event_retry_min after the last one, as a device coming reports a burst of events + CHECK(rig.step(milliseconds{1}, output_follower::device_added) == action::none); + CHECK(rig.step(output_follower::event_retry_min - milliseconds{2}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); // the event brought the attempt forward and wasn't forgotten + CHECK_FALSE(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::event_retry_min, output_follower::default_changed) == action::reopen); + + // a lost device isn't asked about its connection, it is opened again + CHECK(rig.checks == 1); + + rig.connected = true; + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.lost()); + CHECK(rig.step(milliseconds{10}) == action::none); + // and the next loss starts from the short delay, with its own line in the log + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::retry_min) == action::reopen); +} + +TEST_CASE("audio output: a device set in eu07.ini doesn't follow the default output while it works") +{ + output_rig rig{true}; + CHECK_FALSE(rig.follower.follows_default()); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::none); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); + // but it is opened again when it loses the connection + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); +} + +TEST_CASE("audio output: the default output standing in for the device set in eu07.ini") +{ + output_rig rig{true}; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + // the device set is gone, the default one was opened instead + rig.connected = true; + rig.follower.succeeded(true, rig.now); + CHECK(rig.follower.fallback()); + CHECK(rig.follower.follows_default()); + + // the default output is followed for as long as it stands in + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::reopen); + rig.follower.succeeded(true, rig.now); + // and a device that appears may be the one set + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + CHECK(rig.follower.fallback()); // it wasn't, nothing changes + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::none); +} + +TEST_CASE("audio output: the game started on the default output, the device set in eu07.ini being absent") +{ + output_rig rig{true, true}; + CHECK(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); +} + +TEST_CASE("audio output: without a device set in eu07.ini there is nothing to fall back from") +{ + output_rig rig{false, true}; + CHECK_FALSE(rig.follower.fallback()); + rig.follower.succeeded(true, rig.now); + CHECK_FALSE(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); +} + +TEST_CASE("audio output: after a minute without an output the attempts thin out, the events still count at once") +{ + output_rig rig; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + auto const loststart{rig.now}; + + // 0.5, 1, 2, then 4 s until a minute has gone by since the first failure + while (rig.now - loststart < output_follower::retry_late_after) + { + auto const before{rig.now}; + auto next{rig.step(milliseconds{50})}; + while (next != action::reopen) + next = rig.step(milliseconds{50}); + CHECK(rig.now - before <= output_follower::retry_max); + rig.follower.failed(rig.now); + } + // the failure past the minute puts the next attempt 30 s away + CHECK(rig.step(output_follower::retry_late - milliseconds{1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + rig.follower.failed(rig.now); + CHECK(rig.step(output_follower::retry_late - milliseconds{1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + rig.follower.failed(rig.now); + + // a device coming has the attempt made at once still + CHECK(rig.step(output_follower::event_retry_min, output_follower::device_added) == action::reopen); + rig.follower.failed(rig.now); + + // and the next loss starts from the short delays again + rig.follower.succeeded(false, rig.now); + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::retry_min) == action::reopen); +} + +TEST_CASE("audio output: a move back to the device set in eu07.ini that didn't work out is tried again 3 times") +{ + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); // reported before it was ready, say + + // again after 1, 2 and 4 s + for (auto const delay : {1000, 2000, 4000}) + { + CHECK(rig.step(milliseconds{delay - 1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + } + // then not any more: a device that never works doesn't break the sound every few seconds + for (int second = 0; second < 60; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); + + // until a device appears again, which starts a fresh round + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + CHECK(rig.step(output_follower::restore_retry_min) == action::restore_preferred); + + // the device works this time: nothing more to try + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.fallback()); + for (int second = 0; second < 10; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} + +TEST_CASE("audio output: the default output opened anew after a failed move back keeps the round of attempts") +{ + // the device set opened but didn't start, and the library had let go of the default output before: that's opened + // again, and the move back is still retried, with no endless round + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + for (int attempt = 0; attempt < output_follower::restore_retries; ++attempt) + { + rig.follower.succeeded(true, rig.now); + rig.follower.restore_failed(rig.now); + CHECK(rig.follower.fallback()); + action next{action::none}; + for (int frame = 0; frame < 1000 && next == action::none; ++frame) + next = rig.step(milliseconds{10}); + CHECK(next == action::restore_preferred); + } + rig.follower.succeeded(true, rig.now); + rig.follower.restore_failed(rig.now); + for (int second = 0; second < 60; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} + +TEST_CASE("audio output: the settings applied drop a pending move back") +{ + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + // the settings applied: the device set may be another one now, a pending attempt is dropped + rig.follower.start(true, true, rig.now); + for (int second = 0; second < 10; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +}