CSoundHandler.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. CCS->soundh->soundFinishedCallback(channel);
  43. });
  44. }
  45. }
  46. CSoundHandler::~CSoundHandler()
  47. {
  48. if(isInitialized())
  49. {
  50. Mix_HaltChannel(-1);
  51. for(auto & chunk : soundChunks)
  52. {
  53. if(chunk.second.first)
  54. Mix_FreeChunk(chunk.second.first);
  55. }
  56. }
  57. }
  58. // Allocate an SDL chunk and cache it.
  59. Mix_Chunk * CSoundHandler::GetSoundChunk(const AudioPath & sound, bool cache)
  60. {
  61. try
  62. {
  63. if(cache && soundChunks.find(sound) != soundChunks.end())
  64. return soundChunks[sound].first;
  65. auto data = CResourceHandler::get()->load(sound.addPrefix("SOUNDS/"))->readAll();
  66. SDL_RWops * ops = SDL_RWFromMem(data.first.get(), data.second);
  67. Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  68. if(cache)
  69. soundChunks.insert({sound, std::make_pair(chunk, std::move(data.first))});
  70. return chunk;
  71. }
  72. catch(std::exception & e)
  73. {
  74. logGlobal->warn("Cannot get sound %s chunk: %s", sound.getOriginalName(), e.what());
  75. return nullptr;
  76. }
  77. }
  78. Mix_Chunk * CSoundHandler::GetSoundChunk(std::pair<std::unique_ptr<ui8[]>, si64> & data, bool cache)
  79. {
  80. try
  81. {
  82. std::vector<ui8> startBytes = std::vector<ui8>(data.first.get(), data.first.get() + std::min(static_cast<si64>(100), data.second));
  83. if(cache && soundChunksRaw.find(startBytes) != soundChunksRaw.end())
  84. return soundChunksRaw[startBytes].first;
  85. SDL_RWops * ops = SDL_RWFromMem(data.first.get(), data.second);
  86. Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  87. if(cache)
  88. soundChunksRaw.insert({startBytes, std::make_pair(chunk, std::move(data.first))});
  89. return chunk;
  90. }
  91. catch(std::exception & e)
  92. {
  93. logGlobal->warn("Cannot get sound chunk: %s", e.what());
  94. return nullptr;
  95. }
  96. }
  97. int CSoundHandler::ambientDistToVolume(int distance) const
  98. {
  99. const auto & distancesVector = ambientConfig["distances"].Vector();
  100. if(distance >= distancesVector.size())
  101. return 0;
  102. int volumeByDistance = static_cast<int>(distancesVector[distance].Integer());
  103. return volumeByDistance * ambientConfig["volume"].Integer() / 100;
  104. }
  105. void CSoundHandler::ambientStopSound(const AudioPath & soundId)
  106. {
  107. stopSound(ambientChannels[soundId]);
  108. setChannelVolume(ambientChannels[soundId], volume);
  109. }
  110. uint32_t CSoundHandler::getSoundDurationMilliseconds(const AudioPath & sound)
  111. {
  112. if(!isInitialized() || sound.empty())
  113. return 0;
  114. auto resourcePath = sound.addPrefix("SOUNDS/");
  115. if(!CResourceHandler::get()->existsResource(resourcePath))
  116. return 0;
  117. auto data = CResourceHandler::get()->load(resourcePath)->readAll();
  118. SDL_AudioSpec spec;
  119. uint32_t audioLen;
  120. uint8_t * audioBuf;
  121. uint32_t milliseconds = 0;
  122. if(SDL_LoadWAV_RW(SDL_RWFromMem(data.first.get(), data.second), 1, &spec, &audioBuf, &audioLen) != nullptr)
  123. {
  124. SDL_FreeWAV(audioBuf);
  125. uint32_t sampleSize = SDL_AUDIO_BITSIZE(spec.format) / 8;
  126. uint32_t sampleCount = audioLen / sampleSize;
  127. uint32_t sampleLen = sampleCount / spec.channels;
  128. milliseconds = 1000 * sampleLen / spec.freq;
  129. }
  130. return milliseconds;
  131. }
  132. // Plays a sound, and return its channel so we can fade it out later
  133. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  134. {
  135. assert(soundID < soundBase::sound_after_last);
  136. auto sound = AudioPath::builtin(soundsList[soundID]);
  137. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound.getOriginalName());
  138. return playSound(sound, repeats, true);
  139. }
  140. int CSoundHandler::playSound(const AudioPath & sound, int repeats, bool cache)
  141. {
  142. if(!isInitialized() || sound.empty())
  143. return -1;
  144. int channel;
  145. Mix_Chunk * chunk = GetSoundChunk(sound, cache);
  146. if(chunk)
  147. {
  148. channel = Mix_PlayChannel(-1, chunk, repeats);
  149. if(channel == -1)
  150. {
  151. logGlobal->error("Unable to play sound file %s , error %s", sound.getOriginalName(), Mix_GetError());
  152. if(!cache)
  153. Mix_FreeChunk(chunk);
  154. }
  155. else if(cache)
  156. initCallback(channel);
  157. else
  158. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  159. }
  160. else
  161. channel = -1;
  162. return channel;
  163. }
  164. int CSoundHandler::playSound(std::pair<std::unique_ptr<ui8[]>, si64> & data, int repeats, bool cache)
  165. {
  166. int channel = -1;
  167. if(Mix_Chunk * chunk = GetSoundChunk(data, cache))
  168. {
  169. channel = Mix_PlayChannel(-1, chunk, repeats);
  170. if(channel == -1)
  171. {
  172. logGlobal->error("Unable to play sound, error %s", Mix_GetError());
  173. if(!cache)
  174. Mix_FreeChunk(chunk);
  175. }
  176. else if(cache)
  177. initCallback(channel);
  178. else
  179. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  180. }
  181. return channel;
  182. }
  183. // Helper. Randomly select a sound from an array and play it
  184. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> & sound_vec)
  185. {
  186. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  187. }
  188. void CSoundHandler::stopSound(int handler)
  189. {
  190. if(isInitialized() && handler != -1)
  191. Mix_HaltChannel(handler);
  192. }
  193. ui32 CSoundHandler::getVolume() const
  194. {
  195. return volume;
  196. }
  197. // Sets the sound volume, from 0 (mute) to 100
  198. void CSoundHandler::setVolume(ui32 percent)
  199. {
  200. volume = std::min(100u, percent);
  201. if(isInitialized())
  202. {
  203. setChannelVolume(-1, volume);
  204. for(const auto & channel : channelVolumes)
  205. updateChannelVolume(channel.first);
  206. }
  207. }
  208. void CSoundHandler::updateChannelVolume(int channel)
  209. {
  210. if(channelVolumes.count(channel))
  211. setChannelVolume(channel, getVolume() * channelVolumes[channel] / 100);
  212. else
  213. setChannelVolume(channel, getVolume());
  214. }
  215. // Sets the sound volume, from 0 (mute) to 100
  216. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  217. {
  218. Mix_Volume(channel, (MIX_MAX_VOLUME * percent) / 100);
  219. }
  220. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  221. {
  222. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  223. auto iter = callbacks.find(channel);
  224. //channel not found. It may have finished so fire callback now
  225. if(iter == callbacks.end())
  226. function();
  227. else
  228. iter->second.push_back(function);
  229. }
  230. void CSoundHandler::resetCallback(int channel)
  231. {
  232. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  233. callbacks.erase(channel);
  234. }
  235. void CSoundHandler::soundFinishedCallback(int channel)
  236. {
  237. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  238. if(callbacks.count(channel) == 0)
  239. return;
  240. // store callbacks from container locally - SDL might reuse this channel for another sound
  241. // but do actually execution in separate thread, to avoid potential deadlocks in case if callback requires locks of its own
  242. auto callback = callbacks.at(channel);
  243. callbacks.erase(channel);
  244. if(!callback.empty())
  245. {
  246. GH.dispatchMainThread(
  247. [callback]()
  248. {
  249. for(const auto & entry : callback)
  250. entry();
  251. }
  252. );
  253. }
  254. }
  255. void CSoundHandler::initCallback(int channel)
  256. {
  257. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  258. assert(callbacks.count(channel) == 0);
  259. callbacks[channel] = {};
  260. }
  261. void CSoundHandler::initCallback(int channel, const std::function<void()> & function)
  262. {
  263. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  264. assert(callbacks.count(channel) == 0);
  265. callbacks[channel].push_back(function);
  266. }
  267. int CSoundHandler::ambientGetRange() const
  268. {
  269. return ambientConfig["range"].Integer();
  270. }
  271. void CSoundHandler::ambientUpdateChannels(std::map<AudioPath, int> soundsArg)
  272. {
  273. boost::mutex::scoped_lock guard(mutex);
  274. std::vector<AudioPath> stoppedSounds;
  275. for(const auto & pair : ambientChannels)
  276. {
  277. const auto & soundId = pair.first;
  278. const int channel = pair.second;
  279. if(!vstd::contains(soundsArg, soundId))
  280. {
  281. ambientStopSound(soundId);
  282. stoppedSounds.push_back(soundId);
  283. }
  284. else
  285. {
  286. int channelVolume = ambientDistToVolume(soundsArg[soundId]);
  287. channelVolumes[channel] = channelVolume;
  288. updateChannelVolume(channel);
  289. }
  290. }
  291. for(const auto & soundId : stoppedSounds)
  292. {
  293. channelVolumes.erase(ambientChannels[soundId]);
  294. ambientChannels.erase(soundId);
  295. }
  296. for(const auto & pair : soundsArg)
  297. {
  298. const auto & soundId = pair.first;
  299. const int distance = pair.second;
  300. if(!vstd::contains(ambientChannels, soundId))
  301. {
  302. int channel = playSound(soundId, -1);
  303. int channelVolume = ambientDistToVolume(distance);
  304. channelVolumes[channel] = channelVolume;
  305. updateChannelVolume(channel);
  306. ambientChannels[soundId] = channel;
  307. }
  308. }
  309. }
  310. void CSoundHandler::ambientStopAllChannels()
  311. {
  312. boost::mutex::scoped_lock guard(mutex);
  313. for(const auto & ch : ambientChannels)
  314. {
  315. ambientStopSound(ch.first);
  316. }
  317. channelVolumes.clear();
  318. ambientChannels.clear();
  319. }