CMusicHandler.cpp 16 KB

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