CMusicHandler.cpp 14 KB

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