CMusicHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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.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.reset();
  311. next.reset();
  312. }
  313. CAudioBase::release();
  314. }
  315. void CMusicHandler::playMusic(const std::string & musicURI, bool loop, bool fromStart)
  316. {
  317. boost::mutex::scoped_lock guard(mutex);
  318. if (current && current->isPlaying() && current->isTrack(musicURI))
  319. return;
  320. queueNext(this, "", musicURI, loop, fromStart);
  321. }
  322. void CMusicHandler::playMusicFromSet(const std::string & musicSet, const std::string & entryID, bool loop, bool fromStart)
  323. {
  324. playMusicFromSet(musicSet + "_" + entryID, loop, fromStart);
  325. }
  326. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop, bool fromStart)
  327. {
  328. boost::mutex::scoped_lock guard(mutex);
  329. auto selectedSet = musicsSet.find(whichSet);
  330. if (selectedSet == musicsSet.end())
  331. {
  332. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  333. return;
  334. }
  335. if (current && current->isPlaying() && current->isSet(whichSet))
  336. return;
  337. // in this mode - play random track from set
  338. queueNext(this, whichSet, "", loop, fromStart);
  339. }
  340. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  341. {
  342. if (!initialized)
  343. return;
  344. next = std::move(queued);
  345. if (current.get() == nullptr || !current->stop(1000))
  346. {
  347. current.reset(next.release());
  348. current->play();
  349. }
  350. }
  351. void CMusicHandler::queueNext(CMusicHandler *owner, const std::string & setName, const std::string & musicURI, bool looped, bool fromStart)
  352. {
  353. try
  354. {
  355. queueNext(std::make_unique<MusicEntry>(owner, setName, musicURI, looped, fromStart));
  356. }
  357. catch(std::exception &e)
  358. {
  359. logGlobal->error("Failed to queue music. setName=%s\tmusicURI=%s", setName, musicURI);
  360. logGlobal->error("Exception: %s", e.what());
  361. }
  362. }
  363. void CMusicHandler::stopMusic(int fade_ms)
  364. {
  365. if (!initialized)
  366. return;
  367. boost::mutex::scoped_lock guard(mutex);
  368. if (current.get() != nullptr)
  369. current->stop(fade_ms);
  370. next.reset();
  371. }
  372. void CMusicHandler::setVolume(ui32 percent)
  373. {
  374. CAudioBase::setVolume(percent);
  375. if (initialized)
  376. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  377. }
  378. void CMusicHandler::musicFinishedCallback()
  379. {
  380. // boost::mutex::scoped_lock guard(mutex);
  381. // FIXME: WORKAROUND FOR A POTENTIAL DEADLOCK
  382. // It is possible for:
  383. // 1) SDL thread to call this method on end of playback
  384. // 2) VCMI code to call queueNext() method to queue new file
  385. // this leads to:
  386. // 1) SDL thread waiting to acquire music lock in this method (while keeping internal SDL mutex locked)
  387. // 2) VCMI thread waiting to acquire internal SDL mutex (while keeping music mutex locked)
  388. // Because of that (and lack of clear way to fix that)
  389. // We will try to acquire lock here and if failed - do nothing
  390. // This may break music playback till next song is enqued but won't deadlock the game
  391. if (!mutex.try_lock())
  392. {
  393. logGlobal->error("Failed to acquire mutex! Unable to restart music!");
  394. return;
  395. }
  396. if (current.get() != nullptr)
  397. {
  398. // if music is looped, play it again
  399. if (current->play())
  400. {
  401. mutex.unlock();
  402. return;
  403. }
  404. else
  405. current.reset();
  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)
  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->info("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. }