CSoundHandler.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 "CSoundHandler.h"
  12. #include "../gui/CGuiHandler.h"
  13. #include "../CGameInfo.h"
  14. #include "../lib/filesystem/Filesystem.h"
  15. #include "../lib/CRandomGenerator.h"
  16. #include <SDL_mixer.h>
  17. #define VCMI_SOUND_NAME(x)
  18. #define VCMI_SOUND_FILE(y) #y,
  19. // sounds mapped to soundBase enum
  20. static const std::string soundsList[] = {
  21. "", // invalid
  22. "", // todo
  23. VCMI_SOUND_LIST
  24. };
  25. #undef VCMI_SOUND_NAME
  26. #undef VCMI_SOUND_FILE
  27. void CSoundHandler::onVolumeChange(const JsonNode & volumeNode)
  28. {
  29. setVolume(volumeNode.Integer());
  30. }
  31. CSoundHandler::CSoundHandler():
  32. listener(settings.listen["general"]["sound"]),
  33. ambientConfig(JsonPath::builtin("config/ambientSounds.json"))
  34. {
  35. listener(std::bind(&CSoundHandler::onVolumeChange, this, _1));
  36. if(ambientConfig["allocateChannels"].isNumber())
  37. Mix_AllocateChannels(ambientConfig["allocateChannels"].Integer());
  38. if(isInitialized())
  39. {
  40. Mix_ChannelFinished([](int channel)
  41. {
  42. if (CCS)
  43. {
  44. CCS->soundh->soundFinishedCallback(channel);
  45. }
  46. });
  47. }
  48. }
  49. CSoundHandler::~CSoundHandler()
  50. {
  51. if(isInitialized())
  52. {
  53. Mix_HaltChannel(-1);
  54. for(auto & chunk : soundChunks)
  55. {
  56. if(chunk.second.first)
  57. Mix_FreeChunk(chunk.second.first);
  58. }
  59. }
  60. }
  61. // Allocate an SDL chunk and cache it.
  62. Mix_Chunk * CSoundHandler::GetSoundChunk(const AudioPath & sound, bool cache)
  63. {
  64. try
  65. {
  66. if(cache && soundChunks.find(sound) != soundChunks.end())
  67. return soundChunks[sound].first;
  68. auto data = CResourceHandler::get()->load(sound.addPrefix("SOUNDS/"))->readAll();
  69. SDL_RWops * ops = SDL_RWFromMem(data.first.get(), data.second);
  70. Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  71. if(cache)
  72. soundChunks.insert({sound, std::make_pair(chunk, std::move(data.first))});
  73. return chunk;
  74. }
  75. catch(std::exception & e)
  76. {
  77. logGlobal->warn("Cannot get sound %s chunk: %s", sound.getOriginalName(), e.what());
  78. return nullptr;
  79. }
  80. }
  81. Mix_Chunk * CSoundHandler::GetSoundChunk(std::pair<std::unique_ptr<ui8[]>, si64> & data, bool cache)
  82. {
  83. try
  84. {
  85. std::vector<ui8> startBytes = std::vector<ui8>(data.first.get(), data.first.get() + std::min(static_cast<si64>(100), data.second));
  86. if(cache && soundChunksRaw.find(startBytes) != soundChunksRaw.end())
  87. return soundChunksRaw[startBytes].first;
  88. SDL_RWops * ops = SDL_RWFromMem(data.first.get(), data.second);
  89. Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  90. if(cache)
  91. soundChunksRaw.insert({startBytes, std::make_pair(chunk, std::move(data.first))});
  92. return chunk;
  93. }
  94. catch(std::exception & e)
  95. {
  96. logGlobal->warn("Cannot get sound chunk: %s", e.what());
  97. return nullptr;
  98. }
  99. }
  100. int CSoundHandler::ambientDistToVolume(int distance) const
  101. {
  102. const auto & distancesVector = ambientConfig["distances"].Vector();
  103. if(distance >= distancesVector.size())
  104. return 0;
  105. int volumeByDistance = static_cast<int>(distancesVector[distance].Integer());
  106. return volumeByDistance * ambientConfig["volume"].Integer() / 100;
  107. }
  108. void CSoundHandler::ambientStopSound(const AudioPath & soundId)
  109. {
  110. stopSound(ambientChannels[soundId]);
  111. setChannelVolume(ambientChannels[soundId], volume);
  112. }
  113. uint32_t CSoundHandler::getSoundDurationMilliseconds(const AudioPath & sound)
  114. {
  115. if(!isInitialized() || sound.empty())
  116. return 0;
  117. auto resourcePath = sound.addPrefix("SOUNDS/");
  118. if(!CResourceHandler::get()->existsResource(resourcePath))
  119. return 0;
  120. auto data = CResourceHandler::get()->load(resourcePath)->readAll();
  121. uint32_t milliseconds = 0;
  122. Mix_Chunk * chunk = Mix_LoadWAV_RW(SDL_RWFromMem(data.first.get(), data.second), 1);
  123. int freq = 0;
  124. Uint16 fmt = 0;
  125. int chans = 0;
  126. if(!Mix_QuerySpec(&freq, &fmt, &chans))
  127. return 0;
  128. if(chunk != nullptr)
  129. {
  130. Uint32 points = (chunk->alen / ((fmt & 0xFF) / 8));
  131. Uint32 frames = (points / chans);
  132. milliseconds = ((frames * 1000) / freq);
  133. Mix_FreeChunk(chunk);
  134. }
  135. return milliseconds;
  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 = AudioPath::builtin(soundsList[soundID]);
  142. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound.getOriginalName());
  143. return playSound(sound, repeats, true);
  144. }
  145. int CSoundHandler::playSound(const AudioPath & sound, int repeats, bool cache)
  146. {
  147. if(!isInitialized() || 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.getOriginalName(), Mix_GetError());
  157. if(!cache)
  158. Mix_FreeChunk(chunk);
  159. }
  160. else if(cache)
  161. initCallback(channel);
  162. else
  163. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  164. }
  165. else
  166. channel = -1;
  167. return channel;
  168. }
  169. int CSoundHandler::playSound(std::pair<std::unique_ptr<ui8[]>, si64> & data, int repeats, bool cache)
  170. {
  171. int channel = -1;
  172. if(Mix_Chunk * chunk = GetSoundChunk(data, cache))
  173. {
  174. channel = Mix_PlayChannel(-1, chunk, repeats);
  175. if(channel == -1)
  176. {
  177. logGlobal->error("Unable to play sound, error %s", Mix_GetError());
  178. if(!cache)
  179. Mix_FreeChunk(chunk);
  180. }
  181. else if(cache)
  182. initCallback(channel);
  183. else
  184. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  185. }
  186. return channel;
  187. }
  188. // Helper. Randomly select a sound from an array and play it
  189. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> & sound_vec)
  190. {
  191. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  192. }
  193. void CSoundHandler::stopSound(int handler)
  194. {
  195. if(isInitialized() && handler != -1)
  196. Mix_HaltChannel(handler);
  197. }
  198. ui32 CSoundHandler::getVolume() const
  199. {
  200. return volume;
  201. }
  202. // Sets the sound volume, from 0 (mute) to 100
  203. void CSoundHandler::setVolume(ui32 percent)
  204. {
  205. volume = std::min(100u, percent);
  206. if(isInitialized())
  207. {
  208. setChannelVolume(-1, volume);
  209. for(const auto & channel : channelVolumes)
  210. updateChannelVolume(channel.first);
  211. }
  212. }
  213. void CSoundHandler::updateChannelVolume(int channel)
  214. {
  215. if(channelVolumes.count(channel))
  216. setChannelVolume(channel, getVolume() * channelVolumes[channel] / 100);
  217. else
  218. setChannelVolume(channel, getVolume());
  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. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  228. auto 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.push_back(function);
  234. }
  235. void CSoundHandler::resetCallback(int channel)
  236. {
  237. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  238. callbacks.erase(channel);
  239. }
  240. void CSoundHandler::soundFinishedCallback(int channel)
  241. {
  242. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  243. if(callbacks.count(channel) == 0)
  244. return;
  245. // store callbacks from container locally - SDL might reuse this channel for another sound
  246. // but do actually execution in separate thread, to avoid potential deadlocks in case if callback requires locks of its own
  247. auto callback = callbacks.at(channel);
  248. callbacks.erase(channel);
  249. if(!callback.empty())
  250. {
  251. GH.dispatchMainThread(
  252. [callback]()
  253. {
  254. for(const auto & entry : callback)
  255. entry();
  256. }
  257. );
  258. }
  259. }
  260. void CSoundHandler::initCallback(int channel)
  261. {
  262. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  263. assert(callbacks.count(channel) == 0);
  264. callbacks[channel] = {};
  265. }
  266. void CSoundHandler::initCallback(int channel, const std::function<void()> & function)
  267. {
  268. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  269. assert(callbacks.count(channel) == 0);
  270. callbacks[channel].push_back(function);
  271. }
  272. int CSoundHandler::ambientGetRange() const
  273. {
  274. return ambientConfig["range"].Integer();
  275. }
  276. void CSoundHandler::ambientUpdateChannels(std::map<AudioPath, int> soundsArg)
  277. {
  278. boost::mutex::scoped_lock guard(mutex);
  279. std::vector<AudioPath> stoppedSounds;
  280. for(const auto & pair : ambientChannels)
  281. {
  282. const auto & soundId = pair.first;
  283. const int channel = pair.second;
  284. if(!vstd::contains(soundsArg, soundId))
  285. {
  286. ambientStopSound(soundId);
  287. stoppedSounds.push_back(soundId);
  288. }
  289. else
  290. {
  291. int channelVolume = ambientDistToVolume(soundsArg[soundId]);
  292. channelVolumes[channel] = channelVolume;
  293. updateChannelVolume(channel);
  294. }
  295. }
  296. for(const auto & soundId : stoppedSounds)
  297. {
  298. channelVolumes.erase(ambientChannels[soundId]);
  299. ambientChannels.erase(soundId);
  300. }
  301. for(const auto & pair : soundsArg)
  302. {
  303. const auto & soundId = pair.first;
  304. const int distance = pair.second;
  305. if(!vstd::contains(ambientChannels, soundId))
  306. {
  307. int channel = playSound(soundId, -1);
  308. int channelVolume = ambientDistToVolume(distance);
  309. channelVolumes[channel] = channelVolume;
  310. updateChannelVolume(channel);
  311. ambientChannels[soundId] = channel;
  312. }
  313. }
  314. }
  315. void CSoundHandler::ambientStopAllChannels()
  316. {
  317. boost::mutex::scoped_lock guard(mutex);
  318. for(const auto & ch : ambientChannels)
  319. {
  320. ambientStopSound(ch.first);
  321. }
  322. channelVolumes.clear();
  323. ambientChannels.clear();
  324. }