CMusicHandler.cpp 12 KB

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