CMusicHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 <SDL_mixer.h>
  12. #include <SDL_timer.h>
  13. #include "CMusicHandler.h"
  14. #include "CGameInfo.h"
  15. #include "renderSDL/SDLRWwrapper.h"
  16. #include "../lib/JsonNode.h"
  17. #include "../lib/GameConstants.h"
  18. #include "../lib/filesystem/Filesystem.h"
  19. #include "../lib/StringConstants.h"
  20. #include "../lib/CRandomGenerator.h"
  21. #include "../lib/VCMIDirs.h"
  22. #include "../lib/TerrainHandler.h"
  23. #define VCMI_SOUND_NAME(x)
  24. #define VCMI_SOUND_FILE(y) #y,
  25. // sounds mapped to soundBase enum
  26. static std::string sounds[] = {
  27. "", // invalid
  28. "", // todo
  29. VCMI_SOUND_LIST
  30. };
  31. #undef VCMI_SOUND_NAME
  32. #undef VCMI_SOUND_FILE
  33. void CAudioBase::init()
  34. {
  35. if (initialized)
  36. return;
  37. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  38. {
  39. logGlobal->error("Mix_OpenAudio error: %s", Mix_GetError());
  40. return;
  41. }
  42. initialized = true;
  43. }
  44. void CAudioBase::release()
  45. {
  46. if(!(CCS->soundh->initialized && CCS->musich->initialized))
  47. Mix_CloseAudio();
  48. initialized = false;
  49. }
  50. void CAudioBase::setVolume(ui32 percent)
  51. {
  52. if (percent > 100)
  53. percent = 100;
  54. volume = percent;
  55. }
  56. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  57. {
  58. setVolume((ui32)volumeNode.Float());
  59. }
  60. CSoundHandler::CSoundHandler():
  61. listener(settings.listen["general"]["sound"]),
  62. ambientConfig(JsonNode(ResourceID("config/ambientSounds.json")))
  63. {
  64. listener(std::bind(&CSoundHandler::onVolumeChange, this, _1));
  65. battleIntroSounds =
  66. {
  67. soundBase::battle00, soundBase::battle01,
  68. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  69. soundBase::battle05, soundBase::battle06, soundBase::battle07
  70. };
  71. }
  72. void CSoundHandler::init()
  73. {
  74. CAudioBase::init();
  75. if(ambientConfig["allocateChannels"].isNumber())
  76. Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
  77. if (initialized)
  78. {
  79. Mix_ChannelFinished([](int channel)
  80. {
  81. CCS->soundh->soundFinishedCallback(channel);
  82. });
  83. }
  84. }
  85. void CSoundHandler::release()
  86. {
  87. if (initialized)
  88. {
  89. Mix_HaltChannel(-1);
  90. for (auto &chunk : soundChunks)
  91. {
  92. if (chunk.second.first)
  93. Mix_FreeChunk(chunk.second.first);
  94. }
  95. }
  96. CAudioBase::release();
  97. }
  98. // Allocate an SDL chunk and cache it.
  99. Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound, bool cache)
  100. {
  101. try
  102. {
  103. if (cache && soundChunks.find(sound) != soundChunks.end())
  104. return soundChunks[sound].first;
  105. auto data = CResourceHandler::get()->load(ResourceID(std::string("SOUNDS/") + sound, EResType::SOUND))->readAll();
  106. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  107. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  108. if (cache)
  109. soundChunks.insert(std::pair<std::string, CachedChunk>(sound, std::make_pair (chunk, std::move (data.first))));
  110. return chunk;
  111. }
  112. catch(std::exception &e)
  113. {
  114. logGlobal->warn("Cannot get sound %s chunk: %s", sound, e.what());
  115. return nullptr;
  116. }
  117. }
  118. int CSoundHandler::ambientDistToVolume(int distance) const
  119. {
  120. if(distance >= ambientConfig["distances"].Vector().size())
  121. return 0;
  122. int volume = static_cast<int>(ambientConfig["distances"].Vector()[distance].Integer());
  123. return volume * (int)ambientConfig["volume"].Integer() * getVolume() / 10000;
  124. }
  125. void CSoundHandler::ambientStopSound(std::string soundId)
  126. {
  127. stopSound(ambientChannels[soundId]);
  128. setChannelVolume(ambientChannels[soundId], volume);
  129. }
  130. // Plays a sound, and return its channel so we can fade it out later
  131. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  132. {
  133. assert(soundID < soundBase::sound_after_last);
  134. auto sound = sounds[soundID];
  135. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound);
  136. return playSound(sound, repeats, true);
  137. }
  138. int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
  139. {
  140. if (!initialized || sound.empty())
  141. return -1;
  142. int channel;
  143. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  144. if (chunk)
  145. {
  146. channel = Mix_PlayChannel(-1, chunk, repeats);
  147. if (channel == -1)
  148. {
  149. logGlobal->error("Unable to play sound file %s , error %s", sound, Mix_GetError());
  150. if (!cache)
  151. Mix_FreeChunk(chunk);
  152. }
  153. else if (cache)
  154. callbacks[channel];
  155. else
  156. callbacks[channel] = [chunk](){ Mix_FreeChunk(chunk);};
  157. }
  158. else
  159. channel = -1;
  160. return channel;
  161. }
  162. // Helper. Randomly select a sound from an array and play it
  163. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  164. {
  165. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  166. }
  167. void CSoundHandler::stopSound(int handler)
  168. {
  169. if (initialized && handler != -1)
  170. Mix_HaltChannel(handler);
  171. }
  172. // Sets the sound volume, from 0 (mute) to 100
  173. void CSoundHandler::setVolume(ui32 percent)
  174. {
  175. CAudioBase::setVolume(percent);
  176. if (initialized)
  177. setChannelVolume(-1, volume);
  178. }
  179. // Sets the sound volume, from 0 (mute) to 100
  180. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  181. {
  182. Mix_Volume(channel, (MIX_MAX_VOLUME * percent)/100);
  183. }
  184. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  185. {
  186. std::map<int, std::function<void()> >::iterator iter;
  187. iter = callbacks.find(channel);
  188. //channel not found. It may have finished so fire callback now
  189. if(iter == callbacks.end())
  190. function();
  191. else
  192. iter->second = function;
  193. }
  194. void CSoundHandler::soundFinishedCallback(int channel)
  195. {
  196. std::map<int, std::function<void()> >::iterator iter;
  197. iter = callbacks.find(channel);
  198. if (iter == callbacks.end())
  199. return;
  200. auto callback = std::move(iter->second);
  201. callbacks.erase(iter);
  202. if (callback)
  203. callback();
  204. }
  205. int CSoundHandler::ambientGetRange() const
  206. {
  207. return static_cast<int>(ambientConfig["range"].Integer());
  208. }
  209. void CSoundHandler::ambientUpdateChannels(std::map<std::string, int> soundsArg)
  210. {
  211. boost::mutex::scoped_lock guard(mutex);
  212. std::vector<std::string> stoppedSounds;
  213. for(auto & pair : ambientChannels)
  214. {
  215. if(!vstd::contains(soundsArg, pair.first))
  216. {
  217. ambientStopSound(pair.first);
  218. stoppedSounds.push_back(pair.first);
  219. }
  220. else
  221. {
  222. int volume = ambientDistToVolume(soundsArg[pair.first]);
  223. CCS->soundh->setChannelVolume(pair.second, volume);
  224. }
  225. }
  226. for(auto soundId : stoppedSounds)
  227. ambientChannels.erase(soundId);
  228. for(auto & pair : soundsArg)
  229. {
  230. if(!vstd::contains(ambientChannels, pair.first))
  231. {
  232. int channel = CCS->soundh->playSound(pair.first, -1);
  233. int volume = ambientDistToVolume(pair.second);
  234. CCS->soundh->setChannelVolume(channel, volume);
  235. CCS->soundh->ambientChannels.insert(std::make_pair(pair.first, channel));
  236. }
  237. }
  238. }
  239. void CSoundHandler::ambientStopAllChannels()
  240. {
  241. boost::mutex::scoped_lock guard(mutex);
  242. for(auto ch : ambientChannels)
  243. {
  244. ambientStopSound(ch.first);
  245. }
  246. ambientChannels.clear();
  247. }
  248. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  249. {
  250. setVolume((ui32)volumeNode.Float());
  251. }
  252. CMusicHandler::CMusicHandler():
  253. listener(settings.listen["general"]["music"])
  254. {
  255. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  256. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourceID & id) -> bool
  257. {
  258. if(id.getType() != EResType::MUSIC)
  259. return false;
  260. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  261. return false;
  262. logGlobal->trace("Found music file %s", id.getName());
  263. return true;
  264. });
  265. for(const ResourceID & file : mp3files)
  266. {
  267. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  268. addEntryToSet("battle", file.getName());
  269. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  270. addEntryToSet("enemy-turn", file.getName());
  271. }
  272. }
  273. void CMusicHandler::loadTerrainMusicThemes()
  274. {
  275. for (const auto & terrain : CGI->terrainTypeHandler->objects)
  276. {
  277. addEntryToSet("terrain_" + terrain->getJsonKey(), "Music/" + terrain->musicFilename);
  278. }
  279. }
  280. void CMusicHandler::addEntryToSet(const std::string & set, const std::string & musicURI)
  281. {
  282. musicsSet[set].push_back(musicURI);
  283. }
  284. void CMusicHandler::init()
  285. {
  286. CAudioBase::init();
  287. if (initialized)
  288. {
  289. Mix_HookMusicFinished([]()
  290. {
  291. CCS->musich->musicFinishedCallback();
  292. });
  293. }
  294. }
  295. void CMusicHandler::release()
  296. {
  297. if (initialized)
  298. {
  299. boost::mutex::scoped_lock guard(mutex);
  300. Mix_HookMusicFinished(nullptr);
  301. current->stop();
  302. current.reset();
  303. next.reset();
  304. }
  305. CAudioBase::release();
  306. }
  307. void CMusicHandler::playMusic(const std::string & musicURI, bool loop, bool fromStart)
  308. {
  309. boost::mutex::scoped_lock guard(mutex);
  310. if (current && current->isPlaying() && current->isTrack(musicURI))
  311. return;
  312. queueNext(this, "", musicURI, loop, fromStart);
  313. }
  314. void CMusicHandler::playMusicFromSet(const std::string & musicSet, const std::string & entryID, bool loop, bool fromStart)
  315. {
  316. playMusicFromSet(musicSet + "_" + entryID, loop, fromStart);
  317. }
  318. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop, bool fromStart)
  319. {
  320. boost::mutex::scoped_lock guard(mutex);
  321. auto selectedSet = musicsSet.find(whichSet);
  322. if (selectedSet == musicsSet.end())
  323. {
  324. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  325. return;
  326. }
  327. if (current && current->isPlaying() && current->isSet(whichSet))
  328. return;
  329. // in this mode - play random track from set
  330. queueNext(this, whichSet, "", loop, fromStart);
  331. }
  332. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  333. {
  334. if (!initialized)
  335. return;
  336. next = std::move(queued);
  337. if (current.get() == nullptr || !current->stop(1000))
  338. {
  339. current.reset(next.release());
  340. current->play();
  341. }
  342. }
  343. void CMusicHandler::queueNext(CMusicHandler *owner, const std::string & setName, const std::string & musicURI, bool looped, bool fromStart)
  344. {
  345. try
  346. {
  347. queueNext(std::make_unique<MusicEntry>(owner, setName, musicURI, looped, fromStart));
  348. }
  349. catch(std::exception &e)
  350. {
  351. logGlobal->error("Failed to queue music. setName=%s\tmusicURI=%s", setName, musicURI);
  352. logGlobal->error("Exception: %s", e.what());
  353. }
  354. }
  355. void CMusicHandler::stopMusic(int fade_ms)
  356. {
  357. if (!initialized)
  358. return;
  359. boost::mutex::scoped_lock guard(mutex);
  360. if (current.get() != nullptr)
  361. current->stop(fade_ms);
  362. next.reset();
  363. }
  364. void CMusicHandler::setVolume(ui32 percent)
  365. {
  366. CAudioBase::setVolume(percent);
  367. if (initialized)
  368. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  369. }
  370. void CMusicHandler::musicFinishedCallback()
  371. {
  372. // boost::mutex::scoped_lock guard(mutex);
  373. // FIXME: WORKAROUND FOR A POTENTIAL DEADLOCK
  374. // It is possible for:
  375. // 1) SDL thread to call this method on end of playback
  376. // 2) VCMI code to call queueNext() method to queue new file
  377. // this leads to:
  378. // 1) SDL thread waiting to acquire music lock in this method (while keeping internal SDL mutex locked)
  379. // 2) VCMI thread waiting to acquire internal SDL mutex (while keeping music mutex locked)
  380. // Because of that (and lack of clear way to fix that)
  381. // We will try to acquire lock here and if failed - do nothing
  382. // This may break music playback till next song is enqued but won't deadlock the game
  383. if (!mutex.try_lock())
  384. {
  385. logGlobal->error("Failed to acquire mutex! Unable to restart music!");
  386. return;
  387. }
  388. if (current.get() != nullptr)
  389. {
  390. // if music is looped, play it again
  391. if (current->play())
  392. {
  393. mutex.unlock();
  394. return;
  395. }
  396. else
  397. {
  398. current.reset();
  399. }
  400. }
  401. if (current.get() == nullptr && next.get() != nullptr)
  402. {
  403. current.reset(next.release());
  404. current->play();
  405. }
  406. mutex.unlock();
  407. }
  408. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped, bool fromStart):
  409. owner(owner),
  410. music(nullptr),
  411. playing(false),
  412. startTime(uint32_t(-1)),
  413. startPosition(0),
  414. loop(looped ? -1 : 1),
  415. fromStart(fromStart),
  416. setName(std::move(setName))
  417. {
  418. if (!musicURI.empty())
  419. load(std::move(musicURI));
  420. }
  421. MusicEntry::~MusicEntry()
  422. {
  423. if (playing && loop > 0)
  424. {
  425. assert(0);
  426. logGlobal->error("Attempt to delete music while playing!");
  427. Mix_HaltMusic();
  428. }
  429. if (loop == 0 && Mix_FadingMusic() != MIX_NO_FADING)
  430. {
  431. assert(0);
  432. logGlobal->error("Attempt to delete music while fading out!");
  433. Mix_HaltMusic();
  434. }
  435. logGlobal->trace("Del-ing music file %s", currentName);
  436. if (music)
  437. Mix_FreeMusic(music);
  438. }
  439. void MusicEntry::load(std::string musicURI)
  440. {
  441. if (music)
  442. {
  443. logGlobal->trace("Del-ing music file %s", currentName);
  444. Mix_FreeMusic(music);
  445. music = nullptr;
  446. }
  447. currentName = musicURI;
  448. logGlobal->trace("Loading music file %s", musicURI);
  449. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(ResourceID(std::move(musicURI), EResType::MUSIC)));
  450. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  451. if(!music)
  452. {
  453. logGlobal->warn("Warning: Cannot open %s: %s", currentName, Mix_GetError());
  454. return;
  455. }
  456. }
  457. bool MusicEntry::play()
  458. {
  459. if (!(loop--) && music) //already played once - return
  460. return false;
  461. if (!setName.empty())
  462. {
  463. const auto & set = owner->musicsSet[setName];
  464. const auto & iter = RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault());
  465. load(*iter);
  466. }
  467. logGlobal->trace("Playing music file %s", currentName);
  468. if (!fromStart && owner->trackPositions.count(currentName) > 0 && owner->trackPositions[currentName] > 0)
  469. {
  470. float timeToStart = owner->trackPositions[currentName];
  471. startPosition = std::round(timeToStart * 1000);
  472. // erase stored position:
  473. // if music track will be interrupted again - new position will be written in stop() method
  474. // if music track is not interrupted and will finish by timeout/end of file - it will restart from begginning as it should
  475. owner->trackPositions.erase(owner->trackPositions.find(currentName));
  476. if (Mix_FadeInMusicPos(music, 1, 1000, timeToStart) == -1)
  477. {
  478. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  479. return false;
  480. }
  481. }
  482. else
  483. {
  484. startPosition = 0;
  485. if(Mix_PlayMusic(music, 1) == -1)
  486. {
  487. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  488. return false;
  489. }
  490. }
  491. startTime = SDL_GetTicks();
  492. playing = true;
  493. return true;
  494. }
  495. bool MusicEntry::stop(int fade_ms)
  496. {
  497. if (Mix_PlayingMusic())
  498. {
  499. playing = false;
  500. loop = 0;
  501. uint32_t endTime = SDL_GetTicks();
  502. assert(startTime != uint32_t(-1));
  503. float playDuration = (endTime - startTime + startPosition) / 1000.f;
  504. owner->trackPositions[currentName] = playDuration;
  505. logGlobal->trace("Stopping music file %s at %f", currentName, playDuration);
  506. Mix_FadeOutMusic(fade_ms);
  507. return true;
  508. }
  509. return false;
  510. }
  511. bool MusicEntry::isPlaying()
  512. {
  513. return playing;
  514. }
  515. bool MusicEntry::isSet(std::string set)
  516. {
  517. return !setName.empty() && set == setName;
  518. }
  519. bool MusicEntry::isTrack(std::string track)
  520. {
  521. return setName.empty() && track == currentName;
  522. }