CSoundHandler.cpp 9.5 KB

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