27#include <SDL3_mixer/SDL_mixer.h>
33#include <unordered_map>
37#define DBG_AUDIO LOG_STREAM(debug, log_audio)
38#define LOG_AUDIO LOG_STREAM(info, log_audio)
39#define ERR_AUDIO LOG_STREAM(err, log_audio)
43template<
typename Container,
typename Value>
46 auto iter = map.find(
value);
47 if(iter == map.end()) {
48 return utils::nullopt;
65 void allocate_channel(MIX_Mixer* mixer,
const char* type_tag)
67 track_.reset(MIX_CreateTrack(mixer));
68 MIX_TagTrack(*
this, type_tag);
72 operator MIX_Track*()
const
78 std::unique_ptr<MIX_Track,
decltype(&MIX_DestroyTrack)> track_{
nullptr, &MIX_DestroyTrack};
81std::mutex soundsource_map_mutex;
82std::map<unsigned int, MIX_Track*> soundsource_map;
84std::array<channel, 32> channel_pool{};
99 explicit audio_cache(std::size_t size)
104 MIX_Audio* get_or_insert(MIX_Mixer* mixer,
const std::string&
filename)
108 cached_audio->last_access = cache_item::clock::now();
109 return cached_audio->value.get();
113 MIX_Audio* audio = MIX_LoadAudio(mixer,
filename.data(),
false);
115 if(
cache.size() == max_size) {
116 auto to_erase = least_recently_used();
117 DBG_AUDIO <<
"Dropping music file from cache: " << to_erase->first;
118 cache.erase(to_erase);
133 explicit cache_item(MIX_Audio* ptr)
134 :
value(ptr, &MIX_DestroyAudio)
139 std::unique_ptr<MIX_Audio,
decltype(&MIX_DestroyAudio)> value;
141 using clock = std::chrono::steady_clock;
146 std::unordered_map<std::string, cache_item>
cache;
148 auto least_recently_used() const -> decltype(cache)::const_iterator
150#ifdef __cpp_lib_ranges
151 return std::ranges::min_element(
cache, {},
152 [](
const auto&
value) {
return value.second.last_access; });
154 return std::min_element(
cache.begin(),
cache.end(),
155 [](
const auto& lhs,
const auto& rhs) { return lhs.second.last_access < rhs.second.last_access; });
160constexpr std::size_t music_cache_limit = 30;
161constexpr std::size_t sound_cache_limit = 500;
163audio_cache music_cache{music_cache_limit};
164audio_cache sound_cache{sound_cache_limit};
166MIX_Mixer* mixer =
nullptr;
167std::size_t mixer_init_counter = 0;
169using namespace std::chrono_literals;
171utils::optional<std::chrono::steady_clock::time_point> music_start_time;
173bool want_new_music =
false;
174auto fade_out_time = 5000ms;
175bool no_fading =
false;
177std::vector<std::string> played_before;
187std::vector<std::shared_ptr<sound::music_track>> playlist;
188std::shared_ptr<sound::music_track> current_track;
189std::shared_ptr<sound::music_track> previous_track;
191std::vector<std::shared_ptr<sound::music_track>>::const_iterator find_track(
const sound::music_track& track)
194 [](
const std::shared_ptr<const sound::music_track>& ptr) {
return *ptr; });
202 return utils::nullopt;
207 if(iter == playlist.end()) {
208 return utils::nullopt;
211 return std::distance(playlist.begin(), iter);
216 return current_track;
221 previous_track = std::exchange(current_track, std::move(track));
226 return previous_track;
231 return playlist.size();
236 if(
i < playlist.size()) {
240 if(
i == playlist.size()) {
241 return current_track;
247void set_track(
unsigned int i,
const std::shared_ptr<music_track>& to)
249 if(
i < playlist.size() && find_track(*to) != playlist.end()) {
250 playlist[
i] = std::make_shared<music_track>(*to);
256 if(
i >= playlist.size()) {
261 if(current_track && current_track == playlist[
i]) {
262 current_track->set_play_once(
true);
265 playlist.erase(playlist.begin() +
i);
270bool track_ok(
const std::string&
id)
280 if(
id == current_track->file_path()) {
284 if(playlist.size() <= 3) {
296 unsigned int num_played = 0;
297 std::set<std::string> played;
298 std::vector<std::string>::reverse_iterator
i;
300 for(
i = played_before.rbegin();
i != played_before.rend(); ++
i) {
303 if(num_played == 2) {
312 if(num_played == 2 && played.size() != playlist.size() - 1) {
313 LOG_AUDIO <<
"Played twice with only " << played.size() <<
" tracks between";
318 i = played_before.rbegin();
319 if(
i != played_before.rend()) {
321 if(
i != played_before.rend()) {
323 LOG_AUDIO <<
"Played just before previous";
336utils::optional<std::size_t> random_next_track_index()
338 auto indices = std::vector<std::size_t>(playlist.size());
339 std::iota(indices.begin(), indices.end(), 0);
342 for(
const auto i : indices) {
343 if(track_ok(playlist[
i]->file_path())) {
348 return utils::nullopt;
351std::shared_ptr<sound::music_track> choose_track()
353 assert(!playlist.empty());
356 std::size_t next_index{0};
364 if(!current_index || current_track->shuffle()) {
365 if(playlist.size() > 1) {
366 next_index = random_next_track_index().value_or(0);
369 next_index = (current_index.value() + 1) % playlist.size();
372 std::shared_ptr next_track = playlist[next_index];
373 DBG_AUDIO <<
"Next track will be " << next_track->file_path();
374 played_before.push_back(current_track->file_path());
378std::string pick_one(
const std::string& files)
386 if(ids.size() == 1) {
391 static std::map<std::string, unsigned int> prev_choices;
394 if(prev_choices.find(files) != prev_choices.end()) {
396 if(choice >= prev_choices[files]) {
400 prev_choices[files] = choice;
403 prev_choices.emplace(files, choice);
413 const char*
const drvname = SDL_GetCurrentAudioDriver();
414 return drvname ? drvname :
"<not initialized>";
419 std::vector<std::string> res;
420 int num_drivers = SDL_GetNumVideoDrivers();
422 for(
int n = 0;
n < num_drivers; ++
n) {
423 const char* drvname = SDL_GetAudioDriver(
n);
424 res.emplace_back(drvname ? drvname :
"<invalid driver>");
434 if(MIX_GetMixerFormat(mixer, &spec)) {
450 if(SDL_WasInit(SDL_INIT_AUDIO) == 0) {
451 if(!SDL_InitSubSystem(SDL_INIT_AUDIO)) {
452 ERR_AUDIO <<
"Could not initialize audio: " << SDL_GetError();
458 mixer_init_counter++;
460 ERR_AUDIO <<
"Could not initialize mixer: " << SDL_GetError();
467 spec.format = SDL_AUDIO_S16;
469 mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec);
471 ERR_AUDIO <<
"Could not initialize audio: " << SDL_GetError();
476 c.allocate_channel(mixer, sound_tracks::music);
480 c.allocate_channel(mixer, sound_tracks::sound_bell);
484 c.allocate_channel(mixer, sound_tracks::sound_timer);
487 for(
channel&
c : positional_channels) {
488 c.allocate_channel(mixer, sound_tracks::sound_source);
492 c.allocate_channel(mixer, sound_tracks::sound_ui);
496 c.allocate_channel(mixer, sound_tracks::sound_fx);
513 MIX_StopAllTracks(mixer, 0);
516 MIX_DestroyMixer(mixer);
525 while(mixer_init_counter-- > 0) {
529 if(SDL_WasInit(SDL_INIT_AUDIO) != 0) {
530 SDL_QuitSubSystem(SDL_INIT_AUDIO);
539 MIX_StopTag(mixer, sound_tracks::music, 500);
546 MIX_StopTag(mixer, sound_tracks::sound_source, 0);
547 MIX_StopTag(mixer, sound_tracks::sound_fx, 0);
557 MIX_StopTag(mixer, sound_tracks::sound_bell, 0);
558 MIX_StopTag(mixer, sound_tracks::sound_timer, 0);
565 MIX_StopTag(mixer, sound_tracks::sound_ui, 0);
572 MIX_ResumeTag(mixer, sound_tracks::music);
579 MIX_ResumeTag(mixer, sound_tracks::sound_source);
580 MIX_ResumeTag(mixer, sound_tracks::sound_fx);
587 MIX_ResumeTag(mixer, sound_tracks::sound_bell);
588 MIX_ResumeTag(mixer, sound_tracks::sound_timer);
595 MIX_ResumeTag(mixer, sound_tracks::sound_ui);
603 current_track->set_play_once(
true);
619 music_start_time = std::chrono::steady_clock::now();
620 want_new_music =
true;
622 fade_out_time = previous_track !=
nullptr ? previous_track->ms_after() : 0ms;
627 if(
i >= playlist.size()) {
639 music_start_time.reset();
640 want_new_music =
true;
642 if(!
prefs::get().music_on() || !mixer || !current_track) {
646 std::string
filename = current_track->file_path();
652 auto fading_time = current_track->ms_before();
662 MIX_StopTrack(music_channels[0], 0);
664 MIX_Audio* music = music_cache.get_or_insert(mixer,
filename);
665 MIX_SetTrackAudio(music_channels[0], music);
669 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fading_time.count());
671 if(!MIX_PlayTrack(music_channels[0], props)) {
672 ERR_AUDIO <<
"Could not play music: " << SDL_GetError() <<
" " <<
filename <<
" ";
675 want_new_music =
false;
678MIX_Track* get_positional_channel(
unsigned soundsource_id)
680 std::scoped_lock lock{soundsource_map_mutex};
681 const auto it = soundsource_map.find(soundsource_id);
682 return it == soundsource_map.end() ? nullptr : it->second;
698 ERR_AUDIO <<
"cannot open track; disabled in this playlist.";
717 if(find_track(*track) == playlist.end()) {
718 auto insert_at = (
i >= 0 &&
static_cast<std::size_t
>(
i) < playlist.size())
719 ? playlist.begin() +
i
723 playlist.insert(insert_at, track);
732 }
else if(!track->
append() && !allow_interrupt_current_track && current_track) {
734 current_track->set_play_once(
true);
740 if(MIX_GetTrackFadeFrames(music_channels[0]) != 0) {
747 auto now = std::chrono::steady_clock::now();
749 bool is_playing = MIX_TrackPlaying(music_channels[0]);
750 bool is_paused = MIX_TrackPaused(music_channels[0]);
751 if(!music_start_time && !playlist.empty() && !is_playing && !is_paused) {
754 music_start_time = now;
759 if(music_start_time && music_refresh_rate.poll()) {
760 want_new_music = now >= *music_start_time - fade_out_time;
764 if(MIX_TrackPlaying(music_channels[0])) {
765 MIX_StopTrack(music_channels[0], MIX_TrackMSToFrames(music_channels[0], fade_out_time.count()));
775 :
events::sdl_handler(false)
783 if(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED) {
784 MIX_ResumeTrack(music_channels[0]);
786 }
else if(event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {
787 if(MIX_TrackPlaying(music_channels[0])) {
788 MIX_PauseTrack(music_channels[0]);
797 played_before.clear();
801 if(current_track->play_once()) {
806 for(
auto m : playlist) {
807 if(*current_track == *m) {
814 if(playlist.empty()) {
827 for(
auto m : playlist) {
828 m->write(snapshot, append);
835 if(MIX_Track* track = get_positional_channel(
id)) {
837 MIX_StopTrack(track, 0);
843 MIX_SetTrack3DPosition(track, &pos);
850 MIX_Track* track = get_positional_channel(
id);
851 return track && MIX_TrackPlaying(track);
861MIX_Track* find_free_channel(sound_tracks::type group)
863 const auto search = [](
const auto& span) -> MIX_Track* {
865 if(!MIX_TrackPlaying(
c)) {
874 case sound_tracks::type::music:
875 return search(music_channels);
876 case sound_tracks::type::sound_bell:
877 return search(bell_channels);
878 case sound_tracks::type::sound_timer:
879 return search(timer_channels);
880 case sound_tracks::type::sound_source:
881 return search(positional_channels);
882 case sound_tracks::type::sound_ui:
883 return search(UI_channels);
884 case sound_tracks::type::sound_fx:
885 return search(SFX_channels);
891void play_sound_internal(
const std::string& files,
892 sound_tracks::type group,
893 unsigned int repeats = 0,
894 unsigned int distance = 0,
895 unsigned int soundsource_id = UINT_MAX,
896 const std::chrono::milliseconds& loop_ticks = 0ms,
897 const std::chrono::milliseconds& fadein_ticks = 0ms)
899 if(files.empty() || !mixer) {
903 if(group == sound_tracks::type::sound_source) {
904 if(soundsource_id != UINT_MAX) {
914 MIX_Track* free_channel = find_free_channel(group);
920 std::string file = pick_one(files);
923 ERR_AUDIO <<
"Could not locate sound file '" << file <<
"'.";
927 std::string real_path = localized.value_or(
filename.value());
933 MIX_SetTrack3DPosition(free_channel, &pos);
935 MIX_Audio*
sound = sound_cache.get_or_insert(mixer, real_path);
936 MIX_SetTrackAudio(free_channel,
sound);
939 if(loop_ticks > 0ms) {
940 SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, -1);
941 if(fadein_ticks > 0ms) {
942 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fadein_ticks.count());
943 SDL_SetNumberProperty(props, MIX_PROP_PLAY_MAX_MILLISECONDS_NUMBER, loop_ticks.count());
946 if(fadein_ticks > 0ms) {
947 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fadein_ticks.count());
949 SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, repeats);
953 if(!MIX_PlayTrack(free_channel, props)) {
954 ERR_AUDIO <<
"error playing sound effect " << real_path <<
" : " << SDL_GetError();
956 }
else if(group == sound_tracks::type::sound_source) {
959 std::scoped_lock lock(soundsource_map_mutex);
960 unsigned int* key =
const_cast<unsigned int*
>(&(soundsource_map.emplace(soundsource_id, free_channel).first->first));
961 DBG_AUDIO <<
"adding callback for soundsource id " << *key;
962 MIX_SetTrackStoppedCallback(free_channel, [](
void* userdata, MIX_Track*){
963 std::scoped_lock lock(soundsource_map_mutex);
964 DBG_AUDIO <<
"in callback to erase soundsource mapping for id " << *
static_cast<unsigned int*
>(userdata);
965 soundsource_map.erase(*
static_cast<unsigned int*
>(userdata));
971volume clamp_gain(volume
value)
978void play_sound(
const std::string& files, sound_tracks::type group,
unsigned int repeats)
981 sound::play_sound_internal(files, group, repeats);
988 sound::play_sound_internal(files, sound_tracks::type::sound_source, repeats, distance,
id);
996 sound::play_sound_internal(files, sound_tracks::type::sound_bell);
1001void play_timer(
const std::string& files,
const std::chrono::milliseconds& loop_ticks,
const std::chrono::milliseconds& fadein_ticks)
1004 sound::play_sound_internal(files, sound_tracks::type::sound_timer, 0,
distance_none, UINT_MAX, loop_ticks, fadein_ticks);
1012 sound::play_sound_internal(files, sound_tracks::type::sound_ui);
1019 return volume{MIX_GetTrackGain(sound::music_channels[0])};
1028 MIX_SetTagGain(mixer, sound_tracks::music, clamp_gain(vol));
1036 return volume{MIX_GetTrackGain(sound::positional_channels[0])};
1045 vol = clamp_gain(vol);
1047 MIX_SetTagGain(mixer, sound_tracks::sound_source, vol);
1048 MIX_SetTagGain(mixer, sound_tracks::sound_fx, vol);
1058 vol = clamp_gain(vol);
1060 MIX_SetTagGain(mixer, sound_tracks::sound_bell, vol);
1061 MIX_SetTagGain(mixer, sound_tracks::sound_timer, vol);
1068 MIX_SetTagGain(mixer, sound_tracks::sound_ui, clamp_gain(vol));
1074 music_cache.clear();
1075 sound_cache.clear();
constexpr std::enable_if< C==dynamic_extent, span< T, detail::span_sub< E, O >::value > >::type subspan() const
A config object defines a single node in a WML file, with access to child nodes.
virtual void join_global()
static rng & default_instance()
int get_random_int(int min, int max)
void handle_window_event(const SDL_Event &event) override
Internal representation of music tracks.
const std::string & file_path() const
static std::shared_ptr< music_track > create(const config &cfg)
A simple wrapper class for optional reference types.
Declarations for File-IO.
std::string id
Text to match against addon_info.tags()
Standard logging facilities (interface).
void clear()
Clear the current render target.
Handling of system events.
utils::optional< std::string > get_binary_file_location(const std::string &type, const std::string &filename)
Returns a complete path to the actual file of a given type, if it exists.
utils::optional< std::string > get_localized_path(const std::string &file, const std::string &suff="")
Returns the localized version of the given filename, if it exists.
Audio output for sound and music.
void write_music_play_list(config &snapshot)
void reposition_sound(unsigned id, unsigned int distance)
void set_UI_volume(volume vol)
void set_music_volume(volume vol)
volume get_music_volume()
void play_music_config(const config &music_node, bool allow_interrupt_current_track, int i)
void remove_track(unsigned int i)
utils::optional< std::size_t > get_current_track_index()
unsigned int get_num_tracks()
constexpr int distance_none
void set_sound_volume(volume vol)
void play_music_once(const std::string &file)
constexpr int distance_silent
void set_track(unsigned int i, const std::shared_ptr< music_track > &to)
std::vector< std::string > enumerate_drivers()
void play_sound(const std::string &files, sound_tracks::type group, unsigned int repeats)
void set_bell_volume(volume vol)
bool is_sound_playing(int id)
volume get_sound_volume()
void play_timer(const std::string &files, const std::chrono::milliseconds &loop_ticks, const std::chrono::milliseconds &fadein_ticks)
void play_sound_positioned(const std::string &files, int repeats, unsigned int distance, unsigned int id)
void commit_music_changes()
void play_track(unsigned int i)
constexpr volume max_volume
void play_UI_sound(const std::string &files)
std::shared_ptr< music_track > get_previous_music_track()
std::shared_ptr< music_track > get_track(unsigned int i)
std::shared_ptr< music_track > get_current_track()
static void set_current_track(std::shared_ptr< music_track > track)
std::string current_driver()
void play_bell(const std::string &files)
std::size_t size(std::string_view str)
Length in characters of a UTF-8 string.
auto find(Container &container, const Value &value, const Projection &projection={})
auto find_in(Container &map, const Value &value) -> utils::optional_reference< typename Container::mapped_type >
std::vector< std::string > square_parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Similar to parenthetical_split, but also expands embedded square brackets.
std::unique_ptr< MIX_Track, decltype(&MIX_DestroyTrack)> track_
std::unordered_map< std::string, cache_item > cache
const std::size_t max_size
static lg::log_domain log_audio("audio")
std::unique_ptr< MIX_Audio, decltype(&MIX_DestroyAudio)> value
clock::time_point last_access
std::string filename
Filename.
static driver_status query()
static std::string get_string(enum_type key)
Converts a enum to its string equivalent.
static map_location::direction n