CMusicHandler.cpp 13 KB

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