CMusicHandler.cpp 16 KB

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