CMusicHandler.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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/GameLibrary.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 : LIBRARY->terrainTypeHandler->objects)
  57. {
  58. for(const auto & filename : terrain->musicFilename)
  59. addEntryToSet("terrain_" + terrain->getJsonKey(), filename);
  60. }
  61. for(const auto & faction : LIBRARY->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. std::scoped_lock guard(mutex);
  78. Mix_HookMusicFinished(nullptr);
  79. current.reset();
  80. next.reset();
  81. }
  82. }
  83. void CMusicHandler::playMusic(const AudioPath & musicURI, bool loop, bool fromStart)
  84. {
  85. std::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. std::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. std::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. ENGINE->dispatchMainThread(
  152. [this]()
  153. {
  154. std::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. logGlobal->trace("Halting playback of music file %s", currentName.getOriginalName());
  195. Mix_HaltMusic();
  196. }
  197. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  198. if(music)
  199. Mix_FreeMusic(music);
  200. }
  201. void MusicEntry::load(const AudioPath & musicURI)
  202. {
  203. if(music)
  204. {
  205. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  206. Mix_FreeMusic(music);
  207. music = nullptr;
  208. }
  209. if(CResourceHandler::get()->existsResource(musicURI))
  210. currentName = musicURI;
  211. else
  212. currentName = musicURI.addPrefix("MUSIC/");
  213. music = nullptr;
  214. logGlobal->trace("Loading music file %s", currentName.getOriginalName());
  215. try
  216. {
  217. std::unique_ptr<CInputStream> stream = CResourceHandler::get()->load(currentName);
  218. if(musicURI.getName() == "BLADEFWCAMPAIGN") // handle defect MP3 file - ffprobe says: Skipping 52 bytes of junk at 0.
  219. stream->seek(52);
  220. auto * musicFile = MakeSDLRWops(std::move(stream));
  221. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  222. }
  223. catch(const std::exception & e)
  224. {
  225. logGlobal->error("Failed to load music. setName=%s\tmusicURI=%s", setName, currentName.getOriginalName());
  226. logGlobal->error("Exception: %s", e.what());
  227. }
  228. if(!music)
  229. {
  230. logGlobal->warn("Warning: Cannot open %s: %s", currentName.getOriginalName(), Mix_GetError());
  231. return;
  232. }
  233. }
  234. bool MusicEntry::play()
  235. {
  236. if(!(loop--) && music) //already played once - return
  237. return false;
  238. if(!setName.empty())
  239. {
  240. const auto & set = owner->musicsSet[setName];
  241. const auto & iter = RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault());
  242. load(*iter);
  243. }
  244. logGlobal->trace("Playing music file %s", currentName.getOriginalName());
  245. if(!fromStart && owner->trackPositions.count(currentName) > 0 && owner->trackPositions[currentName] > 0)
  246. {
  247. float timeToStart = owner->trackPositions[currentName];
  248. startPosition = std::round(timeToStart * 1000);
  249. // erase stored position:
  250. // if music track will be interrupted again - new position will be written in stop() method
  251. // if music track is not interrupted and will finish by timeout/end of file - it will restart from beginning as it should
  252. owner->trackPositions.erase(owner->trackPositions.find(currentName));
  253. if(Mix_FadeInMusicPos(music, 1, 1000, timeToStart) == -1)
  254. {
  255. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  256. return false;
  257. }
  258. }
  259. else
  260. {
  261. startPosition = 0;
  262. if(Mix_PlayMusic(music, 1) == -1)
  263. {
  264. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  265. return false;
  266. }
  267. }
  268. startTime = ENGINE->input().getTicks();
  269. playing = true;
  270. return true;
  271. }
  272. bool MusicEntry::stop(int fade_ms)
  273. {
  274. if(Mix_PlayingMusic())
  275. {
  276. playing = false;
  277. loop = 0;
  278. uint32_t endTime = ENGINE->input().getTicks();
  279. assert(startTime != uint32_t(-1));
  280. float playDuration = (endTime - startTime + startPosition) / 1000.f;
  281. owner->trackPositions[currentName] = playDuration;
  282. logGlobal->trace("Stopping music file %s at %f", currentName.getOriginalName(), playDuration);
  283. Mix_FadeOutMusic(fade_ms);
  284. return true;
  285. }
  286. return false;
  287. }
  288. bool MusicEntry::isPlaying() const
  289. {
  290. return playing;
  291. }
  292. bool MusicEntry::isSet(const std::string & set)
  293. {
  294. return !setName.empty() && set == setName;
  295. }
  296. bool MusicEntry::isTrack(const AudioPath & track)
  297. {
  298. return setName.empty() && track == currentName;
  299. }