CMusicHandler.cpp 8.8 KB

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