CMusicHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. void CSoundHandler::initSpellsSounds(const std::vector< ConstTransitivePtr<CSpell> > &spells)
  151. {
  152. const JsonNode config(ResourceID("config/sp_sounds.json"));
  153. if (!config["spell_sounds"].isNull())
  154. {
  155. for(const JsonNode &node : config["spell_sounds"].Vector())
  156. {
  157. int spellid = node["id"].Float();
  158. const CSpell *s = CGI->spellh->spells[spellid];
  159. if (vstd::contains(spellSounds, s))
  160. logGlobal->errorStream() << "Spell << " << spellid << " already has a sound";
  161. std::string sound = node["soundfile"].String();
  162. if (sound.empty())
  163. logGlobal->errorStream() << "Error: invalid sound for id "<< spellid;
  164. spellSounds[s] = sound;
  165. }
  166. }
  167. }
  168. // Plays a sound, and return its channel so we can fade it out later
  169. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  170. {
  171. assert(soundID < soundBase::sound_after_last);
  172. if (!initialized)
  173. return -1;
  174. int channel;
  175. Mix_Chunk *chunk = GetSoundChunk(soundID);
  176. if (chunk)
  177. {
  178. channel = Mix_PlayChannel(-1, chunk, repeats);
  179. if (channel == -1)
  180. logGlobal->errorStream() << "Unable to play sound file " << soundID << " , error " << Mix_GetError();
  181. else
  182. callbacks[channel];//insert empty callback
  183. }
  184. else
  185. {
  186. channel = -1;
  187. }
  188. return channel;
  189. }
  190. int CSoundHandler::playSound(std::string sound, int repeats)
  191. {
  192. if (!initialized)
  193. return -1;
  194. int channel;
  195. Mix_Chunk *chunk = GetSoundChunk(sound);
  196. if (chunk)
  197. {
  198. channel = Mix_PlayChannel(-1, chunk, repeats);
  199. if (channel == -1)
  200. logGlobal->errorStream() << "Unable to play sound file " << sound << " , error " << Mix_GetError();
  201. else
  202. callbacks[channel];//insert empty callback
  203. }
  204. else
  205. {
  206. channel = -1;
  207. }
  208. return channel;
  209. }
  210. // Helper. Randomly select a sound from an array and play it
  211. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  212. {
  213. return playSound(sound_vec[rand() % sound_vec.size()]);
  214. }
  215. void CSoundHandler::stopSound( int handler )
  216. {
  217. if (initialized && handler != -1)
  218. Mix_HaltChannel(handler);
  219. }
  220. // Sets the sound volume, from 0 (mute) to 100
  221. void CSoundHandler::setVolume(ui32 percent)
  222. {
  223. CAudioBase::setVolume(percent);
  224. if (initialized)
  225. Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
  226. }
  227. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  228. {
  229. std::map<int, std::function<void()> >::iterator iter;
  230. iter = callbacks.find(channel);
  231. //channel not found. It may have finished so fire callback now
  232. if(iter == callbacks.end())
  233. function();
  234. else
  235. iter->second = function;
  236. }
  237. void CSoundHandler::soundFinishedCallback(int channel)
  238. {
  239. std::map<int, std::function<void()> >::iterator iter;
  240. iter = callbacks.find(channel);
  241. assert(iter != callbacks.end());
  242. if (iter->second)
  243. iter->second();
  244. callbacks.erase(iter);
  245. }
  246. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  247. {
  248. setVolume(volumeNode.Float());
  249. }
  250. CMusicHandler::CMusicHandler():
  251. listener(settings.listen["general"]["music"])
  252. {
  253. listener(boost::bind(&CMusicHandler::onVolumeChange, this, _1));
  254. // Map music IDs
  255. // Vectors for helper
  256. const std::string setEnemy[] = {"AITheme0", "AITheme1", "AITheme2"};
  257. const std::string setBattle[] = {"Combat01", "Combat02", "Combat03", "Combat04"};
  258. auto fillSet = [=](std::string setName, const std::string list[], size_t amount)
  259. {
  260. for (size_t i=0; i < amount; i++)
  261. addEntryToSet(setName, i, "music/" + list[i]);
  262. };
  263. fillSet("enemy-turn", setEnemy, ARRAY_COUNT(setEnemy));
  264. fillSet("battle", setBattle, ARRAY_COUNT(setBattle));
  265. JsonNode terrains(ResourceID("config/terrains.json"));
  266. for (auto entry : terrains.Struct())
  267. {
  268. int terrIndex = vstd::find_pos(GameConstants::TERRAIN_NAMES, entry.first);
  269. addEntryToSet("terrain", terrIndex, "Music/" + entry.second["music"].String());
  270. }
  271. }
  272. void CMusicHandler::addEntryToSet(std::string set, int musicID, std::string musicURI)
  273. {
  274. musicsSet[set][musicID] = musicURI;
  275. }
  276. void CMusicHandler::init()
  277. {
  278. CAudioBase::init();
  279. if (initialized)
  280. Mix_HookMusicFinished(musicFinishedCallbackC);
  281. }
  282. void CMusicHandler::release()
  283. {
  284. if (initialized)
  285. {
  286. boost::mutex::scoped_lock guard(musicMutex);
  287. Mix_HookMusicFinished(nullptr);
  288. current.reset();
  289. next.reset();
  290. }
  291. CAudioBase::release();
  292. }
  293. void CMusicHandler::playMusic(std::string musicURI, bool loop)
  294. {
  295. if (current && current->isTrack( musicURI))
  296. return;
  297. queueNext(this, "", musicURI, loop);
  298. }
  299. void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
  300. {
  301. auto selectedSet = musicsSet.find(whichSet);
  302. if (selectedSet == musicsSet.end())
  303. {
  304. logGlobal->errorStream() << "Error: playing music from non-existing set: " << whichSet;
  305. return;
  306. }
  307. if (current && current->isSet(whichSet))
  308. return;
  309. // in this mode - play random track from set
  310. queueNext(this, whichSet, "", loop);
  311. }
  312. void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loop)
  313. {
  314. auto selectedSet = musicsSet.find(whichSet);
  315. if (selectedSet == musicsSet.end())
  316. {
  317. logGlobal->errorStream() << "Error: playing music from non-existing set: " << whichSet;
  318. return;
  319. }
  320. auto selectedEntry = selectedSet->second.find(entryID);
  321. if (selectedEntry == selectedSet->second.end())
  322. {
  323. logGlobal->errorStream() << "Error: playing non-existing entry " << entryID << " from set: " << whichSet;
  324. return;
  325. }
  326. if (current && current->isTrack( selectedEntry->second))
  327. return;
  328. // in this mode - play specific track from set
  329. queueNext(this, "", selectedEntry->second, loop);
  330. }
  331. void CMusicHandler::queueNext(unique_ptr<MusicEntry> queued)
  332. {
  333. if (!initialized)
  334. return;
  335. boost::mutex::scoped_lock guard(musicMutex);
  336. next = std::move(queued);
  337. if (current.get() == nullptr || !current->stop(1000))
  338. {
  339. current.reset(next.release());
  340. current->play();
  341. }
  342. }
  343. void CMusicHandler::queueNext(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped)
  344. {
  345. try
  346. {
  347. queueNext(make_unique<MusicEntry>(owner, setName, musicURI, looped));
  348. }
  349. catch(std::exception &e)
  350. {
  351. logGlobal->errorStream() << "Failed to queue music. setName=" << setName << "\tmusicURI=" << musicURI;
  352. logGlobal->errorStream() << "Exception: " << e.what();
  353. }
  354. }
  355. void CMusicHandler::stopMusic(int fade_ms)
  356. {
  357. if (!initialized)
  358. return;
  359. boost::mutex::scoped_lock guard(musicMutex);
  360. if (current.get() != nullptr)
  361. current->stop(fade_ms);
  362. next.reset();
  363. }
  364. void CMusicHandler::setVolume(ui32 percent)
  365. {
  366. CAudioBase::setVolume(percent);
  367. if (initialized)
  368. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  369. }
  370. void CMusicHandler::musicFinishedCallback(void)
  371. {
  372. boost::mutex::scoped_lock guard(musicMutex);
  373. if (current.get() != nullptr)
  374. {
  375. //return if current music still not finished
  376. if (current->play())
  377. return;
  378. else
  379. current.reset();
  380. }
  381. if (current.get() == nullptr && next.get() != nullptr)
  382. {
  383. current.reset(next.release());
  384. current->play();
  385. }
  386. }
  387. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
  388. owner(owner),
  389. music(nullptr),
  390. musicFile(nullptr),
  391. loop(looped ? -1 : 1),
  392. setName(setName)
  393. {
  394. if (!musicURI.empty())
  395. load(musicURI);
  396. }
  397. MusicEntry::~MusicEntry()
  398. {
  399. logGlobal->traceStream()<<"Del-ing music file "<<currentName;
  400. if (music)
  401. Mix_FreeMusic(music);
  402. }
  403. void MusicEntry::load(std::string musicURI)
  404. {
  405. if (music)
  406. {
  407. logGlobal->traceStream()<<"Del-ing music file "<<currentName;
  408. Mix_FreeMusic(music);
  409. music = nullptr;
  410. }
  411. currentName = musicURI;
  412. logGlobal->traceStream()<<"Loading music file "<<musicURI;
  413. data = CResourceHandler::get()->load(ResourceID(musicURI, EResType::MUSIC))->readAll();
  414. musicFile = SDL_RWFromConstMem(data.first.get(), data.second);
  415. music = Mix_LoadMUS_RW(musicFile);
  416. if(!music)
  417. {
  418. SDL_FreeRW(musicFile);
  419. musicFile = nullptr;
  420. logGlobal->warnStream() << "Warning: Cannot open " << currentName << ": " << Mix_GetError();
  421. return;
  422. }
  423. #ifdef _WIN32
  424. //The assertion will fail if old MSVC libraries pack .dll is used
  425. assert(Mix_GetMusicType(music) != MUS_MP3);
  426. #endif
  427. }
  428. bool MusicEntry::play()
  429. {
  430. if (!(loop--) && music) //already played once - return
  431. return false;
  432. if (!setName.empty())
  433. {
  434. auto set = owner->musicsSet[setName];
  435. size_t entryID = rand() % set.size();
  436. auto iterator = set.begin();
  437. std::advance(iterator, entryID);
  438. load(iterator->second);
  439. }
  440. logGlobal->traceStream()<<"Playing music file "<<currentName;
  441. if(Mix_PlayMusic(music, 1) == -1)
  442. {
  443. logGlobal->errorStream() << "Unable to play music (" << Mix_GetError() << ")";
  444. return false;
  445. }
  446. return true;
  447. }
  448. bool MusicEntry::stop(int fade_ms)
  449. {
  450. if (Mix_PlayingMusic())
  451. {
  452. logGlobal->traceStream()<<"Stoping music file "<<currentName;
  453. loop = 0;
  454. Mix_FadeOutMusic(fade_ms);
  455. return true;
  456. }
  457. return false;
  458. }
  459. bool MusicEntry::isSet(std::string set)
  460. {
  461. return !setName.empty() && set == setName;
  462. }
  463. bool MusicEntry::isTrack(std::string track)
  464. {
  465. return setName.empty() && track == currentName;
  466. }