CMusicHandler.cpp 13 KB

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