27 #include <SDL3_mixer/SDL_mixer.h>
34 #define DBG_AUDIO LOG_STREAM(debug, log_audio)
35 #define LOG_AUDIO LOG_STREAM(info, log_audio)
36 #define ERR_AUDIO LOG_STREAM(err, log_audio)
47 void allocate_channel(MIX_Mixer* mixer,
const char* type_tag)
49 track_.reset(MIX_CreateTrack(mixer));
50 MIX_TagTrack(*
this, type_tag);
54 operator MIX_Track*()
const
60 std::unique_ptr<MIX_Track, decltype(&MIX_DestroyTrack)>
track_{
nullptr, &MIX_DestroyTrack};
63 std::mutex soundsource_map_mutex;
64 std::map<unsigned int, MIX_Track*> soundsource_map;
66 std::array<channel, 32> channel_pool{};
79 std::map<std::string, std::shared_ptr<MIX_Audio>> music_cache;
80 std::vector<std::string> music_cache_insertion_order;
82 std::map<std::string, std::shared_ptr<MIX_Audio>> sound_cache;
83 std::vector<std::string> sound_cache_insertion_order;
86 std::size_t mixer_init_counter = 0;
88 using namespace std::chrono_literals;
91 utils::optional<std::chrono::steady_clock::time_point> music_start_time;
93 bool want_new_music =
false;
94 auto fade_out_time = 5000ms;
95 bool no_fading =
false;
97 const std::size_t music_cache_limit = 30;
98 const std::size_t sound_cache_limit = 500;
100 std::vector<std::string> played_before;
110 std::vector<std::shared_ptr<sound::music_track>> current_track_list;
111 std::shared_ptr<sound::music_track> current_track;
112 unsigned int current_track_index = 0;
113 std::shared_ptr<sound::music_track> previous_track;
115 std::vector<std::shared_ptr<sound::music_track>>::const_iterator find_track(
const sound::music_track& track)
118 [](
const std::shared_ptr<const sound::music_track>& ptr) {
return *ptr; });
125 if(current_track_index >= current_track_list.size()){
128 return current_track_index;
132 return current_track;
136 return previous_track;
140 previous_track = std::move(track);
145 return current_track_list.size();
150 if(
i < current_track_list.size()) {
151 return current_track_list[
i];
154 if(
i == current_track_list.size()) {
155 return current_track;
161 void set_track(
unsigned int i,
const std::shared_ptr<music_track>& to)
163 if(
i < current_track_list.size() && find_track(*to) != current_track_list.end()) {
164 current_track_list[
i] = std::make_shared<music_track>(*to);
170 if(
i >= current_track_list.size()) {
174 if(
i == current_track_index) {
177 current_track->set_play_once(
true);
180 current_track_index = current_track_list.size() - 1;
181 }
else if(
i < current_track_index) {
182 current_track_index--;
185 current_track_list.erase(current_track_list.begin() +
i);
190 bool track_ok(
const std::string&
id)
200 if(
id == current_track->file_path()) {
204 if(current_track_list.size() <= 3) {
216 unsigned int num_played = 0;
217 std::set<std::string> played;
218 std::vector<std::string>::reverse_iterator
i;
220 for(
i = played_before.rbegin();
i != played_before.rend(); ++
i) {
223 if(num_played == 2) {
232 if(num_played == 2 && played.size() != current_track_list.size() - 1) {
233 LOG_AUDIO <<
"Played twice with only " << played.size() <<
" tracks between";
238 i = played_before.rbegin();
239 if(
i != played_before.rend()) {
241 if(
i != played_before.rend()) {
243 LOG_AUDIO <<
"Played just before previous";
252 std::shared_ptr<sound::music_track> choose_track()
254 assert(!current_track_list.empty());
256 if(current_track_index >= current_track_list.size()) {
257 current_track_index = 0;
260 if(current_track_list[current_track_index]->
shuffle()) {
261 unsigned int track = 0;
263 if(current_track_list.size() > 1) {
266 }
while(!track_ok(current_track_list[track]->file_path()));
269 current_track_index = track;
272 DBG_AUDIO <<
"Next track will be " << current_track_list[current_track_index]->file_path();
273 played_before.push_back(current_track_list[current_track_index]->file_path());
274 return current_track_list[current_track_index];
277 std::string pick_one(
const std::string& files)
285 if(ids.size() == 1) {
290 static std::map<std::string, unsigned int> prev_choices;
293 if(prev_choices.find(files) != prev_choices.end()) {
295 if(choice >= prev_choices[files]) {
299 prev_choices[files] = choice;
302 prev_choices.emplace(files, choice);
312 const char*
const drvname = SDL_GetCurrentAudioDriver();
313 return drvname ? drvname :
"<not initialized>";
318 std::vector<std::string> res;
319 int num_drivers = SDL_GetNumVideoDrivers();
321 for(
int n = 0;
n < num_drivers; ++
n) {
322 const char* drvname = SDL_GetAudioDriver(
n);
323 res.emplace_back(drvname ? drvname :
"<invalid driver>");
335 if(MIX_GetMixerFormat(mixer, &spec)) {
337 res.frequency = spec.freq;
338 res.format = spec.format;
339 res.channels = spec.channels;
349 if(SDL_WasInit(SDL_INIT_AUDIO) == 0) {
350 if(!SDL_InitSubSystem(SDL_INIT_AUDIO)) {
351 ERR_AUDIO <<
"Could not initialize audio: " << SDL_GetError();
357 mixer_init_counter++;
359 ERR_AUDIO <<
"Could not initialize mixer: " << SDL_GetError();
366 spec.format = SDL_AUDIO_S16;
368 mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec);
371 ERR_AUDIO <<
"Could not initialize audio: " << SDL_GetError();
378 c.allocate_channel(mixer, sound_tracks::music);
382 c.allocate_channel(mixer, sound_tracks::sound_bell);
386 c.allocate_channel(mixer, sound_tracks::sound_timer);
389 for(
channel&
c : positional_channels) {
390 c.allocate_channel(mixer, sound_tracks::sound_source);
394 c.allocate_channel(mixer, sound_tracks::sound_ui);
398 c.allocate_channel(mixer, sound_tracks::sound_fx);
425 MIX_DestroyMixer(mixer);
431 for(std::size_t
i = 0;
i < mixer_init_counter;
i++) {
434 mixer_init_counter = 0;
436 if(SDL_WasInit(SDL_INIT_AUDIO) != 0) {
437 SDL_QuitSubSystem(SDL_INIT_AUDIO);
450 if(music ||
sound || bell || UI_sound) {
476 MIX_StopTrack(
c, MIX_TrackMSToFrames(
c, 500));
484 MIX_StopTag(mixer, sound_tracks::sound_source, 0);
485 MIX_StopTag(mixer, sound_tracks::sound_fx, 0);
495 MIX_StopTag(mixer, sound_tracks::sound_bell, 0);
496 MIX_StopTag(mixer, sound_tracks::sound_timer, 0);
503 MIX_StopTag(mixer, sound_tracks::sound_ui, 0);
511 current_track = std::move(track);
512 current_track->set_play_once(
true);
513 current_track_index = current_track_list.size();
520 current_track_list.clear();
529 music_start_time = std::chrono::steady_clock::now();
530 want_new_music =
true;
532 fade_out_time = previous_track !=
nullptr ? previous_track->ms_after() : 0ms;
538 if(
i >= current_track_list.size()) {
539 current_track = choose_track();
541 current_track_index =
i;
542 current_track = current_track_list[
i];
549 void play_new_music()
551 music_start_time.reset();
552 want_new_music =
true;
554 if(!
prefs::get().music_on() || !mix_ok || !current_track) {
558 std::string
filename = current_track->file_path();
564 auto fading_time = current_track->ms_before();
574 MIX_StopTrack(music_channels[0], 0);
576 std::shared_ptr<MIX_Audio> music;
577 if(music_cache.count(
filename) != 0) {
581 music.reset(MIX_LoadAudio(mixer,
filename.c_str(),
false), &MIX_DestroyAudio);
586 MIX_SetTrackAudio(music_channels[0], music.get());
589 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fading_time.count());
591 if(!MIX_PlayTrack(music_channels[0], props)) {
592 ERR_AUDIO <<
"Could not play music: " << SDL_GetError() <<
" " <<
filename <<
" ";
593 }
else if(music_cache.count(
filename) == 0) {
594 music_cache.emplace(
filename, music);
595 music_cache_insertion_order.emplace_back(
filename);
597 if(music_cache.size() > music_cache_limit) {
598 std::string to_erase = music_cache_insertion_order[0];
599 DBG_AUDIO <<
"Uncaching music file " << to_erase;
600 music_cache_insertion_order.erase(music_cache_insertion_order.begin());
601 music_cache.erase(to_erase);
605 want_new_music =
false;
608 MIX_Track* get_positional_channel(
unsigned soundsource_id)
610 std::scoped_lock lock{soundsource_map_mutex};
611 const auto it = soundsource_map.find(soundsource_id);
612 return it == soundsource_map.end() ? nullptr : it->second;
628 ERR_AUDIO <<
"cannot open track; disabled in this playlist.";
633 if(track->play_once()) {
635 current_track = std::move(track);
636 current_track_index = current_track_list.size();
642 if(!track->append()) {
643 current_track_list.clear();
646 auto iter = find_track(*track);
650 if(iter == current_track_list.end()) {
651 auto insert_at = (
i >= 0 &&
static_cast<std::size_t
>(
i) < current_track_list.size())
652 ? current_track_list.begin() +
i
653 : current_track_list.end();
656 iter = current_track_list.insert(insert_at, track);
657 auto new_track_index = std::distance(current_track_list.cbegin(), iter);
661 if(new_track_index <= current_track_index) {
662 ++current_track_index;
665 ERR_AUDIO <<
"tried to add duplicate track '" << track->file_path() <<
"'";
669 if(track->immediate()) {
671 current_track = *iter;
672 current_track_index = std::distance(current_track_list.cbegin(), iter);
674 }
else if(!track->append() && !allow_interrupt_current_track && current_track) {
676 current_track->set_play_once(
true);
682 if(MIX_GetTrackFadeFrames(music_channels[0]) != 0) {
689 auto now = std::chrono::steady_clock::now();
691 bool is_playing = MIX_TrackPlaying(music_channels[0]);
692 bool is_paused = MIX_TrackPaused(music_channels[0]);
693 if(!music_start_time && !current_track_list.empty() && !is_playing && !is_paused) {
696 current_track = choose_track();
697 music_start_time = now;
702 if(music_start_time && music_refresh_rate.poll()) {
703 want_new_music = now >= *music_start_time - fade_out_time;
707 if(MIX_TrackPlaying(music_channels[0])) {
708 MIX_StopTrack(music_channels[0], MIX_TrackMSToFrames(music_channels[0], fade_out_time.count()));
718 :
events::sdl_handler(false)
726 if(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED) {
727 MIX_ResumeTrack(music_channels[0]);
729 }
else if(event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {
730 if(MIX_TrackPlaying(music_channels[0])) {
731 MIX_PauseTrack(music_channels[0]);
740 played_before.clear();
744 if(current_track->play_once()) {
749 for(
auto m : current_track_list) {
750 if(*current_track == *m) {
757 if(current_track_list.empty()) {
763 current_track = choose_track();
771 for(
auto m : current_track_list) {
772 m->write(snapshot, append);
779 if(MIX_Track* track = get_positional_channel(
id)) {
781 MIX_StopTrack(track, 0);
787 MIX_SetTrack3DPosition(track, &pos);
794 MIX_Track* track = get_positional_channel(
id);
795 return track && MIX_TrackPlaying(track);
807 const auto search = [](
const auto& span) -> MIX_Track* {
809 if(!MIX_TrackPlaying(
c)) {
818 case sound_tracks::type::music:
819 return search(music_channels);
820 case sound_tracks::type::sound_bell:
821 return search(bell_channels);
822 case sound_tracks::type::sound_timer:
823 return search(timer_channels);
824 case sound_tracks::type::sound_source:
825 return search(positional_channels);
826 case sound_tracks::type::sound_ui:
827 return search(UI_channels);
828 case sound_tracks::type::sound_fx:
829 return search(SFX_channels);
835 void play_sound_internal(
const std::string& files,
837 unsigned int repeats = 0,
838 unsigned int distance = 0,
839 unsigned int soundsource_id = UINT_MAX,
840 const std::chrono::milliseconds& loop_ticks = 0ms,
841 const std::chrono::milliseconds& fadein_ticks = 0ms)
843 if(files.empty() || !mix_ok) {
847 if(group == sound_tracks::type::sound_source) {
848 if(soundsource_id != UINT_MAX) {
858 MIX_Track* free_channel = find_free_channel(group);
864 std::string file = pick_one(files);
867 ERR_AUDIO <<
"Could not locate sound file '" << file <<
"'.";
871 std::string real_path = localized.value_or(
filename.value());
877 MIX_SetTrack3DPosition(free_channel, &pos);
879 std::shared_ptr<MIX_Audio>
sound;
880 if(sound_cache.count(real_path) != 0) {
881 sound = sound_cache[real_path];
882 DBG_AUDIO <<
"cache hit for " << real_path;
884 sound.reset(MIX_LoadAudio(mixer, real_path.c_str(),
false), &MIX_DestroyAudio);
885 DBG_AUDIO <<
"cache miss for " << real_path;
888 MIX_SetTrackAudio(free_channel,
sound.get());
893 if(loop_ticks > 0ms) {
894 if(fadein_ticks > 0ms) {
895 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fadein_ticks.count());
896 SDL_SetNumberProperty(props, MIX_PROP_PLAY_MAX_MILLISECONDS_NUMBER, loop_ticks.count());
898 SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, -1);
901 if(fadein_ticks > 0ms) {
902 SDL_SetNumberProperty(props, MIX_PROP_PLAY_FADE_IN_MILLISECONDS_NUMBER, fadein_ticks.count());
904 SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, repeats);
908 res = MIX_PlayTrack(free_channel, props);
911 ERR_AUDIO <<
"error playing sound effect " << real_path <<
" : " << SDL_GetError();
914 }
else if(group == sound_tracks::type::sound_source) {
917 std::scoped_lock lock(soundsource_map_mutex);
918 unsigned int* key =
const_cast<unsigned int*
>(&(soundsource_map.emplace(soundsource_id, free_channel).first->first));
919 DBG_AUDIO <<
"adding callback for soundsource id " << *key;
920 MIX_SetTrackStoppedCallback(free_channel, [](
void* userdata, MIX_Track*){
921 std::scoped_lock lock(soundsource_map_mutex);
922 DBG_AUDIO <<
"in callback to erase soundsource mapping for id " << *
static_cast<unsigned int*
>(userdata);
923 soundsource_map.erase(*
static_cast<unsigned int*
>(userdata));
927 if(res && sound_cache.count(real_path) == 0) {
928 sound_cache.emplace(real_path,
sound);
929 sound_cache_insertion_order.emplace_back(real_path);
931 if(sound_cache.size() > sound_cache_limit) {
932 std::string to_erase = sound_cache_insertion_order[0];
933 DBG_AUDIO <<
"Uncaching sound file " << to_erase;
934 sound_cache_insertion_order.erase(sound_cache_insertion_order.begin());
935 sound_cache.erase(to_erase);
941 volume clamp_gain(volume value)
951 sound::play_sound_internal(files, group, repeats);
958 sound::play_sound_internal(files, sound_tracks::type::sound_source, repeats, distance,
id);
966 sound::play_sound_internal(files, sound_tracks::type::sound_bell);
971 void play_timer(
const std::string& files,
const std::chrono::milliseconds& loop_ticks,
const std::chrono::milliseconds& fadein_ticks)
974 sound::play_sound_internal(files, sound_tracks::type::sound_timer, 0,
distance_none, UINT_MAX, loop_ticks, fadein_ticks);
982 sound::play_sound_internal(files, sound_tracks::type::sound_ui);
989 return volume{MIX_GetTrackGain(sound::music_channels[0])};
998 MIX_SetTrackGain(sound::music_channels[0], clamp_gain(vol));
1006 return volume{MIX_GetTrackGain(sound::positional_channels[0])};
1015 vol = clamp_gain(vol);
1018 for(
channel&
c : positional_channels) {
1019 MIX_SetTrackGain(
c, vol);
1023 MIX_SetTrackGain(
c, vol);
1034 vol = clamp_gain(vol);
1036 MIX_SetTrackGain(sound::bell_channels[0], vol);
1037 MIX_SetTrackGain(sound::timer_channels[0], vol);
1044 vol = clamp_gain(vol);
1047 MIX_SetTrackGain(
c, vol);
1054 music_cache.clear();
1055 music_cache_insertion_order.clear();
1056 sound_cache.clear();
1057 sound_cache_insertion_order.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()
unsigned int sample_rate()
std::size_t sound_buffer_size()
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.
static std::shared_ptr< music_track > create(const config &cfg)
Declarations for File-IO.
std::string id
Text to match against addon_info.tags()
Standard logging facilities (interface).
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)
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)
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
utils::optional< unsigned int > get_current_track_index()
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)
void set_previous_track(std::shared_ptr< music_track > track)
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)
auto find(Container &container, const Value &value, const Projection &projection={})
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_
static lg::log_domain log_audio("audio")
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