CMusicHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 "CMusicHandler.h"
  13. #include "CGameInfo.h"
  14. #include "SDLRWwrapper.h"
  15. #include "../lib/JsonNode.h"
  16. #include "../lib/GameConstants.h"
  17. #include "../lib/filesystem/Filesystem.h"
  18. #include "../lib/StringConstants.h"
  19. #include "../lib/CRandomGenerator.h"
  20. #include "../lib/VCMIDirs.h"
  21. #include "../lib/Terrain.h"
  22. #define VCMI_SOUND_NAME(x)
  23. #define VCMI_SOUND_FILE(y) #y,
  24. // sounds mapped to soundBase enum
  25. static std::string sounds[] = {
  26. "", // invalid
  27. "", // todo
  28. VCMI_SOUND_LIST
  29. };
  30. #undef VCMI_SOUND_NAME
  31. #undef VCMI_SOUND_FILE
  32. // Not pretty, but there's only one music handler object in the game.
  33. static void soundFinishedCallbackC(int channel)
  34. {
  35. CCS->soundh->soundFinishedCallback(channel);
  36. }
  37. static void musicFinishedCallbackC()
  38. {
  39. CCS->musich->musicFinishedCallback();
  40. }
  41. void CAudioBase::init()
  42. {
  43. if (initialized)
  44. return;
  45. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  46. {
  47. logGlobal->error("Mix_OpenAudio error: %s", Mix_GetError());
  48. return;
  49. }
  50. initialized = true;
  51. }
  52. void CAudioBase::release()
  53. {
  54. if(!(CCS->soundh->initialized && CCS->musich->initialized))
  55. Mix_CloseAudio();
  56. initialized = false;
  57. }
  58. void CAudioBase::setVolume(ui32 percent)
  59. {
  60. if (percent > 100)
  61. percent = 100;
  62. volume = percent;
  63. }
  64. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  65. {
  66. setVolume((ui32)volumeNode.Float());
  67. }
  68. CSoundHandler::CSoundHandler():
  69. listener(settings.listen["general"]["sound"]),
  70. ambientConfig(JsonNode(ResourceID("config/ambientSounds.json")))
  71. {
  72. allTilesSource = ambientConfig["allTilesSource"].Bool();
  73. listener(std::bind(&CSoundHandler::onVolumeChange, this, _1));
  74. // Vectors for helper(s)
  75. pickupSounds =
  76. {
  77. soundBase::pickup01, soundBase::pickup02, soundBase::pickup03,
  78. soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07
  79. };
  80. battleIntroSounds =
  81. {
  82. soundBase::battle00, soundBase::battle01,
  83. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  84. soundBase::battle05, soundBase::battle06, soundBase::battle07
  85. };
  86. //predefine terrain set
  87. //TODO: need refactoring - support custom sounds for new terrains and load from json
  88. horseSounds =
  89. {
  90. {Terrain::DIRT, soundBase::horseDirt},
  91. {Terrain::SAND, soundBase::horseSand},
  92. {Terrain::GRASS, soundBase::horseGrass},
  93. {Terrain::SNOW, soundBase::horseSnow},
  94. {Terrain::SWAMP, soundBase::horseSwamp},
  95. {Terrain::ROUGH, soundBase::horseRough},
  96. {Terrain::SUBTERRANEAN, soundBase::horseSubterranean},
  97. {Terrain::LAVA, soundBase::horseLava},
  98. {Terrain::WATER, soundBase::horseWater},
  99. {Terrain::ROCK, soundBase::horseRock}
  100. };
  101. }
  102. void CSoundHandler::loadHorseSounds()
  103. {
  104. auto terrains = CGI->terrainTypeHandler->terrains();
  105. for(const auto * terrain : terrains)
  106. {
  107. //since all sounds are hardcoded, let's keep it
  108. if(vstd::contains(horseSounds, terrain->id))
  109. continue;
  110. //Use already existing horse sound
  111. horseSounds[terrain->id] = horseSounds.at(terrains[terrain->id]->horseSoundId);
  112. }
  113. }
  114. void CSoundHandler::init()
  115. {
  116. CAudioBase::init();
  117. if(ambientConfig["allocateChannels"].isNumber())
  118. Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
  119. if (initialized)
  120. {
  121. // Load sounds
  122. Mix_ChannelFinished(soundFinishedCallbackC);
  123. }
  124. }
  125. void CSoundHandler::release()
  126. {
  127. if (initialized)
  128. {
  129. Mix_HaltChannel(-1);
  130. for (auto &chunk : soundChunks)
  131. {
  132. if (chunk.second.first)
  133. Mix_FreeChunk(chunk.second.first);
  134. }
  135. }
  136. CAudioBase::release();
  137. }
  138. // Allocate an SDL chunk and cache it.
  139. Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound, bool cache)
  140. {
  141. try
  142. {
  143. if (cache && soundChunks.find(sound) != soundChunks.end())
  144. return soundChunks[sound].first;
  145. auto data = CResourceHandler::get()->load(ResourceID(std::string("SOUNDS/") + sound, EResType::SOUND))->readAll();
  146. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  147. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  148. if (cache)
  149. soundChunks.insert(std::pair<std::string, CachedChunk>(sound, std::make_pair (chunk, std::move (data.first))));
  150. return chunk;
  151. }
  152. catch(std::exception &e)
  153. {
  154. logGlobal->warn("Cannot get sound %s chunk: %s", sound, e.what());
  155. return nullptr;
  156. }
  157. }
  158. int CSoundHandler::ambientDistToVolume(int distance) const
  159. {
  160. if(distance >= ambientConfig["distances"].Vector().size())
  161. return 0;
  162. int volume = static_cast<int>(ambientConfig["distances"].Vector()[distance].Integer());
  163. return volume * (int)ambientConfig["volume"].Integer() * getVolume() / 10000;
  164. }
  165. void CSoundHandler::ambientStopSound(std::string soundId)
  166. {
  167. stopSound(ambientChannels[soundId]);
  168. setChannelVolume(ambientChannels[soundId], volume);
  169. }
  170. // Plays a sound, and return its channel so we can fade it out later
  171. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  172. {
  173. assert(soundID < soundBase::sound_after_last);
  174. auto sound = sounds[soundID];
  175. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound);
  176. return playSound(sound, repeats, true);
  177. }
  178. int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
  179. {
  180. if (!initialized || sound.empty())
  181. return -1;
  182. int channel;
  183. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  184. if (chunk)
  185. {
  186. channel = Mix_PlayChannel(-1, chunk, repeats);
  187. if (channel == -1)
  188. {
  189. logGlobal->error("Unable to play sound file %s , error %s", sound, Mix_GetError());
  190. if (!cache)
  191. Mix_FreeChunk(chunk);
  192. }
  193. else if (cache)
  194. callbacks[channel];
  195. else
  196. callbacks[channel] = [chunk](){ Mix_FreeChunk(chunk);};
  197. }
  198. else
  199. channel = -1;
  200. return channel;
  201. }
  202. // Helper. Randomly select a sound from an array and play it
  203. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  204. {
  205. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  206. }
  207. void CSoundHandler::stopSound( int handler )
  208. {
  209. if (initialized && handler != -1)
  210. Mix_HaltChannel(handler);
  211. }
  212. // Sets the sound volume, from 0 (mute) to 100
  213. void CSoundHandler::setVolume(ui32 percent)
  214. {
  215. CAudioBase::setVolume(percent);
  216. if (initialized)
  217. setChannelVolume(-1, volume);
  218. }
  219. // Sets the sound volume, from 0 (mute) to 100
  220. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  221. {
  222. Mix_Volume(channel, (MIX_MAX_VOLUME * percent)/100);
  223. }
  224. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  225. {
  226. std::map<int, std::function<void()> >::iterator iter;
  227. iter = callbacks.find(channel);
  228. //channel not found. It may have finished so fire callback now
  229. if(iter == callbacks.end())
  230. function();
  231. else
  232. iter->second = function;
  233. }
  234. void CSoundHandler::soundFinishedCallback(int channel)
  235. {
  236. std::map<int, std::function<void()> >::iterator iter;
  237. iter = callbacks.find(channel);
  238. if (iter == callbacks.end())
  239. return;
  240. auto callback = std::move(iter->second);
  241. callbacks.erase(iter);
  242. if (callback)
  243. callback();
  244. }
  245. int CSoundHandler::ambientGetRange() const
  246. {
  247. return static_cast<int>(ambientConfig["range"].Integer());
  248. }
  249. bool CSoundHandler::ambientCheckVisitable() const
  250. {
  251. return !allTilesSource;
  252. }
  253. void CSoundHandler::ambientUpdateChannels(std::map<std::string, int> soundsArg)
  254. {
  255. boost::mutex::scoped_lock guard(mutex);
  256. std::vector<std::string> stoppedSounds;
  257. for(auto & pair : ambientChannels)
  258. {
  259. if(!vstd::contains(soundsArg, pair.first))
  260. {
  261. ambientStopSound(pair.first);
  262. stoppedSounds.push_back(pair.first);
  263. }
  264. else
  265. {
  266. CCS->soundh->setChannelVolume(pair.second, ambientDistToVolume(soundsArg[pair.first]));
  267. }
  268. }
  269. for(auto soundId : stoppedSounds)
  270. ambientChannels.erase(soundId);
  271. for(auto & pair : soundsArg)
  272. {
  273. if(!vstd::contains(ambientChannels, pair.first))
  274. {
  275. int channel = CCS->soundh->playSound(pair.first, -1);
  276. CCS->soundh->setChannelVolume(channel, ambientDistToVolume(pair.second));
  277. CCS->soundh->ambientChannels.insert(std::make_pair(pair.first, channel));
  278. }
  279. }
  280. }
  281. void CSoundHandler::ambientStopAllChannels()
  282. {
  283. boost::mutex::scoped_lock guard(mutex);
  284. for(auto ch : ambientChannels)
  285. {
  286. ambientStopSound(ch.first);
  287. }
  288. ambientChannels.clear();
  289. }
  290. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  291. {
  292. setVolume((ui32)volumeNode.Float());
  293. }
  294. CMusicHandler::CMusicHandler():
  295. listener(settings.listen["general"]["music"])
  296. {
  297. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  298. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourceID & id) -> bool
  299. {
  300. if(id.getType() != EResType::MUSIC)
  301. return false;
  302. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  303. return false;
  304. logGlobal->trace("Found music file %s", id.getName());
  305. return true;
  306. });
  307. for(const ResourceID & file : mp3files)
  308. {
  309. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  310. addEntryToSet("battle", file.getName(), file.getName());
  311. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  312. addEntryToSet("enemy-turn", file.getName(), file.getName());
  313. }
  314. }
  315. void CMusicHandler::loadTerrainSounds()
  316. {
  317. for (const auto* terrain : CGI->terrainTypeHandler->terrains())
  318. {
  319. addEntryToSet("terrain", terrain->name, "Music/" + terrain->musicFilename);
  320. }
  321. }
  322. void CMusicHandler::addEntryToSet(const std::string & set, const std::string & musicID, const std::string & musicURI)
  323. {
  324. musicsSet[set][musicID] = musicURI;
  325. }
  326. void CMusicHandler::init()
  327. {
  328. CAudioBase::init();
  329. if (initialized)
  330. Mix_HookMusicFinished(musicFinishedCallbackC);
  331. }
  332. void CMusicHandler::release()
  333. {
  334. if (initialized)
  335. {
  336. boost::mutex::scoped_lock guard(mutex);
  337. Mix_HookMusicFinished(nullptr);
  338. current.reset();
  339. next.reset();
  340. }
  341. CAudioBase::release();
  342. }
  343. void CMusicHandler::playMusic(const std::string & musicURI, bool loop)
  344. {
  345. if (current && current->isTrack(musicURI))
  346. return;
  347. queueNext(this, "", musicURI, loop);
  348. }
  349. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop)
  350. {
  351. auto selectedSet = musicsSet.find(whichSet);
  352. if (selectedSet == musicsSet.end())
  353. {
  354. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  355. return;
  356. }
  357. if (current && current->isSet(whichSet))
  358. return;
  359. // in this mode - play random track from set
  360. queueNext(this, whichSet, "", loop);
  361. }
  362. void CMusicHandler::playMusicFromSet(const std::string & whichSet, const std::string & entryID, bool loop)
  363. {
  364. auto selectedSet = musicsSet.find(whichSet);
  365. if (selectedSet == musicsSet.end())
  366. {
  367. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  368. return;
  369. }
  370. auto selectedEntry = selectedSet->second.find(entryID);
  371. if (selectedEntry == selectedSet->second.end())
  372. {
  373. logGlobal->error("Error: playing non-existing entry %s from set: %s", entryID, whichSet);
  374. return;
  375. }
  376. if (current && current->isTrack(selectedEntry->second))
  377. return;
  378. // in this mode - play specific track from set
  379. queueNext(this, "", selectedEntry->second, loop);
  380. }
  381. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  382. {
  383. if (!initialized)
  384. return;
  385. boost::mutex::scoped_lock guard(mutex);
  386. next = std::move(queued);
  387. if (current.get() == nullptr || !current->stop(1000))
  388. {
  389. current.reset(next.release());
  390. current->play();
  391. }
  392. }
  393. void CMusicHandler::queueNext(CMusicHandler *owner, const std::string & setName, const std::string & musicURI, bool looped)
  394. {
  395. try
  396. {
  397. queueNext(make_unique<MusicEntry>(owner, setName, musicURI, looped));
  398. }
  399. catch(std::exception &e)
  400. {
  401. logGlobal->error("Failed to queue music. setName=%s\tmusicURI=%s", setName, musicURI);
  402. logGlobal->error("Exception: %s", e.what());
  403. }
  404. }
  405. void CMusicHandler::stopMusic(int fade_ms)
  406. {
  407. if (!initialized)
  408. return;
  409. boost::mutex::scoped_lock guard(mutex);
  410. if (current.get() != nullptr)
  411. current->stop(fade_ms);
  412. next.reset();
  413. }
  414. void CMusicHandler::setVolume(ui32 percent)
  415. {
  416. CAudioBase::setVolume(percent);
  417. if (initialized)
  418. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  419. }
  420. void CMusicHandler::musicFinishedCallback()
  421. {
  422. boost::mutex::scoped_lock guard(mutex);
  423. if (current.get() != nullptr)
  424. {
  425. //return if current music still not finished
  426. if (current->play())
  427. return;
  428. else
  429. current.reset();
  430. }
  431. if (current.get() == nullptr && next.get() != nullptr)
  432. {
  433. current.reset(next.release());
  434. current->play();
  435. }
  436. }
  437. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
  438. owner(owner),
  439. music(nullptr),
  440. loop(looped ? -1 : 1),
  441. setName(std::move(setName))
  442. {
  443. if (!musicURI.empty())
  444. load(std::move(musicURI));
  445. }
  446. MusicEntry::~MusicEntry()
  447. {
  448. logGlobal->trace("Del-ing music file %s", currentName);
  449. if (music)
  450. Mix_FreeMusic(music);
  451. }
  452. void MusicEntry::load(std::string musicURI)
  453. {
  454. if (music)
  455. {
  456. logGlobal->trace("Del-ing music file %s", currentName);
  457. Mix_FreeMusic(music);
  458. music = nullptr;
  459. }
  460. currentName = musicURI;
  461. logGlobal->trace("Loading music file %s", musicURI);
  462. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(ResourceID(std::move(musicURI), EResType::MUSIC)));
  463. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  464. if(!music)
  465. {
  466. logGlobal->warn("Warning: Cannot open %s: %s", currentName, Mix_GetError());
  467. return;
  468. }
  469. }
  470. bool MusicEntry::play()
  471. {
  472. if (!(loop--) && music) //already played once - return
  473. return false;
  474. if (!setName.empty())
  475. {
  476. const auto & set = owner->musicsSet[setName];
  477. load(RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault())->second);
  478. }
  479. logGlobal->trace("Playing music file %s", currentName);
  480. if(Mix_PlayMusic(music, 1) == -1)
  481. {
  482. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  483. return false;
  484. }
  485. return true;
  486. }
  487. bool MusicEntry::stop(int fade_ms)
  488. {
  489. if (Mix_PlayingMusic())
  490. {
  491. logGlobal->trace("Stopping music file %s", currentName);
  492. loop = 0;
  493. Mix_FadeOutMusic(fade_ms);
  494. return true;
  495. }
  496. return false;
  497. }
  498. bool MusicEntry::isSet(std::string set)
  499. {
  500. return !setName.empty() && set == setName;
  501. }
  502. bool MusicEntry::isTrack(std::string track)
  503. {
  504. return setName.empty() && track == currentName;
  505. }