CMusicHandler.cpp 8.5 KB

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