CMusicHandler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. #include "StdInc.h"
  2. #include <SDL_mixer.h>
  3. #include "CMusicHandler.h"
  4. #include "CGameInfo.h"
  5. #include "SDLRWwrapper.h"
  6. #include "../lib/CCreatureHandler.h"
  7. #include "../lib/spells/CSpellHandler.h"
  8. #include "../lib/JsonNode.h"
  9. #include "../lib/GameConstants.h"
  10. #include "../lib/filesystem/Filesystem.h"
  11. #include "../lib/StringConstants.h"
  12. #include "../lib/CRandomGenerator.h"
  13. /*
  14. * CMusicHandler.cpp, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  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(void)
  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->errorStream() << "Mix_OpenAudio error: " << Mix_GetError();
  48. return;
  49. }
  50. initialized = true;
  51. }
  52. void CAudioBase::release()
  53. {
  54. if (initialized)
  55. {
  56. Mix_CloseAudio();
  57. initialized = false;
  58. }
  59. }
  60. void CAudioBase::setVolume(ui32 percent)
  61. {
  62. if (percent > 100)
  63. percent = 100;
  64. volume = percent;
  65. }
  66. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  67. {
  68. setVolume(volumeNode.Float());
  69. }
  70. CSoundHandler::CSoundHandler():
  71. listener(settings.listen["general"]["sound"])
  72. {
  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. horseSounds = // must be the same order as terrains (see ETerrainType);
  81. {
  82. soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
  83. soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
  84. soundBase::horseSubterranean, soundBase::horseLava,
  85. soundBase::horseWater, soundBase::horseRock
  86. };
  87. battleIntroSounds =
  88. {
  89. soundBase::battle00, soundBase::battle01,
  90. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  91. soundBase::battle05, soundBase::battle06, soundBase::battle07
  92. };
  93. };
  94. void CSoundHandler::init()
  95. {
  96. CAudioBase::init();
  97. if (initialized)
  98. {
  99. // Load sounds
  100. Mix_ChannelFinished(soundFinishedCallbackC);
  101. }
  102. }
  103. void CSoundHandler::release()
  104. {
  105. if (initialized)
  106. {
  107. Mix_HaltChannel(-1);
  108. for (auto &chunk : soundChunks)
  109. {
  110. if (chunk.second)
  111. Mix_FreeChunk(chunk.second);
  112. }
  113. }
  114. CAudioBase::release();
  115. }
  116. // Allocate an SDL chunk and cache it.
  117. Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound, bool cache)
  118. {
  119. try
  120. {
  121. if (cache && soundChunks.find(sound) != soundChunks.end())
  122. return soundChunks[sound];
  123. auto data = CResourceHandler::get()->load(ResourceID(std::string("SOUNDS/") + sound, EResType::SOUND))->readAll();
  124. SDL_RWops *ops = SDL_RWFromMem(data.first.release(), data.second);
  125. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  126. if (cache)
  127. soundChunks.insert(std::pair<std::string, Mix_Chunk *>(sound, chunk));
  128. return chunk;
  129. }
  130. catch(std::exception &e)
  131. {
  132. logGlobal->warnStream() << "Cannot get sound " << sound << " chunk: " << e.what();
  133. return nullptr;
  134. }
  135. }
  136. // Plays a sound, and return its channel so we can fade it out later
  137. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  138. {
  139. assert(soundID < soundBase::sound_after_last);
  140. auto sound = sounds[soundID];
  141. logGlobal->traceStream() << "Attempt to play sound " << soundID << " with file name " << sound << " with cache";
  142. return playSound(sound, repeats, true);
  143. }
  144. int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
  145. {
  146. if (!initialized || sound.empty())
  147. return -1;
  148. int channel;
  149. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  150. if (chunk)
  151. {
  152. channel = Mix_PlayChannel(-1, chunk, repeats);
  153. if (channel == -1)
  154. {
  155. logGlobal->errorStream() << "Unable to play sound file " << sound << " , error " << Mix_GetError();
  156. if (!cache)
  157. Mix_FreeChunk(chunk);
  158. }
  159. else if (cache)
  160. callbacks[channel];
  161. else
  162. callbacks[channel] = [chunk]{ Mix_FreeChunk(chunk);};
  163. }
  164. else
  165. channel = -1;
  166. return channel;
  167. }
  168. // Helper. Randomly select a sound from an array and play it
  169. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  170. {
  171. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  172. }
  173. void CSoundHandler::stopSound( int handler )
  174. {
  175. if (initialized && handler != -1)
  176. Mix_HaltChannel(handler);
  177. }
  178. // Sets the sound volume, from 0 (mute) to 100
  179. void CSoundHandler::setVolume(ui32 percent)
  180. {
  181. CAudioBase::setVolume(percent);
  182. if (initialized)
  183. Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
  184. }
  185. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  186. {
  187. std::map<int, std::function<void()> >::iterator iter;
  188. iter = callbacks.find(channel);
  189. //channel not found. It may have finished so fire callback now
  190. if(iter == callbacks.end())
  191. function();
  192. else
  193. iter->second = function;
  194. }
  195. void CSoundHandler::soundFinishedCallback(int channel)
  196. {
  197. std::map<int, std::function<void()> >::iterator iter;
  198. iter = callbacks.find(channel);
  199. assert(iter != callbacks.end());
  200. if (iter->second)
  201. iter->second();
  202. callbacks.erase(iter);
  203. }
  204. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  205. {
  206. setVolume(volumeNode.Float());
  207. }
  208. CMusicHandler::CMusicHandler():
  209. listener(settings.listen["general"]["music"])
  210. {
  211. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  212. // Map music IDs
  213. // Vectors for helper
  214. const std::string setEnemy[] = {"AITheme0", "AITheme1", "AITheme2"};
  215. const std::string setBattle[] = {"Combat01", "Combat02", "Combat03", "Combat04"};
  216. auto fillSet = [=](std::string setName, const std::string list[], size_t amount)
  217. {
  218. for (size_t i=0; i < amount; i++)
  219. addEntryToSet(setName, i, "music/" + list[i]);
  220. };
  221. fillSet("enemy-turn", setEnemy, ARRAY_COUNT(setEnemy));
  222. fillSet("battle", setBattle, ARRAY_COUNT(setBattle));
  223. JsonNode terrains(ResourceID("config/terrains.json"));
  224. for (auto entry : terrains.Struct())
  225. {
  226. int terrIndex = vstd::find_pos(GameConstants::TERRAIN_NAMES, entry.first);
  227. addEntryToSet("terrain", terrIndex, "Music/" + entry.second["music"].String());
  228. }
  229. }
  230. void CMusicHandler::addEntryToSet(std::string set, int musicID, std::string musicURI)
  231. {
  232. musicsSet[set][musicID] = musicURI;
  233. }
  234. void CMusicHandler::init()
  235. {
  236. CAudioBase::init();
  237. if (initialized)
  238. Mix_HookMusicFinished(musicFinishedCallbackC);
  239. }
  240. void CMusicHandler::release()
  241. {
  242. if (initialized)
  243. {
  244. boost::mutex::scoped_lock guard(musicMutex);
  245. Mix_HookMusicFinished(nullptr);
  246. current.reset();
  247. next.reset();
  248. }
  249. CAudioBase::release();
  250. }
  251. void CMusicHandler::playMusic(std::string musicURI, bool loop)
  252. {
  253. if (current && current->isTrack(musicURI))
  254. return;
  255. queueNext(this, "", musicURI, loop);
  256. }
  257. void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
  258. {
  259. auto selectedSet = musicsSet.find(whichSet);
  260. if (selectedSet == musicsSet.end())
  261. {
  262. logGlobal->errorStream() << "Error: playing music from non-existing set: " << whichSet;
  263. return;
  264. }
  265. if (current && current->isSet(whichSet))
  266. return;
  267. // in this mode - play random track from set
  268. queueNext(this, whichSet, "", loop);
  269. }
  270. void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loop)
  271. {
  272. auto selectedSet = musicsSet.find(whichSet);
  273. if (selectedSet == musicsSet.end())
  274. {
  275. logGlobal->errorStream() << "Error: playing music from non-existing set: " << whichSet;
  276. return;
  277. }
  278. auto selectedEntry = selectedSet->second.find(entryID);
  279. if (selectedEntry == selectedSet->second.end())
  280. {
  281. logGlobal->errorStream() << "Error: playing non-existing entry " << entryID << " from set: " << whichSet;
  282. return;
  283. }
  284. if (current && current->isTrack(selectedEntry->second))
  285. return;
  286. // in this mode - play specific track from set
  287. queueNext(this, "", selectedEntry->second, loop);
  288. }
  289. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  290. {
  291. if (!initialized)
  292. return;
  293. boost::mutex::scoped_lock guard(musicMutex);
  294. next = std::move(queued);
  295. if (current.get() == nullptr || !current->stop(1000))
  296. {
  297. current.reset(next.release());
  298. current->play();
  299. }
  300. }
  301. void CMusicHandler::queueNext(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped)
  302. {
  303. try
  304. {
  305. queueNext(make_unique<MusicEntry>(owner, setName, musicURI, looped));
  306. }
  307. catch(std::exception &e)
  308. {
  309. logGlobal->errorStream() << "Failed to queue music. setName=" << setName << "\tmusicURI=" << musicURI;
  310. logGlobal->errorStream() << "Exception: " << e.what();
  311. }
  312. }
  313. void CMusicHandler::stopMusic(int fade_ms)
  314. {
  315. if (!initialized)
  316. return;
  317. boost::mutex::scoped_lock guard(musicMutex);
  318. if (current.get() != nullptr)
  319. current->stop(fade_ms);
  320. next.reset();
  321. }
  322. void CMusicHandler::setVolume(ui32 percent)
  323. {
  324. CAudioBase::setVolume(percent);
  325. if (initialized)
  326. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  327. }
  328. void CMusicHandler::musicFinishedCallback(void)
  329. {
  330. boost::mutex::scoped_lock guard(musicMutex);
  331. if (current.get() != nullptr)
  332. {
  333. //return if current music still not finished
  334. if (current->play())
  335. return;
  336. else
  337. current.reset();
  338. }
  339. if (current.get() == nullptr && next.get() != nullptr)
  340. {
  341. current.reset(next.release());
  342. current->play();
  343. }
  344. }
  345. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
  346. owner(owner),
  347. music(nullptr),
  348. loop(looped ? -1 : 1),
  349. setName(std::move(setName))
  350. {
  351. if (!musicURI.empty())
  352. load(std::move(musicURI));
  353. }
  354. MusicEntry::~MusicEntry()
  355. {
  356. logGlobal->traceStream()<<"Del-ing music file "<<currentName;
  357. if (music)
  358. Mix_FreeMusic(music);
  359. }
  360. void MusicEntry::load(std::string musicURI)
  361. {
  362. if (music)
  363. {
  364. logGlobal->traceStream()<<"Del-ing music file "<<currentName;
  365. Mix_FreeMusic(music);
  366. music = nullptr;
  367. }
  368. currentName = musicURI;
  369. logGlobal->traceStream()<<"Loading music file "<<musicURI;
  370. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(ResourceID(std::move(musicURI), EResType::MUSIC)));
  371. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  372. if(!music)
  373. {
  374. logGlobal->warnStream() << "Warning: Cannot open " << currentName << ": " << Mix_GetError();
  375. return;
  376. }
  377. }
  378. bool MusicEntry::play()
  379. {
  380. if (!(loop--) && music) //already played once - return
  381. return false;
  382. if (!setName.empty())
  383. {
  384. auto set = owner->musicsSet[setName];
  385. load(RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault())->second);
  386. }
  387. logGlobal->traceStream()<<"Playing music file "<<currentName;
  388. if(Mix_PlayMusic(music, 1) == -1)
  389. {
  390. logGlobal->errorStream() << "Unable to play music (" << Mix_GetError() << ")";
  391. return false;
  392. }
  393. return true;
  394. }
  395. bool MusicEntry::stop(int fade_ms)
  396. {
  397. if (Mix_PlayingMusic())
  398. {
  399. logGlobal->traceStream()<<"Stoping music file "<<currentName;
  400. loop = 0;
  401. Mix_FadeOutMusic(fade_ms);
  402. return true;
  403. }
  404. return false;
  405. }
  406. bool MusicEntry::isSet(std::string set)
  407. {
  408. return !setName.empty() && set == setName;
  409. }
  410. bool MusicEntry::isTrack(std::string track)
  411. {
  412. return setName.empty() && track == currentName;
  413. }