CSoundHandler.cpp 9.6 KB

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