CMusicHandler.cpp 13 KB

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