CMusicHandler.cpp 15 KB

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