platform-windows.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <algorithm>
  15. #include <sstream>
  16. #include "obs-config.h"
  17. #include "obs-app.hpp"
  18. #include "qt-wrappers.hpp"
  19. #include "platform.hpp"
  20. #include <util/windows/win-version.h>
  21. #include <util/platform.h>
  22. #define WIN32_LEAN_AND_MEAN
  23. #include <windows.h>
  24. #include <shellapi.h>
  25. #include <shlobj.h>
  26. #include <Dwmapi.h>
  27. #include <mmdeviceapi.h>
  28. #include <audiopolicy.h>
  29. #include <util/windows/WinHandle.hpp>
  30. #include <util/windows/HRError.hpp>
  31. #include <util/windows/ComPtr.hpp>
  32. using namespace std;
  33. static inline bool check_path(const char *data, const char *path,
  34. string &output)
  35. {
  36. ostringstream str;
  37. str << path << data;
  38. output = str.str();
  39. blog(LOG_DEBUG, "Attempted path: %s", output.c_str());
  40. return os_file_exists(output.c_str());
  41. }
  42. bool GetDataFilePath(const char *data, string &output)
  43. {
  44. if (check_path(data, "data/obs-studio/", output))
  45. return true;
  46. return check_path(data, OBS_DATA_PATH "/obs-studio/", output);
  47. }
  48. string GetDefaultVideoSavePath()
  49. {
  50. wchar_t path_utf16[MAX_PATH];
  51. char path_utf8[MAX_PATH] = {};
  52. SHGetFolderPathW(NULL, CSIDL_MYVIDEO, NULL, SHGFP_TYPE_CURRENT,
  53. path_utf16);
  54. os_wcs_to_utf8(path_utf16, wcslen(path_utf16), path_utf8, MAX_PATH);
  55. return string(path_utf8);
  56. }
  57. static vector<string> GetUserPreferredLocales()
  58. {
  59. vector<string> result;
  60. ULONG num, length = 0;
  61. if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num, nullptr,
  62. &length))
  63. return result;
  64. vector<wchar_t> buffer(length);
  65. if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num,
  66. &buffer.front(), &length))
  67. return result;
  68. result.reserve(num);
  69. auto start = begin(buffer);
  70. auto end_ = end(buffer);
  71. decltype(start) separator;
  72. while ((separator = find(start, end_, 0)) != end_) {
  73. if (result.size() == num)
  74. break;
  75. char conv[MAX_PATH] = {};
  76. os_wcs_to_utf8(&*start, separator - start, conv, MAX_PATH);
  77. result.emplace_back(conv);
  78. start = separator + 1;
  79. }
  80. return result;
  81. }
  82. vector<string> GetPreferredLocales()
  83. {
  84. vector<string> windows_locales = GetUserPreferredLocales();
  85. auto obs_locales = GetLocaleNames();
  86. auto windows_to_obs = [&obs_locales](string windows) {
  87. string lang_match;
  88. for (auto &locale_pair : obs_locales) {
  89. auto &locale = locale_pair.first;
  90. if (locale == windows.substr(0, locale.size()))
  91. return locale;
  92. if (lang_match.size())
  93. continue;
  94. if (locale.substr(0, 2) == windows.substr(0, 2))
  95. lang_match = locale;
  96. }
  97. return lang_match;
  98. };
  99. vector<string> result;
  100. result.reserve(obs_locales.size());
  101. for (const string &locale : windows_locales) {
  102. string match = windows_to_obs(locale);
  103. if (!match.size())
  104. continue;
  105. if (find(begin(result), end(result), match) != end(result))
  106. continue;
  107. result.emplace_back(match);
  108. }
  109. return result;
  110. }
  111. uint32_t GetWindowsVersion()
  112. {
  113. static uint32_t ver = 0;
  114. if (ver == 0) {
  115. struct win_version_info ver_info;
  116. get_win_ver(&ver_info);
  117. ver = (ver_info.major << 8) | ver_info.minor;
  118. }
  119. return ver;
  120. }
  121. uint32_t GetWindowsBuild()
  122. {
  123. static uint32_t build = 0;
  124. if (build == 0) {
  125. struct win_version_info ver_info;
  126. get_win_ver(&ver_info);
  127. build = ver_info.build;
  128. }
  129. return build;
  130. }
  131. bool IsAlwaysOnTop(QWidget *window)
  132. {
  133. DWORD exStyle = GetWindowLong((HWND)window->winId(), GWL_EXSTYLE);
  134. return (exStyle & WS_EX_TOPMOST) != 0;
  135. }
  136. void SetAlwaysOnTop(QWidget *window, bool enable)
  137. {
  138. HWND hwnd = (HWND)window->winId();
  139. SetWindowPos(hwnd, enable ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
  140. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
  141. }
  142. void SetProcessPriority(const char *priority)
  143. {
  144. if (!priority)
  145. return;
  146. if (strcmp(priority, "High") == 0)
  147. SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
  148. else if (strcmp(priority, "AboveNormal") == 0)
  149. SetPriorityClass(GetCurrentProcess(),
  150. ABOVE_NORMAL_PRIORITY_CLASS);
  151. else if (strcmp(priority, "Normal") == 0)
  152. SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
  153. else if (strcmp(priority, "BelowNormal") == 0)
  154. SetPriorityClass(GetCurrentProcess(),
  155. BELOW_NORMAL_PRIORITY_CLASS);
  156. else if (strcmp(priority, "Idle") == 0)
  157. SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
  158. }
  159. void SetWin32DropStyle(QWidget *window)
  160. {
  161. HWND hwnd = (HWND)window->winId();
  162. LONG_PTR ex_style = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
  163. ex_style |= WS_EX_ACCEPTFILES;
  164. SetWindowLongPtr(hwnd, GWL_EXSTYLE, ex_style);
  165. }
  166. bool SetDisplayAffinitySupported(void)
  167. {
  168. static bool checked = false;
  169. static bool supported;
  170. /* this has to be version gated as setting WDA_EXCLUDEFROMCAPTURE on
  171. older Windows builds behaves like WDA_MONITOR (black box) */
  172. if (!checked) {
  173. if (GetWindowsVersion() > 0x0A00 ||
  174. GetWindowsVersion() == 0x0A00 && GetWindowsBuild() >= 19041)
  175. supported = true;
  176. else
  177. supported = false;
  178. checked = true;
  179. }
  180. return supported;
  181. }
  182. bool DisableAudioDucking(bool disable)
  183. {
  184. ComPtr<IMMDeviceEnumerator> devEmum;
  185. ComPtr<IMMDevice> device;
  186. ComPtr<IAudioSessionManager2> sessionManager2;
  187. ComPtr<IAudioSessionControl> sessionControl;
  188. ComPtr<IAudioSessionControl2> sessionControl2;
  189. HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
  190. CLSCTX_INPROC_SERVER,
  191. __uuidof(IMMDeviceEnumerator),
  192. (void **)&devEmum);
  193. if (FAILED(result))
  194. return false;
  195. result = devEmum->GetDefaultAudioEndpoint(eRender, eConsole, &device);
  196. if (FAILED(result))
  197. return false;
  198. result = device->Activate(__uuidof(IAudioSessionManager2),
  199. CLSCTX_INPROC_SERVER, nullptr,
  200. (void **)&sessionManager2);
  201. if (FAILED(result))
  202. return false;
  203. result = sessionManager2->GetAudioSessionControl(nullptr, 0,
  204. &sessionControl);
  205. if (FAILED(result))
  206. return false;
  207. result = sessionControl->QueryInterface(&sessionControl2);
  208. if (FAILED(result))
  209. return false;
  210. result = sessionControl2->SetDuckingPreference(disable);
  211. return SUCCEEDED(result);
  212. }
  213. struct RunOnceMutexData {
  214. WinHandle handle;
  215. inline RunOnceMutexData(HANDLE h) : handle(h) {}
  216. };
  217. RunOnceMutex::RunOnceMutex(RunOnceMutex &&rom)
  218. {
  219. delete data;
  220. data = rom.data;
  221. rom.data = nullptr;
  222. }
  223. RunOnceMutex::~RunOnceMutex()
  224. {
  225. delete data;
  226. }
  227. RunOnceMutex &RunOnceMutex::operator=(RunOnceMutex &&rom)
  228. {
  229. delete data;
  230. data = rom.data;
  231. rom.data = nullptr;
  232. return *this;
  233. }
  234. RunOnceMutex CheckIfAlreadyRunning(bool &already_running)
  235. {
  236. string name;
  237. if (!portable_mode) {
  238. name = "OBSStudioCore";
  239. } else {
  240. char path[500];
  241. char absPath[512];
  242. *path = 0;
  243. *absPath = 0;
  244. GetConfigPath(path, sizeof(path), "");
  245. os_get_abs_path(path, absPath, sizeof(absPath));
  246. name = "OBSStudioPortable";
  247. name += absPath;
  248. }
  249. BPtr<wchar_t> wname;
  250. os_utf8_to_wcs_ptr(name.c_str(), name.size(), &wname);
  251. if (wname) {
  252. wchar_t *temp = wname;
  253. while (*temp) {
  254. if (!iswalnum(*temp))
  255. *temp = L'_';
  256. temp++;
  257. }
  258. }
  259. HANDLE h = OpenMutexW(SYNCHRONIZE, false, wname.Get());
  260. already_running = !!h;
  261. if (!already_running)
  262. h = CreateMutexW(nullptr, false, wname.Get());
  263. RunOnceMutex rom(h ? new RunOnceMutexData(h) : nullptr);
  264. return rom;
  265. }
  266. struct MonitorData {
  267. const wchar_t *id;
  268. MONITORINFOEX info;
  269. bool found;
  270. };
  271. static BOOL CALLBACK GetMonitorCallback(HMONITOR monitor, HDC, LPRECT,
  272. LPARAM param)
  273. {
  274. MonitorData *data = (MonitorData *)param;
  275. if (GetMonitorInfoW(monitor, &data->info)) {
  276. if (wcscmp(data->info.szDevice, data->id) == 0) {
  277. data->found = true;
  278. return false;
  279. }
  280. }
  281. return true;
  282. }
  283. #if QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
  284. #define GENERIC_MONITOR_NAME QStringLiteral("Generic PnP Monitor")
  285. QString GetMonitorName(const QString &id)
  286. {
  287. MonitorData data = {};
  288. data.id = (const wchar_t *)id.utf16();
  289. data.info.cbSize = sizeof(data.info);
  290. EnumDisplayMonitors(nullptr, nullptr, GetMonitorCallback,
  291. (LPARAM)&data);
  292. if (!data.found) {
  293. return GENERIC_MONITOR_NAME;
  294. }
  295. UINT32 numPath, numMode;
  296. if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath,
  297. &numMode) != ERROR_SUCCESS) {
  298. return GENERIC_MONITOR_NAME;
  299. }
  300. std::vector<DISPLAYCONFIG_PATH_INFO> paths(numPath);
  301. std::vector<DISPLAYCONFIG_MODE_INFO> modes(numMode);
  302. if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath, paths.data(),
  303. &numMode, modes.data(),
  304. nullptr) != ERROR_SUCCESS) {
  305. return GENERIC_MONITOR_NAME;
  306. }
  307. DISPLAYCONFIG_TARGET_DEVICE_NAME target;
  308. bool found = false;
  309. paths.resize(numPath);
  310. for (size_t i = 0; i < numPath; ++i) {
  311. const DISPLAYCONFIG_PATH_INFO &path = paths[i];
  312. DISPLAYCONFIG_SOURCE_DEVICE_NAME s;
  313. s.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
  314. s.header.size = sizeof(s);
  315. s.header.adapterId = path.sourceInfo.adapterId;
  316. s.header.id = path.sourceInfo.id;
  317. if (DisplayConfigGetDeviceInfo(&s.header) == ERROR_SUCCESS &&
  318. wcscmp(data.info.szDevice, s.viewGdiDeviceName) == 0) {
  319. target.header.type =
  320. DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
  321. target.header.size = sizeof(target);
  322. target.header.adapterId = path.sourceInfo.adapterId;
  323. target.header.id = path.targetInfo.id;
  324. found = DisplayConfigGetDeviceInfo(&target.header) ==
  325. ERROR_SUCCESS;
  326. break;
  327. }
  328. }
  329. if (!found) {
  330. return GENERIC_MONITOR_NAME;
  331. }
  332. return QString::fromWCharArray(target.monitorFriendlyDeviceName);
  333. }
  334. #endif
  335. /* Based on https://www.winehq.org/pipermail/wine-devel/2008-September/069387.html */
  336. typedef const char *(CDECL *WINEGETVERSION)(void);
  337. bool IsRunningOnWine()
  338. {
  339. WINEGETVERSION func;
  340. HMODULE nt;
  341. nt = GetModuleHandleW(L"ntdll");
  342. if (!nt)
  343. return false;
  344. func = (WINEGETVERSION)GetProcAddress(nt, "wine_get_version");
  345. if (func) {
  346. blog(LOG_WARNING, "Running on Wine version \"%s\"", func());
  347. return true;
  348. }
  349. return false;
  350. }
  351. HWND hwnd;
  352. void TaskbarOverlayInit()
  353. {
  354. hwnd = (HWND)App()->GetMainWindow()->winId();
  355. }
  356. void TaskbarOverlaySetStatus(TaskbarOverlayStatus status)
  357. {
  358. ITaskbarList4 *taskbarIcon;
  359. auto hr = CoCreateInstance(CLSID_TaskbarList, NULL,
  360. CLSCTX_INPROC_SERVER,
  361. IID_PPV_ARGS(&taskbarIcon));
  362. if (FAILED(hr)) {
  363. taskbarIcon->Release();
  364. return;
  365. }
  366. hr = taskbarIcon->HrInit();
  367. if (FAILED(hr)) {
  368. taskbarIcon->Release();
  369. return;
  370. }
  371. QIcon qicon;
  372. switch (status) {
  373. case TaskbarOverlayStatusActive:
  374. qicon = QIcon::fromTheme("obs-active",
  375. QIcon(":/res/images/active.png"));
  376. break;
  377. case TaskbarOverlayStatusPaused:
  378. qicon = QIcon::fromTheme("obs-paused",
  379. QIcon(":/res/images/paused.png"));
  380. break;
  381. case TaskbarOverlayStatusInactive:
  382. taskbarIcon->SetOverlayIcon(hwnd, nullptr, nullptr);
  383. taskbarIcon->Release();
  384. return;
  385. }
  386. HICON hicon = nullptr;
  387. if (!qicon.isNull()) {
  388. Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &p);
  389. hicon = qt_pixmapToWinHICON(
  390. qicon.pixmap(GetSystemMetrics(SM_CXSMICON)));
  391. if (!hicon)
  392. return;
  393. }
  394. taskbarIcon->SetOverlayIcon(hwnd, hicon, nullptr);
  395. DestroyIcon(hicon);
  396. taskbarIcon->Release();
  397. }