CMusicHandler.cpp 14 KB

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