CMusicHandler.cpp 17 KB

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