25 #include <SDL2/SDL_mixer.h>
31 #define DBG_AUDIO LOG_STREAM(debug, log_audio)
32 #define LOG_AUDIO LOG_STREAM(info, log_audio)
33 #define ERR_AUDIO LOG_STREAM(err, log_audio)
35 #if (MIX_MAJOR_VERSION < 1) || (MIX_MAJOR_VERSION == 1) && ((MIX_MINOR_VERSION < 2) || (MIX_MINOR_VERSION == 2) && (MIX_PATCHLEVEL <= 11))
36 #error "Please upgrade to SDL mixer version >= 1.2.12, we don't support older versions anymore."
52 int music_start_time = 0;
53 unsigned music_refresh = 0;
54 unsigned music_refresh_rate = 20;
55 bool want_new_music =
false;
56 int fadingout_time = 5000;
57 bool no_fading =
false;
58 bool unload_music =
false;
61 const std::size_t n_of_channels = 32;
64 const std::size_t bell_channel = 0;
65 const std::size_t timer_channel = 1;
68 const std::size_t source_channels = 8;
69 const std::size_t source_channel_start = timer_channel + 1;
70 const std::size_t source_channel_last = source_channel_start + source_channels - 1;
71 const std::size_t UI_sound_channels = 2;
72 const std::size_t UI_sound_channel_start = source_channel_last + 1;
73 const std::size_t UI_sound_channel_last = UI_sound_channel_start + UI_sound_channels - 1;
74 const std::size_t n_reserved_channels = UI_sound_channel_last + 1;
78 unsigned max_cached_chunks = 256;
80 std::map<Mix_Chunk*, int> chunk_usage;
95 assert(this_usage != chunk_usage.end());
96 if(--(this_usage->second) == 0) {
98 chunk_usage.erase(this_usage);
104 class sound_cache_chunk
107 sound_cache_chunk(
const std::string&
f)
113 sound_cache_chunk(
const sound_cache_chunk& scc)
129 void set_data(Mix_Chunk*
d)
136 Mix_Chunk* get_data()
const
141 bool operator==(
const sound_cache_chunk& scc)
const
143 return file == scc.file;
146 bool operator!=(
const sound_cache_chunk& scc)
const
151 sound_cache_chunk& operator=(
const sound_cache_chunk& scc)
155 set_data(scc.get_data());
163 std::list<sound_cache_chunk> sound_cache;
165 std::map<std::string, std::shared_ptr<Mix_Music>> music_cache;
167 std::vector<std::string> played_before;
177 std::vector<std::shared_ptr<sound::music_track>> current_track_list;
178 std::shared_ptr<sound::music_track> current_track;
179 unsigned int current_track_index = 0;
180 std::shared_ptr<sound::music_track> previous_track;
182 std::vector<std::shared_ptr<sound::music_track>>::const_iterator find_track(
const sound::music_track& track)
184 return std::find_if(current_track_list.begin(), current_track_list.end(),
185 [&track](
const std::shared_ptr<const sound::music_track>& ptr) { return *ptr == track; }
201 if(current_track_index >= current_track_list.size()){
204 return current_track_index;
208 return current_track;
212 return previous_track;
216 previous_track = track;
221 return current_track_list.size();
226 if(
i < current_track_list.size()) {
227 return current_track_list[
i];
230 if(
i == current_track_list.size()) {
231 return current_track;
237 void set_track(
unsigned int i,
const std::shared_ptr<music_track>& to)
239 if(
i < current_track_list.size() && find_track(*to) != current_track_list.end()) {
240 current_track_list[
i] = std::make_shared<music_track>(*to);
246 if(
i >= current_track_list.size()) {
250 if(
i == current_track_index) {
253 current_track->set_play_once(
true);
256 current_track_index = current_track_list.size() - 1;
257 }
else if(
i < current_track_index) {
258 current_track_index--;
261 current_track_list.erase(current_track_list.begin() +
i);
276 if(
id == current_track->file_path()) {
280 if(current_track_list.size() <= 3) {
292 unsigned int num_played = 0;
293 std::set<std::string> played;
294 std::vector<std::string>::reverse_iterator
i;
296 for(
i = played_before.rbegin();
i != played_before.rend(); ++
i) {
299 if(num_played == 2) {
308 if(num_played == 2 && played.size() != current_track_list.size() - 1) {
309 LOG_AUDIO <<
"Played twice with only " << played.size() <<
" tracks between";
314 i = played_before.rbegin();
315 if(
i != played_before.rend()) {
317 if(
i != played_before.rend()) {
319 LOG_AUDIO <<
"Played just before previous";
330 assert(!current_track_list.empty());
332 if(current_track_index >= current_track_list.size()) {
333 current_track_index = 0;
336 if(current_track_list[current_track_index]->
shuffle()) {
337 unsigned int track = 0;
339 if(current_track_list.size() > 1) {
342 }
while(!
track_ok(current_track_list[track]->file_path()));
345 current_track_index = track;
348 DBG_AUDIO <<
"Next track will be " << current_track_list[current_track_index]->file_path();
349 played_before.push_back(current_track_list[current_track_index]->file_path());
350 return current_track_list[current_track_index];
353 static std::string
pick_one(
const std::string& files)
361 if(ids.size() == 1) {
366 static std::map<std::string, unsigned int> prev_choices;
369 if(prev_choices.find(files) != prev_choices.end()) {
371 if(choice >= prev_choices[files]) {
375 prev_choices[files] = choice;
378 prev_choices.emplace(files, choice);
412 const char*
const drvname = SDL_GetCurrentAudioDriver();
413 return drvname ? drvname :
"<not initialized>";
418 std::vector<std::string> res;
419 int num_drivers = SDL_GetNumVideoDrivers();
421 for(
int n = 0;
n < num_drivers; ++
n) {
422 const char* drvname = SDL_GetAudioDriver(
n);
423 res.emplace_back(drvname ? drvname :
"<invalid driver>");
434 Mix_QuerySpec(&res.frequency, &res.format, &res.channels);
444 if(SDL_WasInit(SDL_INIT_AUDIO) == 0) {
445 if(SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
453 ERR_AUDIO <<
"Could not initialize audio: " << Mix_GetError();
458 Mix_AllocateChannels(n_of_channels);
459 Mix_ReserveChannels(n_reserved_channels);
467 Mix_GroupChannels(source_channel_start, source_channel_last,
SOUND_SOURCES);
468 Mix_GroupChannels(UI_sound_channel_start, UI_sound_channel_last,
SOUND_UI);
469 Mix_GroupChannels(n_reserved_channels, n_of_channels - 1,
SOUND_FX);
480 DBG_AUDIO <<
"Channel layout: " << n_of_channels <<
" channels (" << n_reserved_channels <<
" reserved)\n"
481 <<
" " << bell_channel <<
" - bell\n"
482 <<
" " << timer_channel <<
" - timer\n"
483 <<
" " << source_channel_start <<
".." << source_channel_last <<
" - sound sources\n"
484 <<
" " << UI_sound_channel_start <<
".." << UI_sound_channel_last <<
" - UI\n"
485 <<
" " << UI_sound_channel_last + 1 <<
".." << n_of_channels - 1 <<
" - sound effects";
495 int frequency, channels;
506 int numtimesopened = Mix_QuerySpec(&frequency, &
format, &channels);
507 if(numtimesopened == 0) {
508 ERR_AUDIO <<
"Error closing audio device: " << Mix_GetError();
511 while(numtimesopened) {
517 if(SDL_WasInit(SDL_INIT_AUDIO) != 0) {
518 SDL_QuitSubSystem(SDL_INIT_AUDIO);
531 if(music ||
sound || bell || UI_sound) {
534 ERR_AUDIO <<
"Error initializing audio device: " << Mix_GetError();
558 Mix_FadeOutMusic(500);
559 Mix_HookMusicFinished([]() { unload_music =
true; });
569 sound_cache.remove_if([](
const sound_cache_chunk&
c) {
584 sound_cache.remove_if([](
const sound_cache_chunk&
c) {
595 sound_cache.remove_if([](
const sound_cache_chunk&
c) {
604 current_track = std::make_shared<music_track>(file);
605 current_track->set_play_once(
true);
606 current_track_index = current_track_list.size();
612 current_track_list.clear();
621 music_start_time = 1;
622 want_new_music =
true;
624 fadingout_time = previous_track !=
nullptr ? previous_track->ms_after() : 0;
630 if(
i >= current_track_list.size()) {
633 current_track_index =
i;
634 current_track = current_track_list[
i];
641 music_start_time = 0;
642 want_new_music =
true;
649 const std::string& filename = localized.empty() ? current_track->file_path() : localized;
651 auto itor = music_cache.find(filename);
652 if(itor == music_cache.end()) {
653 LOG_AUDIO <<
"attempting to insert track '" << filename <<
"' into cache";
657 const std::shared_ptr<Mix_Music> music(Mix_LoadMUSType_RW(rwops.release(), MUS_NONE,
true), &Mix_FreeMusic);
659 if(music ==
nullptr) {
660 ERR_AUDIO <<
"Could not load music file '" << filename <<
"': " << Mix_GetError();
664 itor = music_cache.emplace(filename, music).first;
667 LOG_AUDIO <<
"Playing track '" << filename <<
"'";
668 int fading_time = current_track->ms_before();
681 const int res = Mix_FadeInMusic(itor->second.get(), 1, fading_time);
683 ERR_AUDIO <<
"Could not play music: " << Mix_GetError() <<
" " << filename <<
" ";
686 want_new_music =
false;
696 current_track_list.clear();
697 current_track_list.emplace_back(
new music_track(
id));
699 std::shared_ptr<music_track> last_track = current_track;
700 current_track = current_track_list.back();
701 current_track_index = 0;
704 if(!last_track || !current_track || *last_track != *current_track) {
722 if(!track.
valid() && !track.
id().empty()) {
723 ERR_AUDIO <<
"cannot open track '" << track.
id() <<
"'; disabled in this playlist.";
729 current_track = std::make_shared<music_track>(track);
730 current_track_index = current_track_list.size();
737 current_track_list.clear();
744 auto iter = find_track(track);
748 if(iter == current_track_list.end()) {
749 if(
i < 0 ||
static_cast<std::size_t
>(
i) >= current_track_list.size()) {
750 current_track_list.emplace_back(
new music_track(track));
751 iter = current_track_list.end() - 1;
753 iter = current_track_list.emplace(current_track_list.begin() + 1,
new music_track(track));
754 if(current_track_index >=
static_cast<std::size_t
>(
i)) {
755 current_track_index++;
765 current_track = *iter;
766 current_track_index = iter - current_track_list.begin();
768 }
else if(!track.
append() && !allow_interrupt_current_track && current_track) {
770 current_track->set_play_once(
true);
776 if(Mix_FadingMusic() != MIX_NO_FADING) {
782 if(!music_start_time && !current_track_list.empty() && !Mix_PlayingMusic()) {
786 music_start_time =
info.ticks();
791 if(music_start_time &&
info.ticks(&music_refresh, music_refresh_rate) >= music_start_time - fadingout_time) {
792 want_new_music =
true;
796 if(Mix_PlayingMusic()) {
797 Mix_FadeOutMusic(fadingout_time);
801 unload_music =
false;
810 Mix_HookMusicFinished(
nullptr);
812 unload_music =
false;
817 :
events::sdl_handler(false)
825 if(event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) {
827 }
else if(event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) {
828 if(Mix_PlayingMusic()) {
837 played_before.clear();
841 if(current_track->play_once()) {
846 for(
auto m : current_track_list) {
847 if(*current_track == *m) {
854 if(current_track_list.empty()) {
868 for(
auto m : current_track_list) {
869 m->write(snapshot, append);
877 for(
unsigned ch = 0; ch <
channel_ids.size(); ++ch) {
885 Mix_SetDistance(ch, distance);
907 sound_cache_iterator it_bgn, it_end;
908 sound_cache_iterator it;
910 sound_cache_chunk temp_chunk(file);
911 it_bgn = sound_cache.begin();
912 it_end = sound_cache.end();
913 it = std::find(it_bgn, it_end, temp_chunk);
916 if(it->group != group) {
922 sound_cache.splice(it_bgn, sound_cache, it);
925 bool cache_full = (sound_cache.size() == max_cached_chunks);
926 while(cache_full && it != it_bgn) {
929 if(std::find(
channel_chunks.begin(), ch_end, (--it)->get_data()) == ch_end) {
930 sound_cache.erase(it);
936 LOG_AUDIO <<
"Maximum sound cache size reached and all are busy, skipping.";
940 temp_chunk.group = group;
944 if(!filename.empty()) {
946 temp_chunk.set_data(Mix_LoadWAV_RW(rwops.release(),
true));
948 ERR_AUDIO <<
"Could not load sound file '" << file <<
"'.";
952 if(temp_chunk.get_data() ==
nullptr) {
953 ERR_AUDIO <<
"Could not load sound file '" << filename <<
"': " << Mix_GetError();
957 sound_cache.push_front(temp_chunk);
960 return sound_cache.begin()->get_data();
965 unsigned int repeats = 0,
966 unsigned int distance = 0,
969 int fadein_ticks = 0)
978 int channel = Mix_GroupAvailable(group);
980 LOG_AUDIO <<
"All channels dedicated to sound group(" << group <<
") are busy, skipping.";
999 Mix_SetDistance(
channel, distance);
1003 if(loop_ticks > 0) {
1004 if(fadein_ticks > 0) {
1005 res = Mix_FadeInChannelTimed(
channel, chunk, -1, fadein_ticks, loop_ticks);
1007 res = Mix_PlayChannel(
channel, chunk, -1);
1011 Mix_ExpireChannel(
channel, loop_ticks);
1014 if(fadein_ticks > 0) {
1015 res = Mix_FadeInChannel(
channel, chunk, repeats, fadein_ticks);
1017 res = Mix_PlayChannel(
channel, chunk, repeats);
1022 ERR_AUDIO <<
"error playing sound effect: " << Mix_GetError();
1056 void play_timer(
const std::string& files,
int loop_ticks,
int fadein_ticks)
1074 return Mix_VolumeMusic(-1);
1082 if(mix_ok && vol >= 0) {
1083 if(vol > MIX_MAX_VOLUME) {
1084 vol = MIX_MAX_VOLUME;
1087 Mix_VolumeMusic(vol);
1095 return Mix_Volume(source_channel_start, -1);
1102 if(mix_ok && vol >= 0) {
1103 if(vol > MIX_MAX_VOLUME) {
1104 vol = MIX_MAX_VOLUME;
1108 for(
unsigned i = 0;
i < n_of_channels; ++
i) {
1109 if(!(
i >= UI_sound_channel_start &&
i <= UI_sound_channel_last) &&
i != bell_channel
1110 &&
i != timer_channel) {
1122 if(mix_ok && vol >= 0) {
1123 if(vol > MIX_MAX_VOLUME) {
1124 vol = MIX_MAX_VOLUME;
1127 Mix_Volume(bell_channel, vol);
1128 Mix_Volume(timer_channel, vol);
1134 if(mix_ok && vol >= 0) {
1135 if(vol > MIX_MAX_VOLUME) {
1136 vol = MIX_MAX_VOLUME;
1139 for(
unsigned i = UI_sound_channel_start;
i <= UI_sound_channel_last; ++
i) {
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
void process(events::pump_info &info)
Internal representation of music tracks.
const std::string & file_path() const
const std::string & id() const
bool operator==(const config &a, const config &b)
bool operator!=(const config &a, const config &b)
Declarations for File-IO.
std::string id
Text to match against addon_info.tags()
Standard logging facilities (interface).
Handling of system events.
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::unique_ptr< SDL_RWops, sdl_rwops_deleter > rwops_ptr
rwops_ptr make_read_RWops(const std::string &path)
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 or an empty string if the file isn't prese...
std::vector< game_tip > shuffle(const std::vector< game_tip > &tips)
Shuffles the tips.
bool stop_music_in_background()
std::size_t sound_buffer_size()
unsigned int sample_rate()
Audio output for sound and music.
void write_music_play_list(config &snapshot)
void set_bell_volume(int vol)
void play_sound(const std::string &files, channel_group group, unsigned int repeats)
void play_music_config(const config &music_node, bool allow_interrupt_current_track, int i)
void remove_track(unsigned int i)
void play_music_repeatedly(const std::string &id)
unsigned int get_num_tracks()
static void play_sound_internal(const std::string &files, channel_group group, unsigned int repeats=0, unsigned int distance=0, int id=-1, int loop_ticks=0, int fadein_ticks=0)
void play_music_once(const std::string &file)
void play_sound_positioned(const std::string &files, int id, int repeats, unsigned int distance)
void set_track(unsigned int i, const std::shared_ptr< music_track > &to)
std::vector< std::string > enumerate_drivers()
bool is_sound_playing(int id)
void play_timer(const std::string &files, int loop_ticks, int fadein_ticks)
static std::vector< Mix_Chunk * > channel_chunks
static std::vector< int > channel_ids
void reposition_sound(int id, unsigned int distance)
std::optional< unsigned int > get_current_track_index()
void commit_music_changes()
static void channel_finished_hook(int channel)
static void play_new_music()
void play_track(unsigned int i)
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()
void set_music_volume(int vol)
std::shared_ptr< music_track > get_track(unsigned int i)
std::shared_ptr< music_track > get_current_track()
static Mix_Chunk * load_chunk(const std::string &file, channel_group group)
std::string current_driver()
void set_UI_volume(int vol)
void set_sound_volume(int vol)
void play_bell(const std::string &files)
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::string::const_iterator iterator
static void decrement_chunk_usage(Mix_Chunk *mcp)
static std::shared_ptr< sound::music_track > choose_track()
static void increment_chunk_usage(Mix_Chunk *mcp)
static lg::log_domain log_audio("audio")
static bool track_ok(const std::string &id)
static std::string pick_one(const std::string &files)
static driver_status query()
static map_location::DIRECTION n