SDL_windows.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #if defined(SDL_PLATFORM_WINDOWS)
  20. #include "SDL_windows.h"
  21. #include <objbase.h> // for CoInitialize/CoUninitialize (Win32 only)
  22. #ifdef HAVE_ROAPI_H
  23. #include <roapi.h> // For RoInitialize/RoUninitialize (Win32 only)
  24. #else
  25. typedef enum RO_INIT_TYPE
  26. {
  27. RO_INIT_SINGLETHREADED = 0,
  28. RO_INIT_MULTITHREADED = 1
  29. } RO_INIT_TYPE;
  30. #endif
  31. #ifndef _WIN32_WINNT_VISTA
  32. #define _WIN32_WINNT_VISTA 0x0600
  33. #endif
  34. #ifndef _WIN32_WINNT_WIN7
  35. #define _WIN32_WINNT_WIN7 0x0601
  36. #endif
  37. #ifndef _WIN32_WINNT_WIN8
  38. #define _WIN32_WINNT_WIN8 0x0602
  39. #endif
  40. #ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
  41. #define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
  42. #endif
  43. #ifndef WC_ERR_INVALID_CHARS
  44. #define WC_ERR_INVALID_CHARS 0x00000080
  45. #endif
  46. // Sets an error message based on an HRESULT
  47. bool WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr)
  48. {
  49. TCHAR buffer[1024];
  50. char *message;
  51. TCHAR *p = buffer;
  52. DWORD c = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, 0,
  53. buffer, SDL_arraysize(buffer), NULL);
  54. buffer[c] = 0;
  55. // kill CR/LF that FormatMessage() sticks at the end
  56. while (*p) {
  57. if (*p == '\r') {
  58. *p = 0;
  59. break;
  60. }
  61. ++p;
  62. }
  63. message = WIN_StringToUTF8(buffer);
  64. SDL_SetError("%s%s%s", prefix ? prefix : "", prefix ? ": " : "", message);
  65. SDL_free(message);
  66. return false;
  67. }
  68. // Sets an error message based on GetLastError()
  69. bool WIN_SetError(const char *prefix)
  70. {
  71. return WIN_SetErrorFromHRESULT(prefix, GetLastError());
  72. }
  73. HRESULT
  74. WIN_CoInitialize(void)
  75. {
  76. /* SDL handles any threading model, so initialize with the default, which
  77. is compatible with OLE and if that doesn't work, try multi-threaded mode.
  78. If you need multi-threaded mode, call CoInitializeEx() before SDL_Init()
  79. */
  80. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  81. // On Xbox, there's no need to call CoInitializeEx (and it's not implemented)
  82. return S_OK;
  83. #else
  84. HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  85. if (hr == RPC_E_CHANGED_MODE) {
  86. hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  87. }
  88. // S_FALSE means success, but someone else already initialized.
  89. // You still need to call CoUninitialize in this case!
  90. if (hr == S_FALSE) {
  91. return S_OK;
  92. }
  93. return hr;
  94. #endif
  95. }
  96. void WIN_CoUninitialize(void)
  97. {
  98. CoUninitialize();
  99. }
  100. FARPROC WIN_LoadComBaseFunction(const char *name)
  101. {
  102. static bool s_bLoaded;
  103. static HMODULE s_hComBase;
  104. if (!s_bLoaded) {
  105. s_hComBase = LoadLibraryEx(TEXT("combase.dll"), NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
  106. s_bLoaded = true;
  107. }
  108. if (s_hComBase) {
  109. return GetProcAddress(s_hComBase, name);
  110. } else {
  111. return NULL;
  112. }
  113. }
  114. HRESULT
  115. WIN_RoInitialize(void)
  116. {
  117. typedef HRESULT(WINAPI * RoInitialize_t)(RO_INIT_TYPE initType);
  118. RoInitialize_t RoInitializeFunc = (RoInitialize_t)WIN_LoadComBaseFunction("RoInitialize");
  119. if (RoInitializeFunc) {
  120. // RO_INIT_SINGLETHREADED is equivalent to COINIT_APARTMENTTHREADED
  121. HRESULT hr = RoInitializeFunc(RO_INIT_SINGLETHREADED);
  122. if (hr == RPC_E_CHANGED_MODE) {
  123. hr = RoInitializeFunc(RO_INIT_MULTITHREADED);
  124. }
  125. // S_FALSE means success, but someone else already initialized.
  126. // You still need to call RoUninitialize in this case!
  127. if (hr == S_FALSE) {
  128. return S_OK;
  129. }
  130. return hr;
  131. } else {
  132. return E_NOINTERFACE;
  133. }
  134. }
  135. void WIN_RoUninitialize(void)
  136. {
  137. typedef void(WINAPI * RoUninitialize_t)(void);
  138. RoUninitialize_t RoUninitializeFunc = (RoUninitialize_t)WIN_LoadComBaseFunction("RoUninitialize");
  139. if (RoUninitializeFunc) {
  140. RoUninitializeFunc();
  141. }
  142. }
  143. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  144. static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
  145. {
  146. OSVERSIONINFOEXW osvi;
  147. DWORDLONG const dwlConditionMask = VerSetConditionMask(
  148. VerSetConditionMask(
  149. VerSetConditionMask(
  150. 0, VER_MAJORVERSION, VER_GREATER_EQUAL),
  151. VER_MINORVERSION, VER_GREATER_EQUAL),
  152. VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
  153. SDL_zero(osvi);
  154. osvi.dwOSVersionInfoSize = sizeof(osvi);
  155. osvi.dwMajorVersion = wMajorVersion;
  156. osvi.dwMinorVersion = wMinorVersion;
  157. osvi.wServicePackMajor = wServicePackMajor;
  158. return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;
  159. }
  160. #endif
  161. // apply some static variables so we only call into the Win32 API once per process for each check.
  162. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  163. #define CHECKWINVER(notdesktop_platform_result, test) return (notdesktop_platform_result);
  164. #else
  165. #define CHECKWINVER(notdesktop_platform_result, test) \
  166. static bool checked = false; \
  167. static BOOL result = FALSE; \
  168. if (!checked) { \
  169. result = (test); \
  170. checked = true; \
  171. } \
  172. return result;
  173. #endif
  174. // this is the oldest thing we run on (and we may lose support for this in SDL3 at any time!),
  175. // so there's no "OrGreater" as that would always be TRUE. The other functions are here to
  176. // ask "can we support a specific feature?" but this function is here to ask "do we need to do
  177. // something different for an OS version we probably should abandon?" :)
  178. BOOL WIN_IsWindowsXP(void)
  179. {
  180. CHECKWINVER(FALSE, !WIN_IsWindowsVistaOrGreater() && IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0));
  181. }
  182. BOOL WIN_IsWindowsVistaOrGreater(void)
  183. {
  184. CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0));
  185. }
  186. BOOL WIN_IsWindows7OrGreater(void)
  187. {
  188. CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0));
  189. }
  190. BOOL WIN_IsWindows8OrGreater(void)
  191. {
  192. CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0));
  193. }
  194. #undef CHECKWINVER
  195. /*
  196. WAVExxxCAPS gives you 31 bytes for the device name, and just truncates if it's
  197. longer. However, since WinXP, you can use the WAVExxxCAPS2 structure, which
  198. will give you a name GUID. The full name is in the Windows Registry under
  199. that GUID, located here: HKLM\System\CurrentControlSet\Control\MediaCategories
  200. Note that drivers can report GUID_NULL for the name GUID, in which case,
  201. Windows makes a best effort to fill in those 31 bytes in the usual place.
  202. This info summarized from MSDN:
  203. http://web.archive.org/web/20131027093034/http://msdn.microsoft.com/en-us/library/windows/hardware/ff536382(v=vs.85).aspx
  204. Always look this up in the registry if possible, because the strings are
  205. different! At least on Win10, I see "Yeti Stereo Microphone" in the
  206. Registry, and a unhelpful "Microphone(Yeti Stereo Microph" in winmm. Sigh.
  207. (Also, DirectSound shouldn't be limited to 32 chars, but its device enum
  208. has the same problem.)
  209. WASAPI doesn't need this. This is just for DirectSound/WinMM.
  210. */
  211. char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
  212. {
  213. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  214. return WIN_StringToUTF8W(name); // No registry access on Xbox, go with what we've got.
  215. #else
  216. static const GUID nullguid = { 0 };
  217. const unsigned char *ptr;
  218. char keystr[128];
  219. WCHAR *strw = NULL;
  220. bool rc;
  221. HKEY hkey;
  222. DWORD len = 0;
  223. char *result = NULL;
  224. if (WIN_IsEqualGUID(guid, &nullguid)) {
  225. return WIN_StringToUTF8(name); // No GUID, go with what we've got.
  226. }
  227. ptr = (const unsigned char *)guid;
  228. (void)SDL_snprintf(keystr, sizeof(keystr),
  229. "System\\CurrentControlSet\\Control\\MediaCategories\\{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
  230. ptr[3], ptr[2], ptr[1], ptr[0], ptr[5], ptr[4], ptr[7], ptr[6],
  231. ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
  232. strw = WIN_UTF8ToString(keystr);
  233. rc = (RegOpenKeyExW(HKEY_LOCAL_MACHINE, strw, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS);
  234. SDL_free(strw);
  235. if (!rc) {
  236. return WIN_StringToUTF8(name); // oh well.
  237. }
  238. rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, NULL, &len) == ERROR_SUCCESS);
  239. if (!rc) {
  240. RegCloseKey(hkey);
  241. return WIN_StringToUTF8(name); // oh well.
  242. }
  243. strw = (WCHAR *)SDL_malloc(len + sizeof(WCHAR));
  244. if (!strw) {
  245. RegCloseKey(hkey);
  246. return WIN_StringToUTF8(name); // oh well.
  247. }
  248. rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, (LPBYTE)strw, &len) == ERROR_SUCCESS);
  249. RegCloseKey(hkey);
  250. if (!rc) {
  251. SDL_free(strw);
  252. return WIN_StringToUTF8(name); // oh well.
  253. }
  254. strw[len / 2] = 0; // make sure it's null-terminated.
  255. result = WIN_StringToUTF8(strw);
  256. SDL_free(strw);
  257. return result ? result : WIN_StringToUTF8(name);
  258. #endif
  259. }
  260. BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b)
  261. {
  262. return (SDL_memcmp(a, b, sizeof(*a)) == 0);
  263. }
  264. BOOL WIN_IsEqualIID(REFIID a, REFIID b)
  265. {
  266. return (SDL_memcmp(a, b, sizeof(*a)) == 0);
  267. }
  268. void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect)
  269. {
  270. sdlrect->x = winrect->left;
  271. sdlrect->w = (winrect->right - winrect->left) + 1;
  272. sdlrect->y = winrect->top;
  273. sdlrect->h = (winrect->bottom - winrect->top) + 1;
  274. }
  275. void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect)
  276. {
  277. winrect->left = sdlrect->x;
  278. winrect->right = sdlrect->x + sdlrect->w - 1;
  279. winrect->top = sdlrect->y;
  280. winrect->bottom = sdlrect->y + sdlrect->h - 1;
  281. }
  282. bool WIN_WindowRectValid(const RECT *rect)
  283. {
  284. // A window can be resized to zero height, but not zero width
  285. return (rect->right > 0);
  286. }
  287. // Some GUIDs we need to know without linking to libraries that aren't available before Vista.
  288. /* *INDENT-OFF* */ // clang-format off
  289. static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  290. static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  291. /* *INDENT-ON* */ // clang-format on
  292. SDL_AudioFormat SDL_WaveFormatExToSDLFormat(WAVEFORMATEX *waveformat)
  293. {
  294. if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
  295. return SDL_AUDIO_F32;
  296. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
  297. return SDL_AUDIO_S16;
  298. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
  299. return SDL_AUDIO_S32;
  300. } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  301. const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)waveformat;
  302. if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  303. return SDL_AUDIO_F32;
  304. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
  305. return SDL_AUDIO_S16;
  306. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  307. return SDL_AUDIO_S32;
  308. }
  309. }
  310. return SDL_AUDIO_UNKNOWN;
  311. }
  312. int WIN_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar)
  313. {
  314. if (WIN_IsWindowsXP()) {
  315. dwFlags &= ~WC_ERR_INVALID_CHARS; // not supported before Vista. Without this flag, it will just replace bogus chars with U+FFFD. You're on your own, WinXP.
  316. }
  317. return WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar);
  318. }
  319. #endif // defined(SDL_PLATFORM_WINDOWS)