CMusicHandler.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * CMusicHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CMusicHandler.h"
  12. #include "../CGameInfo.h"
  13. #include "../eventsSDL/InputHandler.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../renderSDL/SDLRWwrapper.h"
  16. #include "../../lib/CRandomGenerator.h"
  17. #include "../../lib/TerrainHandler.h"
  18. #include "../../lib/filesystem/Filesystem.h"
  19. #include <SDL_mixer.h>
  20. void CMusicHandler::onVolumeChange(const JsonNode & volumeNode)
  21. {
  22. setVolume(volumeNode.Integer());
  23. }
  24. CMusicHandler::CMusicHandler():
  25. listener(settings.listen["general"]["music"])
  26. {
  27. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  28. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourcePath & id) -> bool
  29. {
  30. if(id.getType() != EResType::SOUND)
  31. return false;
  32. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  33. return false;
  34. logGlobal->trace("Found music file %s", id.getName());
  35. return true;
  36. });
  37. for(const ResourcePath & file : mp3files)
  38. {
  39. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  40. addEntryToSet("battle", AudioPath::fromResource(file));
  41. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  42. addEntryToSet("enemy-turn", AudioPath::fromResource(file));
  43. }
  44. if (isInitialized())
  45. {
  46. Mix_HookMusicFinished([]()
  47. {
  48. CCS->musich->musicFinishedCallback();
  49. });
  50. }
  51. }
  52. void CMusicHandler::loadTerrainMusicThemes()
  53. {
  54. for(const auto & terrain : CGI->terrainTypeHandler->objects)
  55. {
  56. addEntryToSet("terrain_" + terrain->getJsonKey(), terrain->musicFilename);
  57. }
  58. }
  59. void CMusicHandler::addEntryToSet(const std::string & set, const AudioPath & musicURI)
  60. {
  61. musicsSet[set].push_back(musicURI);
  62. }
  63. CMusicHandler::~CMusicHandler()
  64. {
  65. if(isInitialized())
  66. {
  67. boost::mutex::scoped_lock guard(mutex);
  68. Mix_HookMusicFinished(nullptr);
  69. current->stop();
  70. current.reset();
  71. next.reset();
  72. }
  73. }
  74. void CMusicHandler::playMusic(const AudioPath & musicURI, bool loop, bool fromStart)
  75. {
  76. boost::mutex::scoped_lock guard(mutex);
  77. if(current && current->isPlaying() && current->isTrack(musicURI))
  78. return;
  79. queueNext(this, "", musicURI, loop, fromStart);
  80. }
  81. void CMusicHandler::playMusicFromSet(const std::string & musicSet, const std::string & entryID, bool loop, bool fromStart)
  82. {
  83. playMusicFromSet(musicSet + "_" + entryID, loop, fromStart);
  84. }
  85. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop, bool fromStart)
  86. {
  87. boost::mutex::scoped_lock guard(mutex);
  88. auto selectedSet = musicsSet.find(whichSet);
  89. if(selectedSet == musicsSet.end())
  90. {
  91. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  92. return;
  93. }
  94. if(current && current->isPlaying() && current->isSet(whichSet))
  95. return;
  96. // in this mode - play random track from set
  97. queueNext(this, whichSet, AudioPath(), loop, fromStart);
  98. }
  99. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  100. {
  101. if(!isInitialized())
  102. return;
  103. next = std::move(queued);
  104. if(current == nullptr || !current->stop(1000))
  105. {
  106. current.reset(next.release());
  107. current->play();
  108. }
  109. }
  110. void CMusicHandler::queueNext(CMusicHandler * owner, const std::string & setName, const AudioPath & musicURI, bool looped, bool fromStart)
  111. {
  112. queueNext(std::make_unique<MusicEntry>(owner, setName, musicURI, looped, fromStart));
  113. }
  114. void CMusicHandler::stopMusic(int fade_ms)
  115. {
  116. if(!isInitialized())
  117. return;
  118. boost::mutex::scoped_lock guard(mutex);
  119. if(current != nullptr)
  120. current->stop(fade_ms);
  121. next.reset();
  122. }
  123. ui32 CMusicHandler::getVolume() const
  124. {
  125. return volume;
  126. }
  127. void CMusicHandler::setVolume(ui32 percent)
  128. {
  129. volume = std::min(100u, percent);
  130. if(isInitialized())
  131. Mix_VolumeMusic((MIX_MAX_VOLUME * volume) / 100);
  132. }
  133. void CMusicHandler::musicFinishedCallback()
  134. {
  135. // call music restart in separate thread to avoid deadlock in some cases
  136. // It is possible for:
  137. // 1) SDL thread to call this method on end of playback
  138. // 2) VCMI code to call queueNext() method to queue new file
  139. // this leads to:
  140. // 1) SDL thread waiting to acquire music lock in this method (while keeping internal SDL mutex locked)
  141. // 2) VCMI thread waiting to acquire internal SDL mutex (while keeping music mutex locked)
  142. GH.dispatchMainThread(
  143. [this]()
  144. {
  145. boost::unique_lock lockGuard(mutex);
  146. if(current != nullptr)
  147. {
  148. // if music is looped, play it again
  149. if(current->play())
  150. return;
  151. else
  152. current.reset();
  153. }
  154. if(current == nullptr && next != nullptr)
  155. {
  156. current.reset(next.release());
  157. current->play();
  158. }
  159. }
  160. );
  161. }
  162. MusicEntry::MusicEntry(CMusicHandler * owner, std::string setName, const AudioPath & musicURI, bool looped, bool fromStart)
  163. : owner(owner)
  164. , music(nullptr)
  165. , setName(std::move(setName))
  166. , startTime(static_cast<uint32_t>(-1))
  167. , startPosition(0)
  168. , loop(looped ? -1 : 1)
  169. , fromStart(fromStart)
  170. , playing(false)
  171. {
  172. if(!musicURI.empty())
  173. load(musicURI);
  174. }
  175. MusicEntry::~MusicEntry()
  176. {
  177. if(playing && loop > 0)
  178. {
  179. assert(0);
  180. logGlobal->error("Attempt to delete music while playing!");
  181. Mix_HaltMusic();
  182. }
  183. if(loop == 0 && Mix_FadingMusic() != MIX_NO_FADING)
  184. {
  185. assert(0);
  186. logGlobal->error("Attempt to delete music while fading out!");
  187. Mix_HaltMusic();
  188. }
  189. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  190. if(music)
  191. Mix_FreeMusic(music);
  192. }
  193. void MusicEntry::load(const AudioPath & musicURI)
  194. {
  195. if(music)
  196. {
  197. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  198. Mix_FreeMusic(music);
  199. music = nullptr;
  200. }
  201. if(CResourceHandler::get()->existsResource(musicURI))
  202. currentName = musicURI;
  203. else
  204. currentName = musicURI.addPrefix("MUSIC/");
  205. music = nullptr;
  206. logGlobal->trace("Loading music file %s", currentName.getOriginalName());
  207. try
  208. {
  209. auto * musicFile = MakeSDLRWops(CResourceHandler::get()->load(currentName));
  210. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  211. }
  212. catch(std::exception & e)
  213. {
  214. logGlobal->error("Failed to load music. setName=%s\tmusicURI=%s", setName, currentName.getOriginalName());
  215. logGlobal->error("Exception: %s", e.what());
  216. }
  217. if(!music)
  218. {
  219. logGlobal->warn("Warning: Cannot open %s: %s", currentName.getOriginalName(), Mix_GetError());
  220. return;
  221. }
  222. }
  223. bool MusicEntry::play()
  224. {
  225. if(!(loop--) && music) //already played once - return
  226. return false;
  227. if(!setName.empty())
  228. {
  229. const auto & set = owner->musicsSet[setName];
  230. const auto & iter = RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault());
  231. load(*iter);
  232. }
  233. logGlobal->trace("Playing music file %s", currentName.getOriginalName());
  234. if(!fromStart && owner->trackPositions.count(currentName) > 0 && owner->trackPositions[currentName] > 0)
  235. {
  236. float timeToStart = owner->trackPositions[currentName];
  237. startPosition = std::round(timeToStart * 1000);
  238. // erase stored position:
  239. // if music track will be interrupted again - new position will be written in stop() method
  240. // if music track is not interrupted and will finish by timeout/end of file - it will restart from beginning as it should
  241. owner->trackPositions.erase(owner->trackPositions.find(currentName));
  242. if(Mix_FadeInMusicPos(music, 1, 1000, timeToStart) == -1)
  243. {
  244. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  245. return false;
  246. }
  247. }
  248. else
  249. {
  250. startPosition = 0;
  251. if(Mix_PlayMusic(music, 1) == -1)
  252. {
  253. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  254. return false;
  255. }
  256. }
  257. startTime = GH.input().getTicks();
  258. playing = true;
  259. return true;
  260. }
  261. bool MusicEntry::stop(int fade_ms)
  262. {
  263. if(Mix_PlayingMusic())
  264. {
  265. playing = false;
  266. loop = 0;
  267. uint32_t endTime = GH.input().getTicks();
  268. assert(startTime != uint32_t(-1));
  269. float playDuration = (endTime - startTime + startPosition) / 1000.f;
  270. owner->trackPositions[currentName] = playDuration;
  271. logGlobal->trace("Stopping music file %s at %f", currentName.getOriginalName(), playDuration);
  272. Mix_FadeOutMusic(fade_ms);
  273. return true;
  274. }
  275. return false;
  276. }
  277. bool MusicEntry::isPlaying() const
  278. {
  279. return playing;
  280. }
  281. bool MusicEntry::isSet(const std::string & set)
  282. {
  283. return !setName.empty() && set == setName;
  284. }
  285. bool MusicEntry::isTrack(const AudioPath & track)
  286. {
  287. return setName.empty() && track == currentName;
  288. }