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)
43 template<
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};
81 std::mutex soundsource_map_mutex;
82 std::map<unsigned int, MIX_Track*> soundsource_map;
84 std::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);
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; });
160 constexpr std::size_t music_cache_limit = 30;
161 constexpr std::size_t sound_cache_limit = 500;
163 audio_cache music_cache{music_cache_limit};
164 audio_cache sound_cache{sound_cache_limit};
166 MIX_Mixer* mixer =
nullptr;
167 std::size_t mixer_init_counter = 0;
169 using namespace std::chrono_literals;
171 utils::optional<std::chrono::steady_clock::time_point> music_start_time;
173 bool want_new_music =
false;
174 auto fade_out_time = 5000ms;
175 bool no_fading =
false;
177 std::vector<std::string> played_before;
187 std::vector<std::shared_ptr<sound::music_track>> playlist;
188 std::shared_ptr<sound::music_track> current_track;
189 std::shared_ptr<sound::music_track> previous_track;
191 std::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);
215 return current_track;
219 previous_track = std::exchange(current_track, std::move(track));
223 return previous_track;
228 return playlist.size();
233 if(
i < playlist.size()) {
237 if(
i == playlist.size()) {
238 return current_track;
244 void set_track(
unsigned int i,
const std::shared_ptr<music_track>& to)
246 if(
i < playlist.size() && find_track(*to) != playlist.end()) {
247 playlist[
i] = std::make_shared<music_track>(*to);
253 if(
i >= playlist.size()) {
258 if(current_track && current_track == playlist[
i]) {
259 current_track->set_play_once(
true);
262 playlist.erase(playlist.begin() +
i);
267 bool track_ok(
const std::string&
id)
277 if(
id == current_track->file_path()) {
281 if(playlist.size() <= 3) {
293 unsigned int num_played = 0;
294 std::set<std::string> played;
295 std::vector<std::string>::reverse_iterator
i;
297 for(
i = played_before.rbegin();
i != played_before.rend(); ++
i) {
300 if(num_played == 2) {
309 if(num_played == 2 && played.size() != playlist.size() - 1) {
310 LOG_AUDIO <<
"Played twice with only " << played.size() <<
" tracks between";
315 i = played_before.rbegin();
316 if(
i != played_before.rend()) {
318 if(
i != played_before.rend()) {
320 LOG_AUDIO <<
"Played just before previous";
333 utils::optional<std::size_t> random_next_track_index()
335 auto indices = std::vector<std::size_t>(playlist.size());
336 std::iota(indices.begin(), indices.end(), 0);
339 for(
const auto i : indices) {
340 if(track_ok(playlist[
i]->file_path())) {
345 return utils::nullopt;
348 std::shared_ptr<sound::music_track> choose_track()
350 assert(!playlist.empty());
353 std::size_t next_index{0};
361 if(!current_index || current_track->shuffle()) {
362 if(playlist.size() > 1) {
363 next_index = random_next_track_index().value_or(0);
366 next_index = (current_index.value() + 1) % playlist.size();
369 std::shared_ptr next_track = playlist[next_index];
370 DBG_AUDIO <<
"Next track will be " << next_track->file_path();
371 played_before.push_back(current_track->file_path());
375 std::string pick_one(
const std::string& files)
383 if(ids.size() == 1) {
388 static std::map<std::string, unsigned int> prev_choices;
391 if(prev_choices.find(files) != prev_choices.end()) {
393 if(choice >= prev_choices[files]) {
397 prev_choices[files] = choice;
400 prev_choices.emplace(files, choice);
410 const char*
const drvname = SDL_GetCurrentAudioDriver();
411 return drvname ? drvname :
"<not initialized>";
416 std::vector<std::string> res;
417 int num_drivers = SDL_GetNumVideoDrivers();
419 for(
int n = 0;
n < num_drivers; ++
n) {
420 const char* drvname = SDL_GetAudioDriver(
n);
421 res.emplace_back(drvname ? drvname :
"<invalid driver>");
431 if(MIX_GetMixerFormat(mixer, &spec)) {
447 if(SDL_WasInit(SDL_INIT_AUDIO) == 0) {
448 if(!SDL_InitSubSystem(SDL_INIT_AUDIO)) {
449 ERR_AUDIO <<
"Could not initialize audio: " << SDL_GetError();
455 mixer_init_counter++;
457 ERR_AUDIO <<
"Could not initialize mixer: " << SDL_GetError();
464 spec.format = SDL_AUDIO_S16;
466 mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec);
468 ERR_AUDIO <<
"Could not initialize audio: " << SDL_GetError();
473 c.allocate_channel(mixer, sound_tracks::music);
477 c.allocate_channel(mixer, sound_tracks::sound_bell);
481 c.allocate_channel(mixer, sound_tracks::sound_timer);
484 for(
channel&
c : positional_channels) {
485 c.allocate_channel(mixer, sound_tracks::sound_source);
489 c.allocate_channel(mixer, sound_tracks::sound_ui);
493 c.allocate_channel(mixer, sound_tracks::sound_fx);
510 MIX_StopAllTracks(mixer, 0);
513 MIX_DestroyMixer(mixer);
522 while(mixer_init_counter-- > 0) {
526 if(SDL_WasInit(SDL_INIT_AUDIO) != 0) {
527 SDL_QuitSubSystem(SDL_INIT_AUDIO);
536 MIX_StopTag(mixer, sound_tracks::music, 500);
543 MIX_StopTag(mixer, sound_tracks::sound_source, 0);
544 MIX_StopTag(mixer, sound_tracks::sound_fx, 0);
554 MIX_StopTag(mixer, sound_tracks::sound_bell, 0);
555 MIX_StopTag(mixer, sound_tracks::sound_timer, 0);
562 MIX_StopTag(mixer, sound_tracks::sound_ui, 0);
569 MIX_ResumeTag(mixer, sound_tracks::music);
576 MIX_ResumeTag(mixer, sound_tracks::sound_source);
577 MIX_ResumeTag(mixer, sound_tracks::sound_fx);
584 MIX_ResumeTag(mixer, sound_tracks::sound_bell);
585 MIX_ResumeTag(mixer, sound_tracks::sound_timer);
592 MIX_ResumeTag(mixer, sound_tracks::sound_ui);
600 current_track->set_play_once(
true);
616 music_start_time = std::chrono::steady_clock::now();
617 want_new_music =
true;
619 fade_out_time = previous_track !=
nullptr ? previous_track->ms_after() : 0ms;
624 if(
i >= playlist.size()) {
634 void play_new_music()
636 music_start_time.reset();
637 want_new_music =
true;
639 if(!
prefs::get().music_on() || !mixer || !current_track) {
643 std::string
filename = current_track->file_path();
649 auto fading_time = current_track->ms_before();
659 MIX_StopTrack(music_channels[0], 0);
661 MIX_Audio* music = music_cache.get_or_insert(mixer,
filename);
662 MIX_SetTrackAudio(music_channels[0], music);
666 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fading_time.count());
668 if(!MIX_PlayTrack(music_channels[0], props)) {
669 ERR_AUDIO <<
"Could not play music: " << SDL_GetError() <<
" " <<
filename <<
" ";
672 want_new_music =
false;
675 MIX_Track* get_positional_channel(
unsigned soundsource_id)
677 std::scoped_lock lock{soundsource_map_mutex};
678 const auto it = soundsource_map.find(soundsource_id);
679 return it == soundsource_map.end() ? nullptr : it->second;
695 ERR_AUDIO <<
"cannot open track; disabled in this playlist.";
714 if(find_track(*track) == playlist.end()) {
715 auto insert_at = (
i >= 0 &&
static_cast<std::size_t
>(
i) < playlist.size())
716 ? playlist.begin() +
i
720 playlist.insert(insert_at, track);
729 }
else if(!track->
append() && !allow_interrupt_current_track && current_track) {
731 current_track->set_play_once(
true);
737 if(MIX_GetTrackFadeFrames(music_channels[0]) != 0) {
744 auto now = std::chrono::steady_clock::now();
746 bool is_playing = MIX_TrackPlaying(music_channels[0]);
747 bool is_paused = MIX_TrackPaused(music_channels[0]);
748 if(!music_start_time && !playlist.empty() && !is_playing && !is_paused) {
751 music_start_time = now;
756 if(music_start_time && music_refresh_rate.poll()) {
757 want_new_music = now >= *music_start_time - fade_out_time;
761 if(MIX_TrackPlaying(music_channels[0])) {
762 MIX_StopTrack(music_channels[0], MIX_TrackMSToFrames(music_channels[0], fade_out_time.count()));
772 :
events::sdl_handler(false)
780 if(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED) {
781 MIX_ResumeTrack(music_channels[0]);
783 }
else if(event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {
784 if(MIX_TrackPlaying(music_channels[0])) {
785 MIX_PauseTrack(music_channels[0]);
794 played_before.clear();
798 if(current_track->play_once()) {
803 for(
auto m : playlist) {
804 if(*current_track == *m) {
811 if(playlist.empty()) {
824 for(
auto m : playlist) {
825 m->write(snapshot, append);
832 if(MIX_Track* track = get_positional_channel(
id)) {
834 MIX_StopTrack(track, 0);
840 MIX_SetTrack3DPosition(track, &pos);
847 MIX_Track* track = get_positional_channel(
id);
848 return track && MIX_TrackPlaying(track);
860 const auto search = [](
const auto& span) -> MIX_Track* {
862 if(!MIX_TrackPlaying(
c)) {
871 case sound_tracks::type::music:
872 return search(music_channels);
873 case sound_tracks::type::sound_bell:
874 return search(bell_channels);
875 case sound_tracks::type::sound_timer:
876 return search(timer_channels);
877 case sound_tracks::type::sound_source:
878 return search(positional_channels);
879 case sound_tracks::type::sound_ui:
880 return search(UI_channels);
881 case sound_tracks::type::sound_fx:
882 return search(SFX_channels);
888 void play_sound_internal(
const std::string& files,
890 unsigned int repeats = 0,
891 unsigned int distance = 0,
892 unsigned int soundsource_id = UINT_MAX,
893 const std::chrono::milliseconds& loop_ticks = 0ms,
894 const std::chrono::milliseconds& fadein_ticks = 0ms)
896 if(files.empty() || !mixer) {
900 if(group == sound_tracks::type::sound_source) {
901 if(soundsource_id != UINT_MAX) {
911 MIX_Track* free_channel = find_free_channel(group);
917 std::string file = pick_one(files);
920 ERR_AUDIO <<
"Could not locate sound file '" << file <<
"'.";
924 std::string real_path = localized.value_or(
filename.value());
930 MIX_SetTrack3DPosition(free_channel, &pos);
932 MIX_Audio*
sound = sound_cache.get_or_insert(mixer, real_path);
933 MIX_SetTrackAudio(free_channel,
sound);
936 if(loop_ticks > 0ms) {
937 SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, -1);
938 if(fadein_ticks > 0ms) {
939 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fadein_ticks.count());
940 SDL_SetNumberProperty(props, MIX_PROP_PLAY_MAX_MILLISECONDS_NUMBER, loop_ticks.count());
943 if(fadein_ticks > 0ms) {
944 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fadein_ticks.count());
946 SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, repeats);
950 if(!MIX_PlayTrack(free_channel, props)) {
951 ERR_AUDIO <<
"error playing sound effect " << real_path <<
" : " << SDL_GetError();
953 }
else if(group == sound_tracks::type::sound_source) {
956 std::scoped_lock lock(soundsource_map_mutex);
957 unsigned int* key =
const_cast<unsigned int*
>(&(soundsource_map.emplace(soundsource_id, free_channel).first->first));
958 DBG_AUDIO <<
"adding callback for soundsource id " << *key;
959 MIX_SetTrackStoppedCallback(free_channel, [](
void* userdata, MIX_Track*){
960 std::scoped_lock lock(soundsource_map_mutex);
961 DBG_AUDIO <<
"in callback to erase soundsource mapping for id " << *
static_cast<unsigned int*
>(userdata);
962 soundsource_map.erase(*
static_cast<unsigned int*
>(userdata));
968 volume clamp_gain(volume
value)
978 sound::play_sound_internal(files, group, repeats);
985 sound::play_sound_internal(files, sound_tracks::type::sound_source, repeats, distance,
id);
993 sound::play_sound_internal(files, sound_tracks::type::sound_bell);
998 void play_timer(
const std::string& files,
const std::chrono::milliseconds& loop_ticks,
const std::chrono::milliseconds& fadein_ticks)
1001 sound::play_sound_internal(files, sound_tracks::type::sound_timer, 0,
distance_none, UINT_MAX, loop_ticks, fadein_ticks);
1009 sound::play_sound_internal(files, sound_tracks::type::sound_ui);
1016 return volume{MIX_GetTrackGain(sound::music_channels[0])};
1025 MIX_SetTagGain(mixer, sound_tracks::music, clamp_gain(vol));
1033 return volume{MIX_GetTrackGain(sound::positional_channels[0])};
1042 vol = clamp_gain(vol);
1044 MIX_SetTagGain(mixer, sound_tracks::sound_source, vol);
1045 MIX_SetTagGain(mixer, sound_tracks::sound_fx, vol);
1055 vol = clamp_gain(vol);
1057 MIX_SetTagGain(mixer, sound_tracks::sound_bell, vol);
1058 MIX_SetTagGain(mixer, sound_tracks::sound_timer, vol);
1065 MIX_SetTagGain(mixer, sound_tracks::sound_ui, clamp_gain(vol));
1071 music_cache.clear();
1072 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.
std::vector< game_tip > shuffle(const std::vector< game_tip > &tips)
Shuffles the tips.
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)
void set_current_track(std::shared_ptr< music_track > track)
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()
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