CMusicHandler.cpp 16 KB

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