The Battle for Wesnoth  1.17.0-dev
sound.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2021
3  by David White <dave@whitevine.net>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 #include "sound.hpp"
17 #include "config.hpp"
18 #include "filesystem.hpp"
19 #include "log.hpp"
20 #include "preferences/game.hpp"
21 #include "random.hpp"
23 #include "sound_music_track.hpp"
24 
25 #include <SDL2/SDL.h> // Travis doesn't like this, although it works on my machine -> '#include <SDL2/SDL_sound.h>
26 #include <SDL2/SDL_mixer.h>
27 
28 #include <list>
29 #include <sstream>
30 #include <string>
31 
32 static lg::log_domain log_audio("audio");
33 #define DBG_AUDIO LOG_STREAM(debug, log_audio)
34 #define LOG_AUDIO LOG_STREAM(info, log_audio)
35 #define ERR_AUDIO LOG_STREAM(err, log_audio)
36 
37 #if (MIX_MAJOR_VERSION < 1) || (MIX_MAJOR_VERSION == 1) && ((MIX_MINOR_VERSION < 2) || (MIX_MINOR_VERSION == 2) && (MIX_PATCHLEVEL <= 11))
38 #error "Please upgrade to SDL mixer version >= 1.2.12, we don't support older versions anymore."
39 #endif
40 
41 namespace sound
42 {
43 // Channel-chunk mapping lets us know, if we can safely free a given chunk
44 static std::vector<Mix_Chunk*> channel_chunks;
45 
46 // Channel-id mapping for use with sound sources (to check if given source
47 // is playing on a channel for fading/panning)
48 static std::vector<int> channel_ids;
49 }
50 
51 namespace
52 {
53 bool mix_ok = false;
54 int music_start_time = 0;
55 unsigned music_refresh = 0;
56 unsigned music_refresh_rate = 20;
57 bool want_new_music = false;
58 int fadingout_time = 5000;
59 bool no_fading = false;
60 bool unload_music = false;
61 
62 // number of allocated channels,
63 const std::size_t n_of_channels = 32;
64 
65 // we need 2 channels, because we it for timer as well
66 const std::size_t bell_channel = 0;
67 const std::size_t timer_channel = 1;
68 
69 // number of channels reserved for sound sources
70 const std::size_t source_channels = 8;
71 const std::size_t source_channel_start = timer_channel + 1;
72 const std::size_t source_channel_last = source_channel_start + source_channels - 1;
73 const std::size_t UI_sound_channels = 2;
74 const std::size_t UI_sound_channel_start = source_channel_last + 1;
75 const std::size_t UI_sound_channel_last = UI_sound_channel_start + UI_sound_channels - 1;
76 const std::size_t n_reserved_channels = UI_sound_channel_last + 1; // sources, bell, timer and UI
77 
78 // Max number of sound chunks that we want to cache
79 // Keep this above number of available channels to avoid busy-looping
80 unsigned max_cached_chunks = 256;
81 
82 std::map<Mix_Chunk*, int> chunk_usage;
83 } // end anon namespace
84 
85 static void increment_chunk_usage(Mix_Chunk* mcp)
86 {
87  ++(chunk_usage[mcp]);
88 }
89 
90 static void decrement_chunk_usage(Mix_Chunk* mcp)
91 {
92  if(mcp == nullptr) {
93  return;
94  }
95 
96  std::map<Mix_Chunk*, int>::iterator this_usage = chunk_usage.find(mcp);
97  assert(this_usage != chunk_usage.end());
98  if(--(this_usage->second) == 0) {
99  Mix_FreeChunk(mcp);
100  chunk_usage.erase(this_usage);
101  }
102 }
103 
104 namespace
105 {
106 class sound_cache_chunk
107 {
108 public:
109  sound_cache_chunk(const std::string& f)
110  : group(sound::NULL_CHANNEL)
111  , file(f)
112  , data_(nullptr)
113  {
114  }
115  sound_cache_chunk(const sound_cache_chunk& scc)
116  : group(scc.group)
117  , file(scc.file)
118  , data_(scc.data_)
119  {
120  increment_chunk_usage(data_);
121  }
122 
123  ~sound_cache_chunk()
124  {
125  decrement_chunk_usage(data_);
126  }
127 
128  sound::channel_group group;
129  std::string file;
130 
131  void set_data(Mix_Chunk* d)
132  {
134  decrement_chunk_usage(data_);
135  data_ = d;
136  }
137 
138  Mix_Chunk* get_data() const
139  {
140  return data_;
141  }
142 
143  bool operator==(const sound_cache_chunk& scc) const
144  {
145  return file == scc.file;
146  }
147 
148  bool operator!=(const sound_cache_chunk& scc) const
149  {
150  return !operator==(scc);
151  }
152 
153  sound_cache_chunk& operator=(const sound_cache_chunk& scc)
154  {
155  file = scc.file;
156  group = scc.group;
157  set_data(scc.get_data());
158  return *this;
159  }
160 
161 private:
162  Mix_Chunk* data_;
163 };
164 
165 std::list<sound_cache_chunk> sound_cache;
166 typedef std::list<sound_cache_chunk>::iterator sound_cache_iterator;
167 std::map<std::string, std::shared_ptr<Mix_Music>> music_cache;
168 
169 std::vector<std::string> played_before;
170 
171 //
172 // FIXME: the first music_track may be initialized before main()
173 // is reached. Using the logging facilities may lead to a SIGSEGV
174 // because it's not guaranteed that their objects are already alive.
175 //
176 // Use the music_track default constructor to avoid trying to
177 // invoke a log object while resolving paths.
178 //
179 std::vector<std::shared_ptr<sound::music_track>> current_track_list;
180 std::shared_ptr<sound::music_track> current_track;
181 unsigned int current_track_index = 0;
182 std::shared_ptr<sound::music_track> previous_track;
183 
184 std::vector<std::shared_ptr<sound::music_track>>::const_iterator find_track(const sound::music_track& track)
185 {
186  return std::find_if(current_track_list.begin(), current_track_list.end(),
187  [&track](const std::shared_ptr<const sound::music_track>& ptr) { return *ptr == track; }
188  );
189 }
190 
191 } // end anon namespace
192 
193 namespace sound
194 {
196 {
197  sound_cache.clear();
198  music_cache.clear();
199 }
200 
201 std::optional<unsigned int> get_current_track_index()
202 {
203  if(current_track_index >= current_track_list.size()){
204  return {};
205  }
206  return current_track_index;
207 }
208 std::shared_ptr<music_track> get_current_track()
209 {
210  return current_track;
211 }
212 std::shared_ptr<music_track> get_previous_music_track()
213 {
214  return previous_track;
215 }
216 void set_previous_track(std::shared_ptr<music_track> track)
217 {
218  previous_track = track;
219 }
220 
221 unsigned int get_num_tracks()
222 {
223  return current_track_list.size();
224 }
225 
226 std::shared_ptr<music_track> get_track(unsigned int i)
227 {
228  if(i < current_track_list.size()) {
229  return current_track_list[i];
230  }
231 
232  if(i == current_track_list.size()) {
233  return current_track;
234  }
235 
236  return nullptr;
237 }
238 
239 void set_track(unsigned int i, const std::shared_ptr<music_track>& to)
240 {
241  if(i < current_track_list.size() && find_track(*to) != current_track_list.end()) {
242  current_track_list[i] = std::make_shared<music_track>(*to);
243  }
244 }
245 
246 void remove_track(unsigned int i)
247 {
248  if(i >= current_track_list.size()) {
249  return;
250  }
251 
252  if(i == current_track_index) {
253  // Let the track finish playing
254  if(current_track){
255  current_track->set_play_once(true);
256  }
257  // Set current index to the new size of the list
258  current_track_index = current_track_list.size() - 1;
259  } else if(i < current_track_index) {
260  current_track_index--;
261  }
262 
263  current_track_list.erase(current_track_list.begin() + i);
264 }
265 
266 } // end namespace sound
267 
268 static bool track_ok(const std::string& id)
269 {
270  LOG_AUDIO << "Considering " << id << "\n";
271 
272  if(!current_track) {
273  return true;
274  }
275 
276  // If they committed changes to list, we forget previous plays, but
277  // still *never* repeat same track twice if we have an option.
278  if(id == current_track->file_path()) {
279  return false;
280  }
281 
282  if(current_track_list.size() <= 3) {
283  return true;
284  }
285 
286  // Timothy Pinkham says:
287  // 1) can't be repeated without 2 other pieces have already played
288  // since A was played.
289  // 2) cannot play more than 2 times without every other piece
290  // having played at least 1 time.
291 
292  // Dammit, if our musicians keep coming up with algorithms, I'll
293  // be out of a job!
294  unsigned int num_played = 0;
295  std::set<std::string> played;
296  std::vector<std::string>::reverse_iterator i;
297 
298  for(i = played_before.rbegin(); i != played_before.rend(); ++i) {
299  if(*i == id) {
300  ++num_played;
301  if(num_played == 2) {
302  break;
303  }
304  } else {
305  played.insert(*i);
306  }
307  }
308 
309  // If we've played this twice, must have played every other track.
310  if(num_played == 2 && played.size() != current_track_list.size() - 1) {
311  LOG_AUDIO << "Played twice with only " << played.size() << " tracks between\n";
312  return false;
313  }
314 
315  // Check previous previous track not same.
316  i = played_before.rbegin();
317  if(i != played_before.rend()) {
318  ++i;
319  if(i != played_before.rend()) {
320  if(*i == id) {
321  LOG_AUDIO << "Played just before previous\n";
322  return false;
323  }
324  }
325  }
326 
327  return true;
328 }
329 
330 static std::shared_ptr<sound::music_track> choose_track()
331 {
332  assert(!current_track_list.empty());
333 
334  if(current_track_index >= current_track_list.size()) {
335  current_track_index = 0;
336  }
337 
338  if(current_track_list[current_track_index]->shuffle()) {
339  unsigned int track = 0;
340 
341  if(current_track_list.size() > 1) {
342  do {
343  track = randomness::rng::default_instance().get_random_int(0, current_track_list.size()-1);
344  } while(!track_ok(current_track_list[track]->file_path()));
345  }
346 
347  current_track_index = track;
348  }
349 
350  DBG_AUDIO << "Next track will be " << current_track_list[current_track_index]->file_path() << "\n";
351  played_before.push_back(current_track_list[current_track_index]->file_path());
352  return current_track_list[current_track_index];
353 }
354 
355 static std::string pick_one(const std::string& files)
356 {
357  std::vector<std::string> ids = utils::square_parenthetical_split(files, ',', "[", "]");
358 
359  if(ids.empty()) {
360  return "";
361  }
362 
363  if(ids.size() == 1) {
364  return ids[0];
365  }
366 
367  // We avoid returning same choice twice if we can avoid it.
368  static std::map<std::string, unsigned int> prev_choices;
369  unsigned int choice;
370 
371  if(prev_choices.find(files) != prev_choices.end()) {
372  choice = randomness::rng::default_instance().get_random_int(0, ids.size()-1 - 1);
373  if(choice >= prev_choices[files]) {
374  ++choice;
375  }
376 
377  prev_choices[files] = choice;
378  } else {
379  choice = randomness::rng::default_instance().get_random_int(0, ids.size()-1);
380  prev_choices.emplace(files, choice);
381  }
382 
383  return ids[choice];
384 }
385 
386 namespace
387 {
388 struct audio_lock
389 {
390  audio_lock()
391  {
392  SDL_LockAudio();
393  }
394 
395  ~audio_lock()
396  {
397  SDL_UnlockAudio();
398  }
399 };
400 
401 } // end of anonymous namespace
402 
403 namespace sound
404 {
405 // Removes channel-chunk and channel-id mapping
407 {
408  channel_chunks[channel] = nullptr;
409  channel_ids[channel] = -1;
410 }
411 
412 std::string current_driver()
413 {
414  const char* const drvname = SDL_GetCurrentAudioDriver();
415  return drvname ? drvname : "<not initialized>";
416 }
417 
418 std::vector<std::string> enumerate_drivers()
419 {
420  std::vector<std::string> res;
421  int num_drivers = SDL_GetNumVideoDrivers();
422 
423  for(int n = 0; n < num_drivers; ++n) {
424  const char* drvname = SDL_GetAudioDriver(n);
425  res.emplace_back(drvname ? drvname : "<invalid driver>");
426  }
427 
428  return res;
429 }
430 
432 {
433  driver_status res{mix_ok, 0, 0, 0, 0};
434 
435  if(mix_ok) {
436  Mix_QuerySpec(&res.frequency, &res.format, &res.channels);
437  res.chunk_size = preferences::sound_buffer_size();
438  }
439 
440  return res;
441 }
442 
444 {
445  LOG_AUDIO << "Initializing audio...\n";
446  if(SDL_WasInit(SDL_INIT_AUDIO) == 0) {
447  if(SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
448  return false;
449  }
450  }
451 
452  if(!mix_ok) {
453  if(Mix_OpenAudio(preferences::sample_rate(), MIX_DEFAULT_FORMAT, 2, preferences::sound_buffer_size()) == -1) {
454  mix_ok = false;
455  ERR_AUDIO << "Could not initialize audio: " << Mix_GetError() << std::endl;
456  return false;
457  }
458 
459  mix_ok = true;
460  Mix_AllocateChannels(n_of_channels);
461  Mix_ReserveChannels(n_reserved_channels);
462 
463  channel_chunks.clear();
464  channel_chunks.resize(n_of_channels, nullptr);
465  channel_ids.resize(n_of_channels, -1);
466 
467  Mix_GroupChannel(bell_channel, SOUND_BELL);
468  Mix_GroupChannel(timer_channel, SOUND_TIMER);
469  Mix_GroupChannels(source_channel_start, source_channel_last, SOUND_SOURCES);
470  Mix_GroupChannels(UI_sound_channel_start, UI_sound_channel_last, SOUND_UI);
471  Mix_GroupChannels(n_reserved_channels, n_of_channels - 1, SOUND_FX);
472 
477 
478  Mix_ChannelFinished(channel_finished_hook);
479 
480  LOG_AUDIO << "Audio initialized.\n";
481 
482  DBG_AUDIO << "Channel layout: " << n_of_channels << " channels (" << n_reserved_channels << " reserved)\n"
483  << " " << bell_channel << " - bell\n"
484  << " " << timer_channel << " - timer\n"
485  << " " << source_channel_start << ".." << source_channel_last << " - sound sources\n"
486  << " " << UI_sound_channel_start << ".." << UI_sound_channel_last << " - UI\n"
487  << " " << UI_sound_channel_last + 1 << ".." << n_of_channels - 1 << " - sound effects\n";
488 
489  play_music();
490  }
491 
492  return true;
493 }
494 
496 {
497  int frequency, channels;
498  uint16_t format;
499 
500  if(mix_ok) {
501  stop_bell();
502  stop_UI_sound();
503  stop_sound();
504  sound_cache.clear();
505  stop_music();
506  mix_ok = false;
507 
508  int numtimesopened = Mix_QuerySpec(&frequency, &format, &channels);
509  if(numtimesopened == 0) {
510  ERR_AUDIO << "Error closing audio device: " << Mix_GetError() << std::endl;
511  }
512 
513  while(numtimesopened) {
514  Mix_CloseAudio();
515  --numtimesopened;
516  }
517  }
518 
519  if(SDL_WasInit(SDL_INIT_AUDIO) != 0) {
520  SDL_QuitSubSystem(SDL_INIT_AUDIO);
521  }
522 
523  LOG_AUDIO << "Audio device released.\n";
524 }
525 
527 {
528  bool music = preferences::music_on();
529  bool sound = preferences::sound_on();
530  bool UI_sound = preferences::UI_sound_on();
531  bool bell = preferences::turn_bell();
532 
533  if(music || sound || bell || UI_sound) {
535  if(!sound::init_sound()) {
536  ERR_AUDIO << "Error initializing audio device: " << Mix_GetError() << std::endl;
537  }
538 
539  if(!music) {
541  }
542 
543  if(!sound) {
545  }
546 
547  if(!UI_sound) {
549  }
550 
551  if(!bell) {
553  }
554  }
555 }
556 
558 {
559  if(mix_ok) {
560  Mix_FadeOutMusic(500);
561  Mix_HookMusicFinished([]() { unload_music = true; });
562  }
563 }
564 
566 {
567  if(mix_ok) {
568  Mix_HaltGroup(SOUND_SOURCES);
569  Mix_HaltGroup(SOUND_FX);
570 
571  sound_cache.remove_if([](const sound_cache_chunk& c) {
572  return c.group == SOUND_SOURCES || c.group == SOUND_FX;
573  });
574  }
575 }
576 
577 /*
578  * For the purpose of channel manipulation, we treat turn timer the same as bell
579  */
580 void stop_bell()
581 {
582  if(mix_ok) {
583  Mix_HaltGroup(SOUND_BELL);
584  Mix_HaltGroup(SOUND_TIMER);
585 
586  sound_cache.remove_if([](const sound_cache_chunk& c) {
587  return c.group == SOUND_BELL || c.group == SOUND_TIMER;
588  });
589  }
590 }
591 
593 {
594  if(mix_ok) {
595  Mix_HaltGroup(SOUND_UI);
596 
597  sound_cache.remove_if([](const sound_cache_chunk& c) {
598  return c.group == SOUND_UI;
599  });
600  }
601 }
602 
603 void play_music_once(const std::string& file)
604 {
605  set_previous_track(current_track);
606  current_track = std::make_shared<music_track>(file);
607  current_track->set_play_once(true);
608  current_track_index = current_track_list.size();
609  play_music();
610 }
611 
613 {
614  current_track_list.clear();
615 }
616 
618 {
619  if(!current_track) {
620  return;
621  }
622 
623  music_start_time = 1; // immediate (same as effect as SDL_GetTicks())
624  want_new_music = true;
625  no_fading = false;
626  fadingout_time = previous_track != nullptr ? previous_track->ms_after() : 0;
627 }
628 
629 void play_track(unsigned int i)
630 {
631  set_previous_track(current_track);
632  if(i >= current_track_list.size()) {
633  current_track = choose_track();
634  } else {
635  current_track_index = i;
636  current_track = current_track_list[i];
637  }
638  play_music();
639 }
640 
641 static void play_new_music()
642 {
643  music_start_time = 0; // reset status: no start time
644  want_new_music = true;
645 
646  if(!preferences::music_on() || !mix_ok || !current_track || !current_track->valid()) {
647  return;
648  }
649 
650  const std::string localized = filesystem::get_localized_path(current_track->file_path());
651  const std::string& filename = localized.empty() ? current_track->file_path() : localized;
652 
653  auto itor = music_cache.find(filename);
654  if(itor == music_cache.end()) {
655  LOG_AUDIO << "attempting to insert track '" << filename << "' into cache\n";
656 
658  // SDL takes ownership of rwops
659  const std::shared_ptr<Mix_Music> music(Mix_LoadMUSType_RW(rwops.release(), MUS_NONE, true), &Mix_FreeMusic);
660 
661  if(music == nullptr) {
662  ERR_AUDIO << "Could not load music file '" << filename << "': " << Mix_GetError() << "\n";
663  return;
664  }
665 
666  itor = music_cache.emplace(filename, music).first;
667  }
668 
669  LOG_AUDIO << "Playing track '" << filename << "'\n";
670  int fading_time = current_track->ms_before();
671  if(no_fading) {
672  fading_time = 0;
673  }
674 
675  const int res = Mix_FadeInMusic(itor->second.get(), 1, fading_time);
676  if(res < 0) {
677  ERR_AUDIO << "Could not play music: " << Mix_GetError() << " " << filename << " " << std::endl;
678  }
679 
680  want_new_music = false;
681 }
682 
683 void play_music_repeatedly(const std::string& id)
684 {
685  // Can happen if scenario doesn't specify.
686  if(id.empty()) {
687  return;
688  }
689 
690  current_track_list.clear();
691  current_track_list.emplace_back(new music_track(id));
692 
693  std::shared_ptr<music_track> last_track = current_track;
694  current_track = current_track_list.back();
695  current_track_index = 0;
696 
697  // If we're already playing it, don't interrupt.
698  if(!last_track || !current_track || *last_track != *current_track) {
699  play_music();
700  }
701 
702  last_track.reset();
703 }
704 
705 void play_music_config(const config& music_node, bool allow_interrupt_current_track, int i)
706 {
707  //
708  // FIXME: there is a memory leak somewhere in this function, seemingly related to the shared_ptrs
709  // stored in current_track_list.
710  //
711  // vultraz 5/8/2017
712  //
713 
714  music_track track(music_node);
715 
716  if(!track.valid() && !track.id().empty()) {
717  ERR_AUDIO << "cannot open track '" << track.id() << "'; disabled in this playlist." << std::endl;
718  }
719 
720  // If they say play once, we don't alter playlist.
721  if(track.play_once()) {
722  set_previous_track(current_track);
723  current_track = std::make_shared<music_track>(track);
724  current_track_index = current_track_list.size();
725  play_music();
726  return;
727  }
728 
729  // Clear play list unless they specify append.
730  if(!track.append()) {
731  current_track_list.clear();
732  }
733 
734  if(!track.valid()) {
735  return;
736  }
737 
738  auto iter = find_track(track);
739  // Avoid 2 tracks with the same name, since that can cause an infinite loop
740  // in choose_track(), 2 tracks with the same name will always return the
741  // current track and track_ok() doesn't allow that.
742  if(iter == current_track_list.end()) {
743  if(i < 0 || static_cast<std::size_t>(i) >= current_track_list.size()) {
744  current_track_list.emplace_back(new music_track(track));
745  iter = current_track_list.end() - 1;
746  } else {
747  iter = current_track_list.emplace(current_track_list.begin() + 1, new music_track(track));
748  if(current_track_index >= static_cast<std::size_t>(i)) {
749  current_track_index++;
750  }
751  }
752  } else {
753  ERR_AUDIO << "tried to add duplicate track '" << track.file_path() << "'" << std::endl;
754  }
755 
756  // They can tell us to start playing this list immediately.
757  if(track.immediate()) {
758  set_previous_track(current_track);
759  current_track = *iter;
760  current_track_index = iter - current_track_list.begin();
761  play_music();
762  } else if(!track.append() && !allow_interrupt_current_track && current_track) {
763  // Make sure the current track will finish first
764  current_track->set_play_once(true);
765  }
766 }
767 
769 {
770  if(preferences::music_on()) {
771  if(!music_start_time && !current_track_list.empty() && !Mix_PlayingMusic()) {
772  // Pick next track, add ending time to its start time.
773  set_previous_track(current_track);
774  current_track = choose_track();
775  music_start_time = info.ticks();
776  no_fading = true;
777  fadingout_time = 0;
778  }
779 
780  if(music_start_time && info.ticks(&music_refresh, music_refresh_rate) >= music_start_time - fadingout_time) {
781  want_new_music = true;
782  }
783 
784  if(want_new_music) {
785  if(Mix_PlayingMusic()) {
786  Mix_FadeOutMusic(fadingout_time);
787  }
788 
789  unload_music = false;
790  play_new_music();
791  }
792  }
793 
794  if(unload_music) {
795  // The custom shared_ptr deleter (Mix_FreeMusic) will handle the freeing of each track.
796  music_cache.clear();
797 
798  Mix_HookMusicFinished(nullptr);
799 
800  unload_music = false;
801  }
802 }
803 
805  : events::sdl_handler(false)
806 {
807  join_global();
808 }
809 
810 void music_muter::handle_window_event(const SDL_Event& event)
811 {
813  if(event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) {
814  Mix_ResumeMusic();
815  } else if(event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) {
816  if(Mix_PlayingMusic()) {
817  Mix_PauseMusic();
818  }
819  }
820  }
821 }
822 
824 {
825  played_before.clear();
826 
827  // Play-once is OK if still playing.
828  if(current_track) {
829  if(current_track->play_once()) {
830  return;
831  }
832 
833  // If current track no longer on playlist, change it.
834  for(auto m : current_track_list) {
835  if(*current_track == *m) {
836  return;
837  }
838  }
839  }
840 
841  // Victory empties playlist: if next scenario doesn't specify one...
842  if(current_track_list.empty()) {
843  return;
844  }
845 
846  // FIXME: we don't pause ms_before on this first track. Should we?
847  set_previous_track(current_track);
848  current_track = choose_track();
849  play_music();
850 }
851 
853 {
854  // First entry clears playlist, others append to it.
855  bool append = false;
856  for(auto m : current_track_list) {
857  m->write(snapshot, append);
858  append = true;
859  }
860 }
861 
862 void reposition_sound(int id, unsigned int distance)
863 {
864  audio_lock lock;
865  for(unsigned ch = 0; ch < channel_ids.size(); ++ch) {
866  if(channel_ids[ch] != id) {
867  continue;
868  }
869 
870  if(distance >= DISTANCE_SILENT) {
871  Mix_HaltChannel(ch);
872  } else {
873  Mix_SetDistance(ch, distance);
874  }
875  }
876 }
877 
878 bool is_sound_playing(int id)
879 {
880  audio_lock lock;
881  return std::find(channel_ids.begin(), channel_ids.end(), id) != channel_ids.end();
882 }
883 
884 void stop_sound(int id)
885 {
887 }
888 
890 {
891 };
892 
893 static Mix_Chunk* load_chunk(const std::string& file, channel_group group)
894 {
895  sound_cache_iterator it_bgn, it_end;
896  sound_cache_iterator it;
897 
898  sound_cache_chunk temp_chunk(file); // search the sound cache on this key
899  it_bgn = sound_cache.begin();
900  it_end = sound_cache.end();
901  it = std::find(it_bgn, it_end, temp_chunk);
902 
903  if(it != it_end) {
904  if(it->group != group) {
905  // cached item has been used in multiple sound groups
906  it->group = NULL_CHANNEL;
907  }
908 
909  // splice the most recently used chunk to the front of the cache
910  sound_cache.splice(it_bgn, sound_cache, it);
911  } else {
912  // remove the least recently used chunk from cache if it's full
913  bool cache_full = (sound_cache.size() == max_cached_chunks);
914  while(cache_full && it != it_bgn) {
915  // make sure this chunk is not being played before freeing it
917  if(std::find(channel_chunks.begin(), ch_end, (--it)->get_data()) == ch_end) {
918  sound_cache.erase(it);
919  cache_full = false;
920  }
921  }
922 
923  if(cache_full) {
924  LOG_AUDIO << "Maximum sound cache size reached and all are busy, skipping.\n";
925  throw chunk_load_exception();
926  }
927 
928  temp_chunk.group = group;
929  const std::string& filename = filesystem::get_binary_file_location("sounds", file);
930  const std::string localized = filesystem::get_localized_path(filename);
931 
932  if(!filename.empty()) {
933  filesystem::rwops_ptr rwops = filesystem::make_read_RWops(localized.empty() ? filename : localized);
934  temp_chunk.set_data(Mix_LoadWAV_RW(rwops.release(), true)); // SDL takes ownership of rwops
935  } else {
936  ERR_AUDIO << "Could not load sound file '" << file << "'." << std::endl;
937  throw chunk_load_exception();
938  }
939 
940  if(temp_chunk.get_data() == nullptr) {
941  ERR_AUDIO << "Could not load sound file '" << filename << "': " << Mix_GetError() << "\n";
942  throw chunk_load_exception();
943  }
944 
945  sound_cache.push_front(temp_chunk);
946  }
947 
948  return sound_cache.begin()->get_data();
949 }
950 
951 static void play_sound_internal(const std::string& files,
952  channel_group group,
953  unsigned int repeats = 0,
954  unsigned int distance = 0,
955  int id = -1,
956  int loop_ticks = 0,
957  int fadein_ticks = 0)
958 {
959  if(files.empty() || distance >= DISTANCE_SILENT || !mix_ok) {
960  return;
961  }
962 
963  audio_lock lock;
964 
965  // find a free channel in the desired group
966  int channel = Mix_GroupAvailable(group);
967  if(channel == -1) {
968  LOG_AUDIO << "All channels dedicated to sound group(" << group << ") are busy, skipping.\n";
969  return;
970  }
971 
972  Mix_Chunk* chunk;
973  std::string file = pick_one(files);
974 
975  try {
976  chunk = load_chunk(file, group);
977  assert(chunk);
978  } catch(const chunk_load_exception&) {
979  return;
980  }
981 
982  /*
983  * This check prevents SDL_Mixer from blowing up on Windows when UI sound is played
984  * in response to toggling the checkbox which disables sound.
985  */
986  if(group != SOUND_UI) {
987  Mix_SetDistance(channel, distance);
988  }
989 
990  int res;
991  if(loop_ticks > 0) {
992  if(fadein_ticks > 0) {
993  res = Mix_FadeInChannelTimed(channel, chunk, -1, fadein_ticks, loop_ticks);
994  } else {
995  res = Mix_PlayChannel(channel, chunk, -1);
996  }
997 
998  if(res >= 0) {
999  Mix_ExpireChannel(channel, loop_ticks);
1000  }
1001  } else {
1002  if(fadein_ticks > 0) {
1003  res = Mix_FadeInChannel(channel, chunk, repeats, fadein_ticks);
1004  } else {
1005  res = Mix_PlayChannel(channel, chunk, repeats);
1006  }
1007  }
1008 
1009  if(res < 0) {
1010  ERR_AUDIO << "error playing sound effect: " << Mix_GetError() << std::endl;
1011  // still keep it in the sound cache, in case we want to try again later
1012  return;
1013  }
1014 
1015  channel_ids[channel] = id;
1016 
1017  // reserve the channel's chunk from being freed, since it is playing
1018  channel_chunks[res] = chunk;
1019 }
1020 
1021 void play_sound(const std::string& files, channel_group group, unsigned int repeats)
1022 {
1023  if(preferences::sound_on()) {
1024  play_sound_internal(files, group, repeats);
1025  }
1026 }
1027 
1028 void play_sound_positioned(const std::string& files, int id, int repeats, unsigned int distance)
1029 {
1030  if(preferences::sound_on()) {
1031  play_sound_internal(files, SOUND_SOURCES, repeats, distance, id);
1032  }
1033 }
1034 
1035 // Play bell with separate volume setting
1036 void play_bell(const std::string& files)
1037 {
1038  if(preferences::turn_bell()) {
1040  }
1041 }
1042 
1043 // Play timer with separate volume setting
1044 void play_timer(const std::string& files, int loop_ticks, int fadein_ticks)
1045 {
1046  if(preferences::sound_on()) {
1047  play_sound_internal(files, SOUND_TIMER, 0, 0, -1, loop_ticks, fadein_ticks);
1048  }
1049 }
1050 
1051 // Play UI sounds on separate volume than soundfx
1052 void play_UI_sound(const std::string& files)
1053 {
1054  if(preferences::UI_sound_on()) {
1055  play_sound_internal(files, SOUND_UI);
1056  }
1057 }
1058 
1060 {
1061  if(mix_ok) {
1062  return Mix_VolumeMusic(-1);
1063  }
1064 
1065  return 0;
1066 }
1067 
1068 void set_music_volume(int vol)
1069 {
1070  if(mix_ok && vol >= 0) {
1071  if(vol > MIX_MAX_VOLUME) {
1072  vol = MIX_MAX_VOLUME;
1073  }
1074 
1075  Mix_VolumeMusic(vol);
1076  }
1077 }
1078 
1080 {
1081  if(mix_ok) {
1082  // Since set_sound_volume sets all main channels to the same, just return the volume of any main channel
1083  return Mix_Volume(source_channel_start, -1);
1084  }
1085  return 0;
1086 }
1087 
1088 void set_sound_volume(int vol)
1089 {
1090  if(mix_ok && vol >= 0) {
1091  if(vol > MIX_MAX_VOLUME) {
1092  vol = MIX_MAX_VOLUME;
1093  }
1094 
1095  // Bell, timer and UI have separate channels which we can't set up from this
1096  for(unsigned i = 0; i < n_of_channels; ++i) {
1097  if(!(i >= UI_sound_channel_start && i <= UI_sound_channel_last) && i != bell_channel
1098  && i != timer_channel) {
1099  Mix_Volume(i, vol);
1100  }
1101  }
1102  }
1103 }
1104 
1105 /*
1106  * For the purpose of volume setting, we treat turn timer the same as bell
1107  */
1108 void set_bell_volume(int vol)
1109 {
1110  if(mix_ok && vol >= 0) {
1111  if(vol > MIX_MAX_VOLUME) {
1112  vol = MIX_MAX_VOLUME;
1113  }
1114 
1115  Mix_Volume(bell_channel, vol);
1116  Mix_Volume(timer_channel, vol);
1117  }
1118 }
1119 
1120 void set_UI_volume(int vol)
1121 {
1122  if(mix_ok && vol >= 0) {
1123  if(vol > MIX_MAX_VOLUME) {
1124  vol = MIX_MAX_VOLUME;
1125  }
1126 
1127  for(unsigned i = UI_sound_channel_start; i <= UI_sound_channel_last; ++i) {
1128  Mix_Volume(i, vol);
1129  }
1130  }
1131 }
1132 
1133 } // end namespace sound
void empty_playlist()
Definition: sound.cpp:612
void close_sound()
Definition: sound.cpp:495
unsigned int get_num_tracks()
Definition: sound.cpp:221
int bell_volume()
Definition: general.cpp:605
bool turn_bell()
Definition: general.cpp:645
const std::string & id() const
bool is_sound_playing(int id)
Definition: sound.cpp:878
void play_sound_positioned(const std::string &files, int id, int repeats, unsigned int distance)
Definition: sound.cpp:1028
void stop_music()
Definition: sound.cpp:557
channel_group
Definition: sound.hpp:28
std::string current_driver()
Definition: sound.cpp:412
std::shared_ptr< music_track > get_current_track()
Definition: sound.cpp:208
logger & info()
Definition: log.cpp:89
void set_UI_volume(int vol)
Definition: sound.cpp:1120
int ticks(unsigned *refresh_counter=nullptr, unsigned refresh_rate=1)
Definition: events.cpp:833
rwops_ptr make_read_RWops(const std::string &path)
static void play_new_music()
Definition: sound.cpp:641
void remove_track(unsigned int i)
Definition: sound.cpp:246
std::shared_ptr< music_track > get_previous_music_track()
Definition: sound.cpp:212
void stop_sound()
Definition: sound.cpp:565
unsigned int sample_rate()
Definition: general.cpp:923
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&#39;t prese...
Audio output for sound and music.
Definition: sound.cpp:41
void play_music_once(const std::string &file)
Definition: sound.cpp:603
#define d
static lg::log_domain log_audio("audio")
bool operator!=(const config &a, const config &b)
Definition: config.hpp:57
void write_music_play_list(config &snapshot)
Definition: sound.cpp:852
Definitions for the interface to Wesnoth Markup Language (WML).
bool sound_on()
Definition: general.cpp:698
void reposition_sound(int id, unsigned int distance)
Definition: sound.cpp:862
void play_sound(const std::string &files, channel_group group, unsigned int repeats)
Definition: sound.cpp:1021
bool init_sound()
Definition: sound.cpp:443
static bool track_ok(const std::string &id)
Definition: sound.cpp:268
#define DBG_AUDIO
Definition: sound.cpp:33
void reset_sound()
Definition: sound.cpp:526
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)
Definition: sound.cpp:951
#define LOG_AUDIO
Definition: sound.cpp:34
void set_bell_volume(int vol)
Definition: sound.cpp:1108
static void channel_finished_hook(int channel)
Definition: sound.cpp:406
static std::string pick_one(const std::string &files)
Definition: sound.cpp:355
void stop_UI_sound()
Definition: sound.cpp:592
void set_previous_track(std::shared_ptr< music_track > track)
Definition: sound.cpp:216
void play_music()
Definition: sound.cpp:617
static Mix_Chunk * load_chunk(const std::string &file, channel_group group)
Definition: sound.cpp:893
bool UI_sound_on()
Definition: general.cpp:669
int get_sound_volume()
Definition: sound.cpp:1079
void set_sound_volume(int vol)
Definition: sound.cpp:1088
void set_music_volume(int vol)
Definition: sound.cpp:1068
void flush_cache()
Definition: sound.cpp:195
std::string id
Text to match against addon_info.tags()
Definition: manager.cpp:215
std::size_t i
Definition: function.cpp:967
static std::vector< Mix_Chunk * > channel_chunks
Definition: sound.cpp:44
void process(events::pump_info &info)
Definition: sound.cpp:768
bool stop_music_in_background()
Definition: general.cpp:747
bool operator==(const config &a, const config &b)
Definition: config.cpp:1475
Internal representation of music tracks.
bool music_on()
Definition: general.cpp:721
#define ERR_AUDIO
Definition: sound.cpp:35
Declarations for File-IO.
void stop_bell()
Definition: sound.cpp:580
std::unique_ptr< SDL_RWops, void(*)(SDL_RWops *)> rwops_ptr
Definition: filesystem.hpp:42
int get_random_int(int min, int max)
This helper method provides a random int from the underlying generator, using results of next_random...
Definition: random.hpp:52
std::string get_localized_path(const std::string &file, const std::string &suff)
Returns the localized version of the given filename, if it exists.
int get_music_volume()
Definition: sound.cpp:1059
static void increment_chunk_usage(Mix_Chunk *mcp)
Definition: sound.cpp:85
std::size_t sound_buffer_size()
Definition: general.cpp:545
Handling of system events.
Definition: manager.hpp:43
const std::string & file_path() const
void play_bell(const std::string &files)
Definition: sound.cpp:1036
int sound_volume()
Definition: general.cpp:590
static std::vector< int > channel_ids
Definition: sound.cpp:48
#define f
void play_timer(const std::string &files, int loop_ticks, int fadein_ticks)
Definition: sound.cpp:1044
void play_music_config(const config &music_node, bool allow_interrupt_current_track, int i)
Definition: sound.cpp:705
std::optional< unsigned int > get_current_track_index()
Definition: sound.cpp:201
void play_music_repeatedly(const std::string &id)
Definition: sound.cpp:683
#define DISTANCE_SILENT
Definition: sound.hpp:76
void play_UI_sound(const std::string &files)
Definition: sound.cpp:1052
Standard logging facilities (interface).
void handle_window_event(const SDL_Event &event) override
Definition: sound.cpp:810
int UI_volume()
Definition: general.cpp:620
std::vector< game_tip > shuffle(const std::vector< game_tip > &tips)
Shuffles the tips.
Definition: tips.cpp:47
void commit_music_changes()
Definition: sound.cpp:823
void set_track(unsigned int i, const std::shared_ptr< music_track > &to)
Definition: sound.cpp:239
static driver_status query()
Definition: sound.cpp:431
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:61
mock_char c
std::vector< std::string > enumerate_drivers()
Definition: sound.cpp:418
void play_track(unsigned int i)
Definition: sound.cpp:629
static map_location::DIRECTION n
static std::shared_ptr< sound::music_track > choose_track()
Definition: sound.cpp:330
static void decrement_chunk_usage(Mix_Chunk *mcp)
Definition: sound.cpp:90
static rng & default_instance()
Definition: random.cpp:74
virtual void join_global()
Definition: events.cpp:363
std::string::const_iterator iterator
Definition: tokenizer.hpp:25
std::shared_ptr< music_track > get_track(unsigned int i)
Definition: sound.cpp:226
int music_volume()
Definition: general.cpp:575
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.
channel
Definition: utils.hpp:146