CMusicHandler.cpp 12 KB

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