CMusicHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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/JsonNode.h"
  16. #include "../lib/GameConstants.h"
  17. #include "../lib/filesystem/Filesystem.h"
  18. #include "../lib/StringConstants.h"
  19. #include "../lib/CRandomGenerator.h"
  20. #include "../lib/VCMIDirs.h"
  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()
  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->error("Mix_OpenAudio error: %s", Mix_GetError());
  47. return;
  48. }
  49. initialized = true;
  50. }
  51. void CAudioBase::release()
  52. {
  53. if(!(CCS->soundh->initialized && CCS->musich->initialized))
  54. Mix_CloseAudio();
  55. initialized = false;
  56. }
  57. void CAudioBase::setVolume(ui32 percent)
  58. {
  59. if (percent > 100)
  60. percent = 100;
  61. volume = percent;
  62. }
  63. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  64. {
  65. setVolume((ui32)volumeNode.Float());
  66. }
  67. CSoundHandler::CSoundHandler():
  68. listener(settings.listen["general"]["sound"]),
  69. ambientConfig(JsonNode(ResourceID("config/ambientSounds.json")))
  70. {
  71. allTilesSource = ambientConfig["allTilesSource"].Bool();
  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(ambientConfig["allocateChannels"].isNumber())
  97. Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
  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(), (int)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. int CSoundHandler::ambientDistToVolume(int distance) const
  138. {
  139. if(distance >= ambientConfig["distances"].Vector().size())
  140. return 0;
  141. int volume = static_cast<int>(ambientConfig["distances"].Vector()[distance].Integer());
  142. return volume * (int)ambientConfig["volume"].Integer() * getVolume() / 10000;
  143. }
  144. void CSoundHandler::ambientStopSound(std::string soundId)
  145. {
  146. stopSound(ambientChannels[soundId]);
  147. setChannelVolume(ambientChannels[soundId], volume);
  148. }
  149. // Plays a sound, and return its channel so we can fade it out later
  150. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  151. {
  152. assert(soundID < soundBase::sound_after_last);
  153. auto sound = sounds[soundID];
  154. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound);
  155. return playSound(sound, repeats, true);
  156. }
  157. int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
  158. {
  159. if (!initialized || sound.empty())
  160. return -1;
  161. int channel;
  162. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  163. if (chunk)
  164. {
  165. channel = Mix_PlayChannel(-1, chunk, repeats);
  166. if (channel == -1)
  167. {
  168. logGlobal->error("Unable to play sound file %s , error %s", sound, Mix_GetError());
  169. if (!cache)
  170. Mix_FreeChunk(chunk);
  171. }
  172. else if (cache)
  173. callbacks[channel];
  174. else
  175. callbacks[channel] = [chunk](){ Mix_FreeChunk(chunk);};
  176. }
  177. else
  178. channel = -1;
  179. return channel;
  180. }
  181. // Helper. Randomly select a sound from an array and play it
  182. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  183. {
  184. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  185. }
  186. void CSoundHandler::stopSound( int handler )
  187. {
  188. if (initialized && handler != -1)
  189. Mix_HaltChannel(handler);
  190. }
  191. // Sets the sound volume, from 0 (mute) to 100
  192. void CSoundHandler::setVolume(ui32 percent)
  193. {
  194. CAudioBase::setVolume(percent);
  195. if (initialized)
  196. setChannelVolume(-1, volume);
  197. }
  198. // Sets the sound volume, from 0 (mute) to 100
  199. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  200. {
  201. Mix_Volume(channel, (MIX_MAX_VOLUME * percent)/100);
  202. }
  203. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  204. {
  205. std::map<int, std::function<void()> >::iterator iter;
  206. iter = callbacks.find(channel);
  207. //channel not found. It may have finished so fire callback now
  208. if(iter == callbacks.end())
  209. function();
  210. else
  211. iter->second = function;
  212. }
  213. void CSoundHandler::soundFinishedCallback(int channel)
  214. {
  215. std::map<int, std::function<void()> >::iterator iter;
  216. iter = callbacks.find(channel);
  217. assert(iter != callbacks.end());
  218. if (iter->second)
  219. iter->second();
  220. callbacks.erase(iter);
  221. }
  222. int CSoundHandler::ambientGetRange() const
  223. {
  224. return static_cast<int>(ambientConfig["range"].Integer());
  225. }
  226. bool CSoundHandler::ambientCheckVisitable() const
  227. {
  228. return !allTilesSource;
  229. }
  230. void CSoundHandler::ambientUpdateChannels(std::map<std::string, int> soundsArg)
  231. {
  232. boost::mutex::scoped_lock guard(mutex);
  233. std::vector<std::string> stoppedSounds;
  234. for(auto & pair : ambientChannels)
  235. {
  236. if(!vstd::contains(soundsArg, pair.first))
  237. {
  238. ambientStopSound(pair.first);
  239. stoppedSounds.push_back(pair.first);
  240. }
  241. else
  242. {
  243. CCS->soundh->setChannelVolume(pair.second, ambientDistToVolume(soundsArg[pair.first]));
  244. }
  245. }
  246. for(auto soundId : stoppedSounds)
  247. ambientChannels.erase(soundId);
  248. for(auto & pair : soundsArg)
  249. {
  250. if(!vstd::contains(ambientChannels, pair.first))
  251. {
  252. int channel = CCS->soundh->playSound(pair.first, -1);
  253. CCS->soundh->setChannelVolume(channel, ambientDistToVolume(pair.second));
  254. CCS->soundh->ambientChannels.insert(std::make_pair(pair.first, channel));
  255. }
  256. }
  257. }
  258. void CSoundHandler::ambientStopAllChannels()
  259. {
  260. boost::mutex::scoped_lock guard(mutex);
  261. for(auto ch : ambientChannels)
  262. {
  263. ambientStopSound(ch.first);
  264. }
  265. ambientChannels.clear();
  266. }
  267. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  268. {
  269. setVolume((ui32)volumeNode.Float());
  270. }
  271. CMusicHandler::CMusicHandler():
  272. listener(settings.listen["general"]["music"])
  273. {
  274. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  275. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourceID & id) -> bool
  276. {
  277. if(id.getType() != EResType::MUSIC)
  278. return false;
  279. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  280. return false;
  281. logGlobal->trace("Found music file %s", id.getName());
  282. return true;
  283. });
  284. int battleMusicID = 0;
  285. int AIThemeID = 0;
  286. for(const ResourceID & file : mp3files)
  287. {
  288. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  289. addEntryToSet("battle", battleMusicID++, file.getName());
  290. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  291. addEntryToSet("enemy-turn", AIThemeID++, file.getName());
  292. }
  293. JsonNode terrains(ResourceID("config/terrains.json"));
  294. for (auto entry : terrains.Struct())
  295. {
  296. int terrIndex = vstd::find_pos(GameConstants::TERRAIN_NAMES, entry.first);
  297. addEntryToSet("terrain", terrIndex, "Music/" + entry.second["music"].String());
  298. }
  299. }
  300. void CMusicHandler::addEntryToSet(std::string set, int musicID, std::string musicURI)
  301. {
  302. musicsSet[set][musicID] = musicURI;
  303. }
  304. void CMusicHandler::init()
  305. {
  306. CAudioBase::init();
  307. if (initialized)
  308. Mix_HookMusicFinished(musicFinishedCallbackC);
  309. }
  310. void CMusicHandler::release()
  311. {
  312. if (initialized)
  313. {
  314. boost::mutex::scoped_lock guard(mutex);
  315. Mix_HookMusicFinished(nullptr);
  316. current.reset();
  317. next.reset();
  318. }
  319. CAudioBase::release();
  320. }
  321. void CMusicHandler::playMusic(std::string musicURI, bool loop)
  322. {
  323. if (current && current->isTrack(musicURI))
  324. return;
  325. queueNext(this, "", musicURI, loop);
  326. }
  327. void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
  328. {
  329. auto selectedSet = musicsSet.find(whichSet);
  330. if (selectedSet == musicsSet.end())
  331. {
  332. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  333. return;
  334. }
  335. if (current && current->isSet(whichSet))
  336. return;
  337. // in this mode - play random track from set
  338. queueNext(this, whichSet, "", loop);
  339. }
  340. void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loop)
  341. {
  342. auto selectedSet = musicsSet.find(whichSet);
  343. if (selectedSet == musicsSet.end())
  344. {
  345. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  346. return;
  347. }
  348. auto selectedEntry = selectedSet->second.find(entryID);
  349. if (selectedEntry == selectedSet->second.end())
  350. {
  351. logGlobal->error("Error: playing non-existing entry %d from set: %s", entryID, whichSet);
  352. return;
  353. }
  354. if (current && current->isTrack(selectedEntry->second))
  355. return;
  356. // in this mode - play specific track from set
  357. queueNext(this, "", selectedEntry->second, loop);
  358. }
  359. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  360. {
  361. if (!initialized)
  362. return;
  363. boost::mutex::scoped_lock guard(mutex);
  364. next = std::move(queued);
  365. if (current.get() == nullptr || !current->stop(1000))
  366. {
  367. current.reset(next.release());
  368. current->play();
  369. }
  370. }
  371. void CMusicHandler::queueNext(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped)
  372. {
  373. try
  374. {
  375. queueNext(make_unique<MusicEntry>(owner, setName, musicURI, looped));
  376. }
  377. catch(std::exception &e)
  378. {
  379. logGlobal->error("Failed to queue music. setName=%s\tmusicURI=%s", setName, musicURI);
  380. logGlobal->error("Exception: %s", e.what());
  381. }
  382. }
  383. void CMusicHandler::stopMusic(int fade_ms)
  384. {
  385. if (!initialized)
  386. return;
  387. boost::mutex::scoped_lock guard(mutex);
  388. if (current.get() != nullptr)
  389. current->stop(fade_ms);
  390. next.reset();
  391. }
  392. void CMusicHandler::setVolume(ui32 percent)
  393. {
  394. CAudioBase::setVolume(percent);
  395. if (initialized)
  396. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  397. }
  398. void CMusicHandler::musicFinishedCallback()
  399. {
  400. boost::mutex::scoped_lock guard(mutex);
  401. if (current.get() != nullptr)
  402. {
  403. //return if current music still not finished
  404. if (current->play())
  405. return;
  406. else
  407. current.reset();
  408. }
  409. if (current.get() == nullptr && next.get() != nullptr)
  410. {
  411. current.reset(next.release());
  412. current->play();
  413. }
  414. }
  415. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
  416. owner(owner),
  417. music(nullptr),
  418. loop(looped ? -1 : 1),
  419. setName(std::move(setName))
  420. {
  421. if (!musicURI.empty())
  422. load(std::move(musicURI));
  423. }
  424. MusicEntry::~MusicEntry()
  425. {
  426. logGlobal->trace("Del-ing music file %s", currentName);
  427. if (music)
  428. Mix_FreeMusic(music);
  429. }
  430. void MusicEntry::load(std::string musicURI)
  431. {
  432. if (music)
  433. {
  434. logGlobal->trace("Del-ing music file %s", currentName);
  435. Mix_FreeMusic(music);
  436. music = nullptr;
  437. }
  438. currentName = musicURI;
  439. logGlobal->trace("Loading music file %s", musicURI);
  440. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(ResourceID(std::move(musicURI), EResType::MUSIC)));
  441. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  442. if(!music)
  443. {
  444. logGlobal->warn("Warning: Cannot open %s: %s", currentName, Mix_GetError());
  445. return;
  446. }
  447. }
  448. bool MusicEntry::play()
  449. {
  450. if (!(loop--) && music) //already played once - return
  451. return false;
  452. if (!setName.empty())
  453. {
  454. auto set = owner->musicsSet[setName];
  455. load(RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault())->second);
  456. }
  457. logGlobal->trace("Playing music file %s", currentName);
  458. if(Mix_PlayMusic(music, 1) == -1)
  459. {
  460. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  461. return false;
  462. }
  463. return true;
  464. }
  465. bool MusicEntry::stop(int fade_ms)
  466. {
  467. if (Mix_PlayingMusic())
  468. {
  469. logGlobal->trace("Stopping music file %s", currentName);
  470. loop = 0;
  471. Mix_FadeOutMusic(fade_ms);
  472. return true;
  473. }
  474. return false;
  475. }
  476. bool MusicEntry::isSet(std::string set)
  477. {
  478. return !setName.empty() && set == setName;
  479. }
  480. bool MusicEntry::isTrack(std::string track)
  481. {
  482. return setName.empty() && track == currentName;
  483. }