CMusicHandler.cpp 15 KB

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