CMusicHandler.cpp 16 KB

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