CMusicHandler.cpp 15 KB

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