CSound.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #include <SDL.h>
  2. #include "CSound.h"
  3. #include "WallpaperEngine/FileSystem/Container.h"
  4. #include "WallpaperEngine/Logging/Log.h"
  5. #include <glm/gtc/constants.hpp>
  6. #include <glm/gtc/matrix_access.hpp>
  7. #include <algorithm>
  8. #include <cfloat>
  9. #include <cmath>
  10. #include <random>
  11. using namespace WallpaperEngine::Render::Objects;
  12. namespace {
  13. std::mt19937& generator () {
  14. static std::mt19937 engine { std::random_device {}() };
  15. return engine;
  16. }
  17. /** 0..32767 like the CRT rand () WE picks the file with (sub_1402C97A0) */
  18. int crtRand () { return static_cast<int> (generator () () >> 17); }
  19. /** [0, 1) from a Mersenne twister draw, sub_1401F4BC0 with the renderer's range 0..1 */
  20. float uniform01 () { return static_cast<float> (generator () () >> 8) * 5.9604645e-8f; }
  21. /** OpenAL Soft 1.21.1 alu.cpp: pulls azimuths in front towards the sides */
  22. float scaleAzimuthFront (float azimuth, float scale) {
  23. const float absolute = std::fabs (azimuth);
  24. if (!(absolute >= glm::half_pi<float> ())) {
  25. return std::copysign (std::min (absolute * scale, glm::half_pi<float> ()), azimuth);
  26. }
  27. return azimuth;
  28. }
  29. /**
  30. * Speaker gains of a mono source for OpenAL Soft 1.21.1's stereo output without HRTF (pairwise render mode, alu.cpp
  31. * CalcPanningAndFilters): first order ambisonic coefficients of the direction through panning.cpp's StereoConfig
  32. * decoder. A source at the listener takes the channel's own angle, 0 for mono
  33. */
  34. glm::vec2 stereoPan (const glm::vec3& direction, float distance) {
  35. float azimuth = 0.0f;
  36. float elevation = 0.0f;
  37. if (distance > FLT_EPSILON) {
  38. elevation = std::asin (std::clamp (direction.y, -1.0f, 1.0f));
  39. azimuth = scaleAzimuthFront (std::atan2 (direction.x, -direction.z), 1.5f);
  40. }
  41. const float acn1 = 1.732050808f * -std::sin (azimuth) * std::cos (elevation);
  42. const float acn3 = 1.732050808f * std::cos (azimuth) * std::cos (elevation);
  43. return { 5.00000000e-1f + 2.88675135e-1f * acn1 + 5.52305643e-2f * acn3,
  44. 5.00000000e-1f - 2.88675135e-1f * acn1 + 5.52305643e-2f * acn3 };
  45. }
  46. } // namespace
  47. CSound::CSound (Wallpapers::CScene& scene, const Sound& sound) :
  48. CObject (scene, sound), m_sound (sound), m_startSilent (sound.startsilent.value_or (false)) {
  49. this->m_lastVolume = this->m_sound.volume && this->m_sound.volume->value
  50. ? this->m_sound.volume->value->getFloat ()
  51. : 1.0f;
  52. this->m_lastMaster = this->masterVolume ();
  53. // sub_1401F4F20, when the object is added to the scene
  54. if (!this->m_startSilent) {
  55. this->play ();
  56. }
  57. // a script asked for this sound before it existed
  58. if (const auto request = scene.getSoundPlayRequest (sound.id); request.has_value ()) {
  59. if (request.value ()) {
  60. this->play ();
  61. } else {
  62. this->stop ();
  63. }
  64. }
  65. }
  66. CSound::~CSound () {
  67. for (auto& voice : this->m_voices) {
  68. this->stopVoice (voice);
  69. }
  70. }
  71. void CSound::loadVoices () {
  72. if (!this->getContext ().getApp ().getContext ().settings.audio.enabled) {
  73. return;
  74. }
  75. // WE loads every file the first time it plays and drops the ones that fail (sub_1401F5980)
  76. for (const auto& file : this->m_sound.sounds) {
  77. try {
  78. const Audio::AudioStream probe (this->getScene ().getAudioContext (), this->getAssetLocator ().read (file));
  79. this->m_voices.push_back ({ .file = file,
  80. .duration = static_cast<float> (probe.getDuration ()),
  81. .mono = probe.getSourceChannels () == 1 });
  82. } catch (const std::exception& e) {
  83. sLog.error ("Cannot load sound ", file, ": ", e.what ());
  84. }
  85. }
  86. }
  87. void CSound::playVoice (Voice& voice, bool loop) {
  88. auto& audio = this->getScene ().getAudioContext ();
  89. if (voice.state == VoiceState::Paused && voice.streamId >= 0) {
  90. voice.stream->setRepeat (loop);
  91. audio.setStreamPaused (voice.streamId, false);
  92. voice.state = VoiceState::Playing;
  93. return;
  94. }
  95. this->stopVoice (voice);
  96. try {
  97. voice.stream = std::make_unique<Audio::AudioStream> (audio, this->getAssetLocator ().read (voice.file), loop);
  98. } catch (const std::exception& e) {
  99. sLog.error ("Cannot play sound ", voice.file, ": ", e.what ());
  100. return;
  101. }
  102. const glm::vec2 gains = this->outputGains (voice);
  103. voice.streamId = audio.addStream (voice.stream.get (), SDL_MIX_MAXVOLUME, gains.x, gains.y);
  104. voice.state = VoiceState::Playing;
  105. }
  106. void CSound::pauseVoice (Voice& voice) {
  107. if (voice.streamId >= 0) {
  108. this->getScene ().getAudioContext ().setStreamPaused (voice.streamId, true);
  109. }
  110. voice.state = VoiceState::Paused;
  111. }
  112. void CSound::stopVoice (Voice& voice) {
  113. if (voice.streamId >= 0) {
  114. this->getScene ().getAudioContext ().removeStream (voice.streamId);
  115. }
  116. voice.stream.reset ();
  117. voice.streamId = -1;
  118. voice.state = VoiceState::Stopped;
  119. }
  120. void CSound::stopAllVoices () {
  121. // sub_1401F58E0
  122. this->m_paused = false;
  123. this->m_stopped = true;
  124. this->m_timer = 0.0f;
  125. for (auto& voice : this->m_voices) {
  126. if (voice.state != VoiceState::Stopped) {
  127. this->stopVoice (voice);
  128. }
  129. }
  130. }
  131. CSound::Voice& CSound::pickVoice () {
  132. const int count = static_cast<int> (this->m_voices.size ());
  133. const int index = static_cast<int> (static_cast<float> (crtRand ()) / 32767.0f * static_cast<float> (count) + 0.0f);
  134. return this->m_voices[std::max (std::min (count - 1, index), 0)];
  135. }
  136. bool CSound::hasActiveVoice () const {
  137. return std::ranges::any_of (this->m_voices, [] (const Voice& voice) {
  138. return voice.state != VoiceState::Stopped;
  139. });
  140. }
  141. void CSound::play () {
  142. // sub_1401F5980
  143. if (this->sourceGain () <= 0.0f) {
  144. this->m_paused = false;
  145. this->m_stopped = false;
  146. this->m_startSilent = false;
  147. return;
  148. }
  149. if (this->m_voices.empty ()) {
  150. this->loadVoices ();
  151. }
  152. if (this->m_sound.spatialization) {
  153. this->m_position = this->spatialPosition ();
  154. }
  155. const bool loop = this->m_voices.size () <= 1 && this->m_sound.playbackmode == PlaybackMode_Loop;
  156. if (this->m_paused) {
  157. this->m_paused = false;
  158. const auto paused = std::ranges::find_if (this->m_voices, [] (const Voice& voice) {
  159. return voice.state == VoiceState::Paused;
  160. });
  161. if (paused != this->m_voices.end ()) {
  162. this->playVoice (*paused, loop);
  163. }
  164. return;
  165. }
  166. if (!this->m_voices.empty ()) {
  167. switch (this->m_sound.playbackmode) {
  168. case PlaybackMode_Random:
  169. if (this->m_timer != 0.0f) {
  170. break;
  171. }
  172. this->stopAllVoices ();
  173. {
  174. Voice& voice = this->pickVoice ();
  175. this->playVoice (voice, false);
  176. this->m_remaining = voice.duration;
  177. }
  178. this->m_timer = uniform01 () * (this->m_sound.maxtime - this->m_sound.mintime) + this->m_sound.mintime
  179. + this->m_remaining;
  180. break;
  181. case PlaybackMode_Single: {
  182. this->stopAllVoices ();
  183. this->m_timer = 0.0f;
  184. Voice& voice = this->pickVoice ();
  185. this->playVoice (voice, false);
  186. this->m_remaining = voice.duration;
  187. break;
  188. }
  189. case PlaybackMode_Loop: {
  190. this->stopAllVoices ();
  191. Voice& voice = this->pickVoice ();
  192. this->playVoice (voice, loop);
  193. // several files: the next random one starts when this one is over
  194. this->m_timer = this->m_voices.size () > 1 ? voice.duration : 0.0f;
  195. break;
  196. }
  197. }
  198. }
  199. this->m_stopped = false;
  200. this->m_startSilent = false;
  201. }
  202. void CSound::stop () {
  203. // sub_1401F6E60
  204. this->m_paused = false;
  205. this->m_stopped = true;
  206. this->m_timer = 0.0f;
  207. for (auto& voice : this->m_voices) {
  208. if (voice.state != VoiceState::Stopped) {
  209. this->stopVoice (voice);
  210. }
  211. }
  212. }
  213. void CSound::pause () {
  214. // sub_1401F6F00
  215. if (this->m_paused || this->m_stopped) {
  216. return;
  217. }
  218. this->m_paused = true;
  219. for (auto& voice : this->m_voices) {
  220. if (voice.state == VoiceState::Playing) {
  221. this->pauseVoice (voice);
  222. }
  223. }
  224. }
  225. bool CSound::isPlaying () const {
  226. // sub_1401F6FB0
  227. if (this->m_sound.playbackmode == PlaybackMode_Single && this->m_remaining <= 0.0f) {
  228. return false;
  229. }
  230. if (this->m_sound.playbackmode == PlaybackMode_Random && this->m_timer <= 0.0f) {
  231. return false;
  232. }
  233. return this->hasActiveVoice () && !this->m_paused;
  234. }
  235. void CSound::volumeChanged () {
  236. // sub_1401F4C20, also what a master volume change does to every sound (sub_1401816D0)
  237. const auto mode = this->m_sound.playbackmode;
  238. if (mode != PlaybackMode_Single) {
  239. const bool active = !(mode == PlaybackMode_Random && this->m_timer <= 0.0f) && this->hasActiveVoice ()
  240. && !this->m_paused;
  241. if (!active && !this->m_paused && !this->m_startSilent && !this->m_stopped) {
  242. this->play ();
  243. }
  244. }
  245. const bool audible = this->masterVolume () > 0.0f;
  246. for (auto& voice : this->m_voices) {
  247. this->applyOutput (voice);
  248. if (audible) {
  249. if (!this->m_paused && voice.state == VoiceState::Paused) {
  250. this->playVoice (voice, mode == PlaybackMode_Loop);
  251. return;
  252. }
  253. } else if (voice.state == VoiceState::Playing) {
  254. this->pauseVoice (voice);
  255. if (mode != PlaybackMode_Loop && this->m_remaining <= 0.0f) {
  256. this->stopVoice (voice);
  257. }
  258. }
  259. }
  260. }
  261. void CSound::update (float dt) {
  262. const float volume
  263. = this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
  264. const float master = this->masterVolume ();
  265. if (volume != this->m_lastVolume || master != this->m_lastMaster) {
  266. this->m_lastVolume = volume;
  267. this->m_lastMaster = master;
  268. this->volumeChanged ();
  269. }
  270. // sub_1401F4F50, dt / renderer +340, which stays 1
  271. if (!this->m_paused && !this->m_stopped) {
  272. if (this->sourceGain () > 0.0f && this->m_timer > 0.0f) {
  273. this->m_timer -= dt;
  274. if (this->m_timer <= 0.0f) {
  275. this->m_timer = 0.0f;
  276. this->play ();
  277. }
  278. }
  279. if (master > 0.0f && this->m_remaining > 0.0f) {
  280. this->m_remaining -= dt;
  281. }
  282. if (this->m_sound.spatialization) {
  283. this->m_position = this->spatialPosition ();
  284. }
  285. }
  286. this->applyOutput ();
  287. }
  288. void CSound::setVolumeOverride (std::optional<int> volume) { this->m_screenVolumeOverride = volume; }
  289. float CSound::masterVolume () const {
  290. const int base
  291. = this->m_screenVolumeOverride.value_or (this->getContext ().getApp ().getContext ().state.audio.volume);
  292. return static_cast<float> (base) / static_cast<float> (SDL_MIX_MAXVOLUME);
  293. }
  294. float CSound::sourceGain () const {
  295. const float volume
  296. = this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
  297. // the voice volume call (+208) gets volume * volume * renderer +728, mediaextensions64 turns it into AL_GAIN as is
  298. return volume * volume * this->masterVolume ();
  299. }
  300. glm::vec3 CSound::spatialPosition () const {
  301. const auto& scene = this->getScene ();
  302. // renderer +324 is the frame counter, 0 while the scene is still loading
  303. if (scene.getFrameCounter () == 0) {
  304. return { 0.0f, 0.0f, 99999.0f };
  305. }
  306. const auto& camera = scene.getCamera ();
  307. const glm::vec3 origin (scene.objectWorldMatrix (this->m_sound)[3]);
  308. const glm::mat4& view = camera.isPerspective () ? camera.getView () : camera.getWorldView ();
  309. // renderer +364 / +376 / +352: rows 0 and 1 of the view and minus row 2 (sub_14017FA70), the eye is +104
  310. const glm::vec3 right (glm::row (view, 0));
  311. const glm::vec3 up (glm::row (view, 1));
  312. const glm::vec3 forward = -glm::vec3 (glm::row (view, 2));
  313. const glm::vec3 offset = origin - scene.getFog ().eyeWorld;
  314. glm::vec3 position (glm::dot (offset, right), -glm::dot (offset, up), glm::dot (offset, forward));
  315. // orthographic scenes only keep the direction, scaled down by the sound's depth over a quarter of the scene size
  316. if (camera.isOrthogonal ()) {
  317. const float length = std::sqrt (glm::dot (position, position));
  318. const float reach = static_cast<float> (static_cast<int> (camera.getWidth ()) + static_cast<int> (camera.getHeight ()))
  319. * 0.25f;
  320. position *= 1.0f / length;
  321. position *= std::max (reach - origin.z, 0.0f) / reach;
  322. }
  323. return position;
  324. }
  325. glm::vec2 CSound::outputGains (const Voice& voice) const {
  326. float gain = this->sourceGain ();
  327. glm::vec2 channels (1.0f);
  328. // OpenAL Soft only spatializes mono sources (AL_SOURCE_SPATIALIZE_SOFT defaults to auto), the others go straight
  329. // to their speakers; the source gain is clamped to AL_MAX_GAIN 1 on both paths
  330. if (voice.mono && this->getScene ().getAudioContext ().getChannels () == 2) {
  331. // WE only sets the reference distance and rolloff on spatialized sounds, the others keep OpenAL's 1 and 1 and sit
  332. // on the listener
  333. const float reference = this->m_sound.spatialization ? this->m_sound.mindistance : 1.0f;
  334. const float rolloff = this->m_sound.spatialization ? this->m_sound.attenuation : 1.0f;
  335. const float limit = std::max (reference / 1024.0f, FLT_EPSILON);
  336. glm::vec3 direction = this->m_position;
  337. float distance = 0.0f;
  338. if (glm::dot (direction, direction) > limit * limit) {
  339. distance = std::sqrt (glm::dot (direction, direction));
  340. direction *= 1.0f / distance;
  341. }
  342. // AL_INVERSE_DISTANCE_CLAMPED, WE never changes the distance model or AL_MAX_DISTANCE
  343. const float clamped = std::clamp (distance, reference, FLT_MAX);
  344. if (reference > 0.0f) {
  345. const float scaled = reference + (clamped - reference) * rolloff;
  346. if (scaled > 0.0f) {
  347. gain *= reference / scaled;
  348. }
  349. }
  350. channels = stereoPan (direction, distance);
  351. }
  352. return std::clamp (gain, 0.0f, 1.0f) * channels;
  353. }
  354. void CSound::applyOutput (const Voice& voice) const {
  355. if (voice.streamId < 0) {
  356. return;
  357. }
  358. const glm::vec2 gains = this->outputGains (voice);
  359. this->getScene ().getAudioContext ().setStreamGains (voice.streamId, gains.x, gains.y);
  360. }
  361. void CSound::applyOutput () const {
  362. for (const auto& voice : this->m_voices) {
  363. this->applyOutput (voice);
  364. }
  365. }