CSoundHandler.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. void CSoundHandler::MixChunkDeleter::operator()(Mix_Chunk * ptr)
  46. {
  47. Mix_FreeChunk(ptr);
  48. }
  49. CSoundHandler::~CSoundHandler()
  50. {
  51. if(isInitialized())
  52. {
  53. Mix_ChannelFinished(nullptr);
  54. Mix_HaltChannel(-1);
  55. soundChunks.clear();
  56. uncachedPlayingChunks.clear();
  57. }
  58. }
  59. Mix_Chunk * CSoundHandler::getSoundChunkCached(const AudioPath & sound)
  60. {
  61. if (soundChunks.find(sound) == soundChunks.end())
  62. soundChunks[sound].first = getSoundChunk(sound);
  63. return soundChunks[sound].first.get();
  64. }
  65. // Allocate an SDL chunk and cache it.
  66. CSoundHandler::MixChunkPtr CSoundHandler::getSoundChunk(const AudioPath & sound)
  67. {
  68. try
  69. {
  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. return MixChunkPtr(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. CSoundHandler::MixChunkPtr CSoundHandler::getSoundChunk(std::pair<std::unique_ptr<ui8[]>, si64> & data)
  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. SDL_RWops * ops = SDL_RWFromMem(data.first.get(), data.second);
  87. Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  88. return MixChunkPtr(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)
  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 playSoundImpl(sound, 0, true);
  141. }
  142. int CSoundHandler::playSoundLooped(const AudioPath & sound)
  143. {
  144. return playSoundImpl(sound, -1, true);
  145. }
  146. int CSoundHandler::playSound(const AudioPath & sound)
  147. {
  148. return playSoundImpl(sound, 0, false);
  149. }
  150. int CSoundHandler::playSoundImpl(const AudioPath & sound, int repeats, bool useCache)
  151. {
  152. if(!isInitialized() || sound.empty())
  153. return -1;
  154. int channel;
  155. MixChunkPtr chunkPtr = getSoundChunk(sound);
  156. Mix_Chunk * chunk = nullptr;
  157. if (!useCache)
  158. {
  159. chunkPtr = getSoundChunk(sound);
  160. chunk = chunkPtr.get();
  161. }
  162. else
  163. chunk = getSoundChunkCached(sound);
  164. if(chunk)
  165. {
  166. channel = Mix_PlayChannel(-1, chunk, 0);
  167. if(channel == -1)
  168. {
  169. logGlobal->error("Unable to play sound file %s , error %s", sound.getOriginalName(), Mix_GetError());
  170. }
  171. else
  172. {
  173. storeChunk(channel, std::move(chunkPtr));
  174. initCallback(channel);
  175. }
  176. }
  177. else
  178. channel = -1;
  179. return channel;
  180. }
  181. void CSoundHandler::storeChunk(int channel, MixChunkPtr chunk)
  182. {
  183. std::scoped_lock lockGuard(mutexCallbacks);
  184. uncachedPlayingChunks[channel] = std::move(chunk);
  185. }
  186. int CSoundHandler::playSound(std::pair<std::unique_ptr<ui8[]>, si64> & data)
  187. {
  188. int channel = -1;
  189. auto chunk = getSoundChunk(data);
  190. if(chunk)
  191. {
  192. channel = Mix_PlayChannel(-1, chunk.get(), 0);
  193. if(channel == -1)
  194. {
  195. logGlobal->error("Unable to play sound, error %s", Mix_GetError());
  196. }
  197. else
  198. {
  199. storeChunk(channel, std::move(chunk));
  200. initCallback(channel);
  201. }
  202. }
  203. return channel;
  204. }
  205. // Helper. Randomly select a sound from an array and play it
  206. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> & sound_vec)
  207. {
  208. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  209. }
  210. void CSoundHandler::stopSound(int handler)
  211. {
  212. if(isInitialized() && handler != -1)
  213. Mix_HaltChannel(handler);
  214. }
  215. void CSoundHandler::pauseSound(int handler)
  216. {
  217. if(isInitialized() && handler != -1)
  218. Mix_Pause(handler);
  219. }
  220. void CSoundHandler::resumeSound(int handler)
  221. {
  222. if(isInitialized() && handler != -1)
  223. Mix_Resume(handler);
  224. }
  225. ui32 CSoundHandler::getVolume() const
  226. {
  227. return volume;
  228. }
  229. // Sets the sound volume, from 0 (mute) to 100
  230. void CSoundHandler::setVolume(ui32 percent)
  231. {
  232. volume = std::min(100u, percent);
  233. if(isInitialized())
  234. {
  235. setChannelVolume(-1, volume);
  236. for(const auto & channel : channelVolumes)
  237. updateChannelVolume(channel.first);
  238. }
  239. }
  240. void CSoundHandler::updateChannelVolume(int channel)
  241. {
  242. if(channelVolumes.count(channel))
  243. setChannelVolume(channel, getVolume() * channelVolumes[channel] / 100);
  244. else
  245. setChannelVolume(channel, getVolume());
  246. }
  247. // Sets the sound volume, from 0 (mute) to 100
  248. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  249. {
  250. Mix_Volume(channel, (MIX_MAX_VOLUME * percent) / 100);
  251. }
  252. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  253. {
  254. std::scoped_lock lockGuard(mutexCallbacks);
  255. auto iter = callbacks.find(channel);
  256. //channel not found. It may have finished so fire callback now
  257. if(iter == callbacks.end())
  258. function();
  259. else
  260. iter->second.push_back(function);
  261. }
  262. void CSoundHandler::resetCallback(int channel)
  263. {
  264. std::scoped_lock lockGuard(mutexCallbacks);
  265. callbacks.erase(channel);
  266. }
  267. void CSoundHandler::soundFinishedCallback(int channel)
  268. {
  269. std::scoped_lock lockGuard(mutexCallbacks);
  270. uncachedPlayingChunks.erase(channel);
  271. if(callbacks.count(channel) == 0)
  272. return;
  273. // store callbacks from container locally - SDL might reuse this channel for another sound
  274. // but do actually execution in separate thread, to avoid potential deadlocks in case if callback requires locks of its own
  275. auto callback = callbacks.at(channel);
  276. callbacks.erase(channel);
  277. if(!callback.empty())
  278. {
  279. ENGINE->dispatchMainThread(
  280. [callback]()
  281. {
  282. for(const auto & entry : callback)
  283. entry();
  284. }
  285. );
  286. }
  287. }
  288. void CSoundHandler::initCallback(int channel)
  289. {
  290. std::scoped_lock lockGuard(mutexCallbacks);
  291. assert(callbacks.count(channel) == 0);
  292. callbacks[channel] = {};
  293. }
  294. void CSoundHandler::initCallback(int channel, const std::function<void()> & function)
  295. {
  296. std::scoped_lock lockGuard(mutexCallbacks);
  297. assert(callbacks.count(channel) == 0);
  298. callbacks[channel].push_back(function);
  299. }
  300. int CSoundHandler::ambientGetRange() const
  301. {
  302. return ambientConfig["range"].Integer();
  303. }
  304. void CSoundHandler::ambientUpdateChannels(std::map<AudioPath, int> soundsArg)
  305. {
  306. std::scoped_lock guard(mutex);
  307. std::vector<AudioPath> stoppedSounds;
  308. for(const auto & pair : ambientChannels)
  309. {
  310. const auto & soundId = pair.first;
  311. const int channel = pair.second;
  312. if(!vstd::contains(soundsArg, soundId))
  313. {
  314. ambientStopSound(soundId);
  315. stoppedSounds.push_back(soundId);
  316. }
  317. else
  318. {
  319. int channelVolume = ambientDistToVolume(soundsArg[soundId]);
  320. channelVolumes[channel] = channelVolume;
  321. updateChannelVolume(channel);
  322. }
  323. }
  324. for(const auto & soundId : stoppedSounds)
  325. {
  326. channelVolumes.erase(ambientChannels[soundId]);
  327. ambientChannels.erase(soundId);
  328. }
  329. for(const auto & pair : soundsArg)
  330. {
  331. const auto & soundId = pair.first;
  332. const int distance = pair.second;
  333. if(!vstd::contains(ambientChannels, soundId))
  334. {
  335. int channel = playSoundLooped(soundId);
  336. int channelVolume = ambientDistToVolume(distance);
  337. channelVolumes[channel] = channelVolume;
  338. updateChannelVolume(channel);
  339. ambientChannels[soundId] = channel;
  340. }
  341. }
  342. }
  343. void CSoundHandler::ambientStopAllChannels()
  344. {
  345. std::scoped_lock guard(mutex);
  346. for(const auto & ch : ambientChannels)
  347. {
  348. ambientStopSound(ch.first);
  349. }
  350. channelVolumes.clear();
  351. ambientChannels.clear();
  352. }