CSoundHandler.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 channels = 0;
  126. if(!Mix_QuerySpec(&freq, &fmt, &channels))
  127. return 0;
  128. if(chunk != nullptr)
  129. {
  130. Uint32 sampleSizeBytes = (fmt & 0xFF) / 8;
  131. Uint32 samples = (chunk->alen / sampleSizeBytes);
  132. Uint32 frames = (samples / channels);
  133. milliseconds = ((frames * 1000) / freq);
  134. Mix_FreeChunk(chunk);
  135. }
  136. return milliseconds;
  137. }
  138. // Plays a sound, and return its channel so we can fade it out later
  139. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  140. {
  141. assert(soundID < soundBase::sound_after_last);
  142. auto sound = AudioPath::builtin(soundsList[soundID]);
  143. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound.getOriginalName());
  144. return playSound(sound, repeats, true);
  145. }
  146. int CSoundHandler::playSound(const AudioPath & sound, int repeats, bool cache)
  147. {
  148. if(!isInitialized() || sound.empty())
  149. return -1;
  150. int channel;
  151. Mix_Chunk * chunk = GetSoundChunk(sound, cache);
  152. if(chunk)
  153. {
  154. channel = Mix_PlayChannel(-1, chunk, repeats);
  155. if(channel == -1)
  156. {
  157. logGlobal->error("Unable to play sound file %s , error %s", sound.getOriginalName(), Mix_GetError());
  158. if(!cache)
  159. Mix_FreeChunk(chunk);
  160. }
  161. else if(cache)
  162. initCallback(channel);
  163. else
  164. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  165. }
  166. else
  167. channel = -1;
  168. return channel;
  169. }
  170. int CSoundHandler::playSound(std::pair<std::unique_ptr<ui8[]>, si64> & data, int repeats, bool cache)
  171. {
  172. int channel = -1;
  173. if(Mix_Chunk * chunk = GetSoundChunk(data, cache))
  174. {
  175. channel = Mix_PlayChannel(-1, chunk, repeats);
  176. if(channel == -1)
  177. {
  178. logGlobal->error("Unable to play sound, error %s", Mix_GetError());
  179. if(!cache)
  180. Mix_FreeChunk(chunk);
  181. }
  182. else if(cache)
  183. initCallback(channel);
  184. else
  185. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  186. }
  187. return channel;
  188. }
  189. // Helper. Randomly select a sound from an array and play it
  190. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> & sound_vec)
  191. {
  192. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  193. }
  194. void CSoundHandler::stopSound(int handler)
  195. {
  196. if(isInitialized() && handler != -1)
  197. Mix_HaltChannel(handler);
  198. }
  199. void CSoundHandler::pauseSound(int handler)
  200. {
  201. if(isInitialized() && handler != -1)
  202. Mix_Pause(handler);
  203. }
  204. void CSoundHandler::resumeSound(int handler)
  205. {
  206. if(isInitialized() && handler != -1)
  207. Mix_Resume(handler);
  208. }
  209. ui32 CSoundHandler::getVolume() const
  210. {
  211. return volume;
  212. }
  213. // Sets the sound volume, from 0 (mute) to 100
  214. void CSoundHandler::setVolume(ui32 percent)
  215. {
  216. volume = std::min(100u, percent);
  217. if(isInitialized())
  218. {
  219. setChannelVolume(-1, volume);
  220. for(const auto & channel : channelVolumes)
  221. updateChannelVolume(channel.first);
  222. }
  223. }
  224. void CSoundHandler::updateChannelVolume(int channel)
  225. {
  226. if(channelVolumes.count(channel))
  227. setChannelVolume(channel, getVolume() * channelVolumes[channel] / 100);
  228. else
  229. setChannelVolume(channel, getVolume());
  230. }
  231. // Sets the sound volume, from 0 (mute) to 100
  232. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  233. {
  234. Mix_Volume(channel, (MIX_MAX_VOLUME * percent) / 100);
  235. }
  236. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  237. {
  238. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  239. auto iter = callbacks.find(channel);
  240. //channel not found. It may have finished so fire callback now
  241. if(iter == callbacks.end())
  242. function();
  243. else
  244. iter->second.push_back(function);
  245. }
  246. void CSoundHandler::resetCallback(int channel)
  247. {
  248. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  249. callbacks.erase(channel);
  250. }
  251. void CSoundHandler::soundFinishedCallback(int channel)
  252. {
  253. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  254. if(callbacks.count(channel) == 0)
  255. return;
  256. // store callbacks from container locally - SDL might reuse this channel for another sound
  257. // but do actually execution in separate thread, to avoid potential deadlocks in case if callback requires locks of its own
  258. auto callback = callbacks.at(channel);
  259. callbacks.erase(channel);
  260. if(!callback.empty())
  261. {
  262. GH.dispatchMainThread(
  263. [callback]()
  264. {
  265. for(const auto & entry : callback)
  266. entry();
  267. }
  268. );
  269. }
  270. }
  271. void CSoundHandler::initCallback(int channel)
  272. {
  273. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  274. assert(callbacks.count(channel) == 0);
  275. callbacks[channel] = {};
  276. }
  277. void CSoundHandler::initCallback(int channel, const std::function<void()> & function)
  278. {
  279. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  280. assert(callbacks.count(channel) == 0);
  281. callbacks[channel].push_back(function);
  282. }
  283. int CSoundHandler::ambientGetRange() const
  284. {
  285. return ambientConfig["range"].Integer();
  286. }
  287. void CSoundHandler::ambientUpdateChannels(std::map<AudioPath, int> soundsArg)
  288. {
  289. boost::mutex::scoped_lock guard(mutex);
  290. std::vector<AudioPath> stoppedSounds;
  291. for(const auto & pair : ambientChannels)
  292. {
  293. const auto & soundId = pair.first;
  294. const int channel = pair.second;
  295. if(!vstd::contains(soundsArg, soundId))
  296. {
  297. ambientStopSound(soundId);
  298. stoppedSounds.push_back(soundId);
  299. }
  300. else
  301. {
  302. int channelVolume = ambientDistToVolume(soundsArg[soundId]);
  303. channelVolumes[channel] = channelVolume;
  304. updateChannelVolume(channel);
  305. }
  306. }
  307. for(const auto & soundId : stoppedSounds)
  308. {
  309. channelVolumes.erase(ambientChannels[soundId]);
  310. ambientChannels.erase(soundId);
  311. }
  312. for(const auto & pair : soundsArg)
  313. {
  314. const auto & soundId = pair.first;
  315. const int distance = pair.second;
  316. if(!vstd::contains(ambientChannels, soundId))
  317. {
  318. int channel = playSound(soundId, -1);
  319. int channelVolume = ambientDistToVolume(distance);
  320. channelVolumes[channel] = channelVolume;
  321. updateChannelVolume(channel);
  322. ambientChannels[soundId] = channel;
  323. }
  324. }
  325. }
  326. void CSoundHandler::ambientStopAllChannels()
  327. {
  328. boost::mutex::scoped_lock guard(mutex);
  329. for(const auto & ch : ambientChannels)
  330. {
  331. ambientStopSound(ch.first);
  332. }
  333. channelVolumes.clear();
  334. ambientChannels.clear();
  335. }