CMusicHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 <SDL.h>
  13. #include "CMusicHandler.h"
  14. #include "CGameInfo.h"
  15. #include "SDLRWwrapper.h"
  16. #include "../lib/JsonNode.h"
  17. #include "../lib/GameConstants.h"
  18. #include "../lib/filesystem/Filesystem.h"
  19. #include "../lib/StringConstants.h"
  20. #include "../lib/CRandomGenerator.h"
  21. #include "../lib/VCMIDirs.h"
  22. #include "../lib/Terrain.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()
  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(!(CCS->soundh->initialized && CCS->musich->initialized))
  56. Mix_CloseAudio();
  57. initialized = false;
  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((ui32)volumeNode.Float());
  68. }
  69. CSoundHandler::CSoundHandler():
  70. listener(settings.listen["general"]["sound"]),
  71. ambientConfig(JsonNode(ResourceID("config/ambientSounds.json")))
  72. {
  73. allTilesSource = ambientConfig["allTilesSource"].Bool();
  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. battleIntroSounds =
  82. {
  83. soundBase::battle00, soundBase::battle01,
  84. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  85. soundBase::battle05, soundBase::battle06, soundBase::battle07
  86. };
  87. //predefine terrain set
  88. //TODO: support custom sounds for new terrains and load from json
  89. horseSounds =
  90. {
  91. {Terrain::DIRT, soundBase::horseDirt},
  92. {Terrain::SAND, soundBase::horseSand},
  93. {Terrain::GRASS, soundBase::horseGrass},
  94. {Terrain::SNOW, soundBase::horseSnow},
  95. {Terrain::SWAMP, soundBase::horseSwamp},
  96. {Terrain::ROUGH, soundBase::horseRough},
  97. {Terrain::SUBTERRANEAN, soundBase::horseSubterranean},
  98. {Terrain::LAVA, soundBase::horseLava},
  99. {Terrain::WATER, soundBase::horseWater},
  100. {Terrain::ROCK, soundBase::horseRock}
  101. };
  102. }
  103. void CSoundHandler::loadHorseSounds()
  104. {
  105. const auto & terrains = CGI->terrainTypeHandler->terrains();
  106. for(const auto & terrain : terrains)
  107. {
  108. //since all sounds are hardcoded, let's keep it
  109. if(vstd::contains(horseSounds, terrain.id))
  110. continue;
  111. //Use already existing horse sound
  112. horseSounds[terrain.id] = horseSounds.at(terrains[terrain.id].horseSoundId);
  113. }
  114. }
  115. void CSoundHandler::init()
  116. {
  117. CAudioBase::init();
  118. if(ambientConfig["allocateChannels"].isNumber())
  119. Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
  120. if (initialized)
  121. {
  122. // Load sounds
  123. Mix_ChannelFinished(soundFinishedCallbackC);
  124. }
  125. }
  126. void CSoundHandler::release()
  127. {
  128. if (initialized)
  129. {
  130. Mix_HaltChannel(-1);
  131. for (auto &chunk : soundChunks)
  132. {
  133. if (chunk.second.first)
  134. Mix_FreeChunk(chunk.second.first);
  135. }
  136. }
  137. CAudioBase::release();
  138. }
  139. // Allocate an SDL chunk and cache it.
  140. Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound, bool cache)
  141. {
  142. try
  143. {
  144. if (cache && soundChunks.find(sound) != soundChunks.end())
  145. return soundChunks[sound].first;
  146. auto data = CResourceHandler::get()->load(ResourceID(std::string("SOUNDS/") + sound, EResType::SOUND))->readAll();
  147. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  148. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  149. if (cache)
  150. soundChunks.insert(std::pair<std::string, CachedChunk>(sound, std::make_pair (chunk, std::move (data.first))));
  151. return chunk;
  152. }
  153. catch(std::exception &e)
  154. {
  155. logGlobal->warn("Cannot get sound %s chunk: %s", sound, e.what());
  156. return nullptr;
  157. }
  158. }
  159. int CSoundHandler::ambientDistToVolume(int distance) const
  160. {
  161. if(distance >= ambientConfig["distances"].Vector().size())
  162. return 0;
  163. int volume = static_cast<int>(ambientConfig["distances"].Vector()[distance].Integer());
  164. return volume * (int)ambientConfig["volume"].Integer() * getVolume() / 10000;
  165. }
  166. void CSoundHandler::ambientStopSound(std::string soundId)
  167. {
  168. stopSound(ambientChannels[soundId]);
  169. setChannelVolume(ambientChannels[soundId], volume);
  170. }
  171. // Plays a sound, and return its channel so we can fade it out later
  172. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  173. {
  174. assert(soundID < soundBase::sound_after_last);
  175. auto sound = sounds[soundID];
  176. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound);
  177. return playSound(sound, repeats, true);
  178. }
  179. int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
  180. {
  181. if (!initialized || sound.empty())
  182. return -1;
  183. int channel;
  184. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  185. if (chunk)
  186. {
  187. channel = Mix_PlayChannel(-1, chunk, repeats);
  188. if (channel == -1)
  189. {
  190. logGlobal->error("Unable to play sound file %s , error %s", sound, Mix_GetError());
  191. if (!cache)
  192. Mix_FreeChunk(chunk);
  193. }
  194. else if (cache)
  195. callbacks[channel];
  196. else
  197. callbacks[channel] = [chunk](){ Mix_FreeChunk(chunk);};
  198. }
  199. else
  200. channel = -1;
  201. return channel;
  202. }
  203. // Helper. Randomly select a sound from an array and play it
  204. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  205. {
  206. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  207. }
  208. void CSoundHandler::stopSound( int handler )
  209. {
  210. if (initialized && handler != -1)
  211. Mix_HaltChannel(handler);
  212. }
  213. // Sets the sound volume, from 0 (mute) to 100
  214. void CSoundHandler::setVolume(ui32 percent)
  215. {
  216. CAudioBase::setVolume(percent);
  217. if (initialized)
  218. setChannelVolume(-1, volume);
  219. }
  220. // Sets the sound volume, from 0 (mute) to 100
  221. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  222. {
  223. Mix_Volume(channel, (MIX_MAX_VOLUME * percent)/100);
  224. }
  225. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  226. {
  227. std::map<int, std::function<void()> >::iterator iter;
  228. iter = callbacks.find(channel);
  229. //channel not found. It may have finished so fire callback now
  230. if(iter == callbacks.end())
  231. function();
  232. else
  233. iter->second = function;
  234. }
  235. void CSoundHandler::soundFinishedCallback(int channel)
  236. {
  237. std::map<int, std::function<void()> >::iterator iter;
  238. iter = callbacks.find(channel);
  239. if (iter == callbacks.end())
  240. return;
  241. auto callback = std::move(iter->second);
  242. callbacks.erase(iter);
  243. if (callback)
  244. callback();
  245. }
  246. int CSoundHandler::ambientGetRange() const
  247. {
  248. return static_cast<int>(ambientConfig["range"].Integer());
  249. }
  250. bool CSoundHandler::ambientCheckVisitable() const
  251. {
  252. return !allTilesSource;
  253. }
  254. void CSoundHandler::ambientUpdateChannels(std::map<std::string, int> soundsArg)
  255. {
  256. boost::mutex::scoped_lock guard(mutex);
  257. std::vector<std::string> stoppedSounds;
  258. for(auto & pair : ambientChannels)
  259. {
  260. if(!vstd::contains(soundsArg, pair.first))
  261. {
  262. ambientStopSound(pair.first);
  263. stoppedSounds.push_back(pair.first);
  264. }
  265. else
  266. {
  267. CCS->soundh->setChannelVolume(pair.second, ambientDistToVolume(soundsArg[pair.first]));
  268. }
  269. }
  270. for(auto soundId : stoppedSounds)
  271. ambientChannels.erase(soundId);
  272. for(auto & pair : soundsArg)
  273. {
  274. if(!vstd::contains(ambientChannels, pair.first))
  275. {
  276. int channel = CCS->soundh->playSound(pair.first, -1);
  277. CCS->soundh->setChannelVolume(channel, ambientDistToVolume(pair.second));
  278. CCS->soundh->ambientChannels.insert(std::make_pair(pair.first, channel));
  279. }
  280. }
  281. }
  282. void CSoundHandler::ambientStopAllChannels()
  283. {
  284. boost::mutex::scoped_lock guard(mutex);
  285. for(auto ch : ambientChannels)
  286. {
  287. ambientStopSound(ch.first);
  288. }
  289. ambientChannels.clear();
  290. }
  291. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  292. {
  293. setVolume((ui32)volumeNode.Float());
  294. }
  295. CMusicHandler::CMusicHandler():
  296. listener(settings.listen["general"]["music"])
  297. {
  298. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  299. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourceID & id) -> bool
  300. {
  301. if(id.getType() != EResType::MUSIC)
  302. return false;
  303. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  304. return false;
  305. logGlobal->trace("Found music file %s", id.getName());
  306. return true;
  307. });
  308. for(const ResourceID & file : mp3files)
  309. {
  310. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  311. addEntryToSet("battle", file.getName(), file.getName());
  312. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  313. addEntryToSet("enemy-turn", file.getName(), file.getName());
  314. }
  315. }
  316. void CMusicHandler::loadTerrainSounds()
  317. {
  318. for (const auto & terrain : CGI->terrainTypeHandler->terrains())
  319. {
  320. addEntryToSet("terrain", terrain.name, "Music/" + terrain.musicFilename);
  321. }
  322. }
  323. void CMusicHandler::addEntryToSet(const std::string & set, const std::string & musicID, const std::string & musicURI)
  324. {
  325. musicsSet[set][musicID] = musicURI;
  326. }
  327. void CMusicHandler::init()
  328. {
  329. CAudioBase::init();
  330. if (initialized)
  331. Mix_HookMusicFinished(musicFinishedCallbackC);
  332. }
  333. void CMusicHandler::release()
  334. {
  335. if (initialized)
  336. {
  337. boost::mutex::scoped_lock guard(mutex);
  338. Mix_HookMusicFinished(nullptr);
  339. current.reset();
  340. next.reset();
  341. }
  342. CAudioBase::release();
  343. }
  344. void CMusicHandler::playMusic(const std::string & musicURI, bool loop, bool fromStart)
  345. {
  346. if (current && current->isTrack(musicURI))
  347. return;
  348. queueNext(this, "", musicURI, loop, fromStart);
  349. }
  350. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop, bool fromStart)
  351. {
  352. auto selectedSet = musicsSet.find(whichSet);
  353. if (selectedSet == musicsSet.end())
  354. {
  355. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  356. return;
  357. }
  358. if (current && current->isSet(whichSet))
  359. return;
  360. // in this mode - play random track from set
  361. queueNext(this, whichSet, "", loop, fromStart);
  362. }
  363. void CMusicHandler::playMusicFromSet(const std::string & whichSet, const std::string & entryID, bool loop, bool fromStart)
  364. {
  365. auto selectedSet = musicsSet.find(whichSet);
  366. if (selectedSet == musicsSet.end())
  367. {
  368. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  369. return;
  370. }
  371. auto selectedEntry = selectedSet->second.find(entryID);
  372. if (selectedEntry == selectedSet->second.end())
  373. {
  374. logGlobal->error("Error: playing non-existing entry %s from set: %s", entryID, whichSet);
  375. return;
  376. }
  377. if (current && current->isTrack(selectedEntry->second))
  378. return;
  379. // in this mode - play specific track from set
  380. queueNext(this, "", selectedEntry->second, loop, fromStart);
  381. }
  382. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  383. {
  384. if (!initialized)
  385. return;
  386. boost::mutex::scoped_lock guard(mutex);
  387. next = std::move(queued);
  388. if (current.get() == nullptr || !current->stop(1000))
  389. {
  390. current.reset(next.release());
  391. current->play();
  392. }
  393. }
  394. void CMusicHandler::queueNext(CMusicHandler *owner, const std::string & setName, const std::string & musicURI, bool looped, bool fromStart)
  395. {
  396. try
  397. {
  398. queueNext(make_unique<MusicEntry>(owner, setName, musicURI, looped, fromStart));
  399. }
  400. catch(std::exception &e)
  401. {
  402. logGlobal->error("Failed to queue music. setName=%s\tmusicURI=%s", setName, musicURI);
  403. logGlobal->error("Exception: %s", e.what());
  404. }
  405. }
  406. void CMusicHandler::stopMusic(int fade_ms)
  407. {
  408. if (!initialized)
  409. return;
  410. boost::mutex::scoped_lock guard(mutex);
  411. if (current.get() != nullptr)
  412. current->stop(fade_ms);
  413. next.reset();
  414. }
  415. void CMusicHandler::setVolume(ui32 percent)
  416. {
  417. CAudioBase::setVolume(percent);
  418. if (initialized)
  419. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  420. }
  421. void CMusicHandler::musicFinishedCallback()
  422. {
  423. boost::mutex::scoped_lock guard(mutex);
  424. if (current.get() != nullptr)
  425. {
  426. //return if current music still not finished
  427. if (current->play())
  428. return;
  429. else
  430. current.reset();
  431. }
  432. if (current.get() == nullptr && next.get() != nullptr)
  433. {
  434. current.reset(next.release());
  435. current->play();
  436. }
  437. }
  438. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped, bool fromStart):
  439. owner(owner),
  440. music(nullptr),
  441. startTime(uint32_t(-1)),
  442. startPosition(0),
  443. loop(looped ? -1 : 1),
  444. fromStart(fromStart),
  445. setName(std::move(setName))
  446. {
  447. if (!musicURI.empty())
  448. load(std::move(musicURI));
  449. }
  450. MusicEntry::~MusicEntry()
  451. {
  452. logGlobal->trace("Del-ing music file %s", currentName);
  453. if (music)
  454. Mix_FreeMusic(music);
  455. }
  456. void MusicEntry::load(std::string musicURI)
  457. {
  458. if (music)
  459. {
  460. logGlobal->trace("Del-ing music file %s", currentName);
  461. Mix_FreeMusic(music);
  462. music = nullptr;
  463. }
  464. currentName = musicURI;
  465. logGlobal->trace("Loading music file %s", musicURI);
  466. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(ResourceID(std::move(musicURI), EResType::MUSIC)));
  467. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  468. if(!music)
  469. {
  470. logGlobal->warn("Warning: Cannot open %s: %s", currentName, Mix_GetError());
  471. return;
  472. }
  473. }
  474. bool MusicEntry::play()
  475. {
  476. if (!(loop--) && music) //already played once - return
  477. return false;
  478. if (!setName.empty())
  479. {
  480. const auto & set = owner->musicsSet[setName];
  481. load(RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault())->second);
  482. }
  483. logGlobal->trace("Playing music file %s", currentName);
  484. if ( !fromStart && owner->trackPositions.count(currentName) > 0 && owner->trackPositions[currentName] > 0)
  485. {
  486. float timeToStart = owner->trackPositions[currentName];
  487. startPosition = std::round(timeToStart * 1000);
  488. if (Mix_FadeInMusicPos(music, 1, 1000, timeToStart) == -1)
  489. {
  490. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  491. return false;
  492. }
  493. }
  494. else if(Mix_PlayMusic(music, 1) == -1)
  495. {
  496. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  497. return false;
  498. }
  499. startTime = SDL_GetTicks();
  500. return true;
  501. }
  502. bool MusicEntry::stop(int fade_ms)
  503. {
  504. if (Mix_PlayingMusic())
  505. {
  506. loop = 0;
  507. uint32_t endTime = SDL_GetTicks();
  508. assert(startTime != uint32_t(-1));
  509. float playDuration = (endTime - startTime + startPosition) / 1000.f;
  510. owner->trackPositions[currentName] = playDuration;
  511. logGlobal->info("Stopping music file %s at %f", currentName, playDuration);
  512. Mix_FadeOutMusic(fade_ms);
  513. return true;
  514. }
  515. return false;
  516. }
  517. bool MusicEntry::isSet(std::string set)
  518. {
  519. return !setName.empty() && set == setName;
  520. }
  521. bool MusicEntry::isTrack(std::string track)
  522. {
  523. return setName.empty() && track == currentName;
  524. }