OpenALStream.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Copyright 2008 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #ifdef _WIN32
  4. #include "AudioCommon/OpenALStream.h"
  5. #include <windows.h>
  6. #include <climits>
  7. #include <cstring>
  8. #include <thread>
  9. #include "Common/Logging/Log.h"
  10. #include "Common/MsgHandler.h"
  11. #include "Common/Thread.h"
  12. #include "Core/Config/MainSettings.h"
  13. static HMODULE s_openal_dll = nullptr;
  14. #define OPENAL_API_VISIT(X) \
  15. X(alBufferData) \
  16. X(alcCloseDevice) \
  17. X(alcCreateContext) \
  18. X(alcDestroyContext) \
  19. X(alcGetContextsDevice) \
  20. X(alcGetCurrentContext) \
  21. X(alcGetString) \
  22. X(alcIsExtensionPresent) \
  23. X(alcMakeContextCurrent) \
  24. X(alcOpenDevice) \
  25. X(alDeleteBuffers) \
  26. X(alDeleteSources) \
  27. X(alGenBuffers) \
  28. X(alGenSources) \
  29. X(alGetError) \
  30. X(alGetSourcei) \
  31. X(alGetString) \
  32. X(alIsExtensionPresent) \
  33. X(alSourcef) \
  34. X(alSourcei) \
  35. X(alSourcePlay) \
  36. X(alSourceQueueBuffers) \
  37. X(alSourceStop) \
  38. X(alSourceUnqueueBuffers)
  39. // Create func_t function pointer type and declare a nullptr-initialized static variable of that
  40. // type named "pfunc".
  41. #define DYN_FUNC_DECLARE(func) \
  42. typedef decltype(&func) func##_t; \
  43. static func##_t p##func = nullptr;
  44. // Attempt to load the function from the given module handle.
  45. #define OPENAL_FUNC_LOAD(func) \
  46. p##func = (func##_t)::GetProcAddress(s_openal_dll, #func); \
  47. if (!p##func) \
  48. { \
  49. return false; \
  50. }
  51. OPENAL_API_VISIT(DYN_FUNC_DECLARE);
  52. static bool InitFunctions()
  53. {
  54. OPENAL_API_VISIT(OPENAL_FUNC_LOAD);
  55. return true;
  56. }
  57. static bool InitLibrary()
  58. {
  59. if (s_openal_dll)
  60. return true;
  61. s_openal_dll = ::LoadLibrary(TEXT("openal32.dll"));
  62. if (!s_openal_dll)
  63. return false;
  64. if (!InitFunctions())
  65. {
  66. ::FreeLibrary(s_openal_dll);
  67. s_openal_dll = nullptr;
  68. return false;
  69. }
  70. return true;
  71. }
  72. bool OpenALStream::IsValid()
  73. {
  74. return InitLibrary();
  75. }
  76. //
  77. // AyuanX: Spec says OpenAL1.1 is thread safe already
  78. //
  79. bool OpenALStream::Init()
  80. {
  81. if (!palcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT"))
  82. {
  83. PanicAlertFmtT("OpenAL: can't find sound devices");
  84. return false;
  85. }
  86. const char* default_device_dame = palcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);
  87. INFO_LOG_FMT(AUDIO, "Found OpenAL device {}", default_device_dame);
  88. ALCdevice* device = palcOpenDevice(default_device_dame);
  89. if (!device)
  90. {
  91. PanicAlertFmtT("OpenAL: can't open device {0}", default_device_dame);
  92. return false;
  93. }
  94. ALCcontext* context = palcCreateContext(device, nullptr);
  95. if (!context)
  96. {
  97. palcCloseDevice(device);
  98. PanicAlertFmtT("OpenAL: can't create context for device {0}", default_device_dame);
  99. return false;
  100. }
  101. palcMakeContextCurrent(context);
  102. m_run_thread.Set();
  103. m_thread = std::thread(&OpenALStream::SoundLoop, this);
  104. return true;
  105. }
  106. OpenALStream::~OpenALStream()
  107. {
  108. m_run_thread.Clear();
  109. m_thread.join();
  110. palSourceStop(m_source);
  111. palSourcei(m_source, AL_BUFFER, 0);
  112. // Clean up buffers and sources
  113. palDeleteSources(1, &m_source);
  114. m_source = 0;
  115. palDeleteBuffers(OAL_BUFFERS, m_buffers.data());
  116. ALCcontext* context = palcGetCurrentContext();
  117. ALCdevice* device = palcGetContextsDevice(context);
  118. palcMakeContextCurrent(nullptr);
  119. palcDestroyContext(context);
  120. palcCloseDevice(device);
  121. }
  122. void OpenALStream::SetVolume(int volume)
  123. {
  124. m_volume = (float)volume / 100.0f;
  125. if (m_source)
  126. palSourcef(m_source, AL_GAIN, m_volume);
  127. }
  128. bool OpenALStream::SetRunning(bool running)
  129. {
  130. if (running)
  131. {
  132. palSourcePlay(m_source);
  133. }
  134. else
  135. {
  136. palSourceStop(m_source);
  137. }
  138. return true;
  139. }
  140. static ALenum CheckALError(const char* desc)
  141. {
  142. ALenum err = palGetError();
  143. if (err != AL_NO_ERROR)
  144. {
  145. std::string type;
  146. switch (err)
  147. {
  148. case AL_INVALID_NAME:
  149. type = "AL_INVALID_NAME";
  150. break;
  151. case AL_INVALID_ENUM:
  152. type = "AL_INVALID_ENUM";
  153. break;
  154. case AL_INVALID_VALUE:
  155. type = "AL_INVALID_VALUE";
  156. break;
  157. case AL_INVALID_OPERATION:
  158. type = "AL_INVALID_OPERATION";
  159. break;
  160. case AL_OUT_OF_MEMORY:
  161. type = "AL_OUT_OF_MEMORY";
  162. break;
  163. default:
  164. type = "UNKNOWN_ERROR";
  165. break;
  166. }
  167. ERROR_LOG_FMT(AUDIO, "Error {}: {:08x} {}", desc, err, type);
  168. }
  169. return err;
  170. }
  171. static bool IsCreativeXFi()
  172. {
  173. return strstr(palGetString(AL_RENDERER), "X-Fi") != nullptr;
  174. }
  175. void OpenALStream::SoundLoop()
  176. {
  177. Common::SetCurrentThreadName("Audio thread - openal");
  178. bool float32_capable = palIsExtensionPresent("AL_EXT_float32") != 0;
  179. bool surround_capable = palIsExtensionPresent("AL_EXT_MCFORMATS") || IsCreativeXFi();
  180. bool use_surround = Config::ShouldUseDPL2Decoder() && surround_capable;
  181. // As there is no extension to check for 32-bit fixed point support
  182. // and we know that only a X-Fi with hardware OpenAL supports it,
  183. // we just check if one is being used.
  184. bool fixed32_capable = IsCreativeXFi();
  185. u32 frequency = m_mixer->GetSampleRate();
  186. u32 frames_per_buffer;
  187. // Can't have zero samples per buffer
  188. if (Config::Get(Config::MAIN_AUDIO_LATENCY) > 0)
  189. {
  190. frames_per_buffer = frequency / 1000 * Config::Get(Config::MAIN_AUDIO_LATENCY) / OAL_BUFFERS;
  191. }
  192. else
  193. {
  194. frames_per_buffer = frequency / 1000 * 1 / OAL_BUFFERS;
  195. }
  196. if (frames_per_buffer > OAL_MAX_FRAMES)
  197. {
  198. frames_per_buffer = OAL_MAX_FRAMES;
  199. }
  200. INFO_LOG_FMT(AUDIO, "Using {} buffers, each with {} audio frames for a total of {}.", OAL_BUFFERS,
  201. frames_per_buffer, frames_per_buffer * OAL_BUFFERS);
  202. // Should we make these larger just in case the mixer ever sends more samples
  203. // than what we request?
  204. m_realtime_buffer.resize(frames_per_buffer * STEREO_CHANNELS);
  205. m_source = 0;
  206. // Clear error state before querying or else we get false positives.
  207. ALenum err = palGetError();
  208. // Generate some AL Buffers for streaming
  209. palGenBuffers(OAL_BUFFERS, (ALuint*)m_buffers.data());
  210. err = CheckALError("generating buffers");
  211. // Generate a Source to playback the Buffers
  212. palGenSources(1, &m_source);
  213. err = CheckALError("generating sources");
  214. // Set the default sound volume as saved in the config file.
  215. palSourcef(m_source, AL_GAIN, m_volume);
  216. // TODO: Error handling
  217. // ALenum err = alGetError();
  218. unsigned int next_buffer = 0;
  219. unsigned int num_buffers_queued = 0;
  220. ALint state = 0;
  221. while (m_run_thread.IsSet())
  222. {
  223. // Block until we have a free buffer
  224. int num_buffers_processed;
  225. palGetSourcei(m_source, AL_BUFFERS_PROCESSED, &num_buffers_processed);
  226. if (num_buffers_queued == OAL_BUFFERS && !num_buffers_processed)
  227. {
  228. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  229. continue;
  230. }
  231. // Remove the Buffer from the Queue.
  232. if (num_buffers_processed)
  233. {
  234. std::array<ALuint, OAL_BUFFERS> unqueued_buffer_ids;
  235. palSourceUnqueueBuffers(m_source, num_buffers_processed, unqueued_buffer_ids.data());
  236. err = CheckALError("unqueuing buffers");
  237. num_buffers_queued -= num_buffers_processed;
  238. }
  239. unsigned int min_frames = frames_per_buffer;
  240. if (use_surround)
  241. {
  242. std::array<float, OAL_MAX_FRAMES * SURROUND_CHANNELS> dpl2;
  243. u32 rendered_frames = m_mixer->MixSurround(dpl2.data(), min_frames);
  244. if (rendered_frames < min_frames)
  245. continue;
  246. if (float32_capable)
  247. {
  248. palBufferData(m_buffers[next_buffer], AL_FORMAT_51CHN32, dpl2.data(),
  249. rendered_frames * FRAME_SURROUND_FLOAT, frequency);
  250. }
  251. else if (fixed32_capable)
  252. {
  253. std::array<int, OAL_MAX_FRAMES * SURROUND_CHANNELS> surround_int32;
  254. for (u32 i = 0; i < rendered_frames * SURROUND_CHANNELS; ++i)
  255. {
  256. dpl2[i] = dpl2[i] * std::numeric_limits<int>::max();
  257. if (dpl2[i] > std::numeric_limits<int>::max())
  258. surround_int32[i] = std::numeric_limits<int>::max();
  259. else if (dpl2[i] < std::numeric_limits<int>::min())
  260. surround_int32[i] = std::numeric_limits<int>::min();
  261. else
  262. surround_int32[i] = static_cast<int>(dpl2[i]);
  263. }
  264. palBufferData(m_buffers[next_buffer], AL_FORMAT_51CHN32, surround_int32.data(),
  265. rendered_frames * FRAME_SURROUND_INT32, frequency);
  266. }
  267. else
  268. {
  269. std::array<short, OAL_MAX_FRAMES * SURROUND_CHANNELS> surround_short;
  270. for (u32 i = 0; i < rendered_frames * SURROUND_CHANNELS; ++i)
  271. {
  272. dpl2[i] = dpl2[i] * std::numeric_limits<short>::max();
  273. if (dpl2[i] > std::numeric_limits<short>::max())
  274. surround_short[i] = std::numeric_limits<short>::max();
  275. else if (dpl2[i] < std::numeric_limits<short>::min())
  276. surround_short[i] = std::numeric_limits<short>::min();
  277. else
  278. surround_short[i] = static_cast<short>(dpl2[i]);
  279. }
  280. palBufferData(m_buffers[next_buffer], AL_FORMAT_51CHN16, surround_short.data(),
  281. rendered_frames * FRAME_SURROUND_SHORT, frequency);
  282. }
  283. err = CheckALError("buffering data");
  284. if (err == AL_INVALID_ENUM)
  285. {
  286. // 5.1 is not supported by the host, fallback to stereo
  287. WARN_LOG_FMT(
  288. AUDIO, "Unable to set 5.1 surround mode. Updating OpenAL Soft might fix this issue.");
  289. use_surround = false;
  290. }
  291. }
  292. else
  293. {
  294. u32 rendered_frames = m_mixer->Mix(m_realtime_buffer.data(), min_frames);
  295. if (!rendered_frames)
  296. continue;
  297. palBufferData(m_buffers[next_buffer], AL_FORMAT_STEREO16, m_realtime_buffer.data(),
  298. rendered_frames * FRAME_STEREO_SHORT, frequency);
  299. }
  300. palSourceQueueBuffers(m_source, 1, &m_buffers[next_buffer]);
  301. err = CheckALError("queuing buffers");
  302. num_buffers_queued++;
  303. next_buffer = (next_buffer + 1) % OAL_BUFFERS;
  304. palGetSourcei(m_source, AL_SOURCE_STATE, &state);
  305. if (state != AL_PLAYING)
  306. {
  307. // Buffer underrun occurred, resume playback
  308. palSourcePlay(m_source);
  309. err = CheckALError("occurred resuming playback");
  310. }
  311. }
  312. }
  313. #endif // _WIN32