CSoundHandler.cpp 9.4 KB

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