obs-app.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh 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 <time.h>
  15. #include <stdio.h>
  16. #include <wchar.h>
  17. #include <chrono>
  18. #include <ratio>
  19. #include <string>
  20. #include <sstream>
  21. #include <mutex>
  22. #include <util/bmem.h>
  23. #include <util/dstr.h>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <obs-config.h>
  27. #include <obs.hpp>
  28. #include <QGuiApplication>
  29. #include <QProxyStyle>
  30. #include <QScreen>
  31. #include "qt-wrappers.hpp"
  32. #include "obs-app.hpp"
  33. #include "window-basic-main.hpp"
  34. #include "window-basic-settings.hpp"
  35. #include "window-license-agreement.hpp"
  36. #include "crash-report.hpp"
  37. #include "platform.hpp"
  38. #include <fstream>
  39. #include <curl/curl.h>
  40. #ifdef _WIN32
  41. #include <windows.h>
  42. #else
  43. #include <signal.h>
  44. #endif
  45. #include <iostream>
  46. using namespace std;
  47. static log_handler_t def_log_handler;
  48. static string currentLogFile;
  49. static string lastLogFile;
  50. static bool portable_mode = false;
  51. static bool log_verbose = false;
  52. static bool unfiltered_log = false;
  53. bool opt_start_streaming = false;
  54. bool opt_start_recording = false;
  55. bool opt_studio_mode = false;
  56. bool opt_start_replaybuffer = false;
  57. bool opt_minimize_tray = false;
  58. bool opt_allow_opengl = false;
  59. bool opt_always_on_top = false;
  60. string opt_starting_collection;
  61. string opt_starting_profile;
  62. string opt_starting_scene;
  63. // AMD PowerXpress High Performance Flags
  64. #ifdef _MSC_VER
  65. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  66. #endif
  67. QObject *CreateShortcutFilter()
  68. {
  69. return new OBSEventFilter([](QObject *obj, QEvent *event)
  70. {
  71. auto mouse_event = [](QMouseEvent &event)
  72. {
  73. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  74. bool pressed = event.type() == QEvent::MouseButtonPress;
  75. switch (event.button()) {
  76. case Qt::NoButton:
  77. case Qt::LeftButton:
  78. case Qt::RightButton:
  79. case Qt::AllButtons:
  80. case Qt::MouseButtonMask:
  81. return false;
  82. case Qt::MidButton:
  83. hotkey.key = OBS_KEY_MOUSE3;
  84. break;
  85. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  86. hotkey.key = OBS_KEY_MOUSE ## j; break;
  87. MAP_BUTTON( 1, 4);
  88. MAP_BUTTON( 2, 5);
  89. MAP_BUTTON( 3, 6);
  90. MAP_BUTTON( 4, 7);
  91. MAP_BUTTON( 5, 8);
  92. MAP_BUTTON( 6, 9);
  93. MAP_BUTTON( 7, 10);
  94. MAP_BUTTON( 8, 11);
  95. MAP_BUTTON( 9, 12);
  96. MAP_BUTTON(10, 13);
  97. MAP_BUTTON(11, 14);
  98. MAP_BUTTON(12, 15);
  99. MAP_BUTTON(13, 16);
  100. MAP_BUTTON(14, 17);
  101. MAP_BUTTON(15, 18);
  102. MAP_BUTTON(16, 19);
  103. MAP_BUTTON(17, 20);
  104. MAP_BUTTON(18, 21);
  105. MAP_BUTTON(19, 22);
  106. MAP_BUTTON(20, 23);
  107. MAP_BUTTON(21, 24);
  108. MAP_BUTTON(22, 25);
  109. MAP_BUTTON(23, 26);
  110. MAP_BUTTON(24, 27);
  111. #undef MAP_BUTTON
  112. }
  113. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  114. event.modifiers());
  115. obs_hotkey_inject_event(hotkey, pressed);
  116. return true;
  117. };
  118. auto key_event = [&](QKeyEvent *event)
  119. {
  120. QDialog *dialog = qobject_cast<QDialog*>(obj);
  121. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  122. bool pressed = event->type() == QEvent::KeyPress;
  123. switch (event->key()) {
  124. case Qt::Key_Shift:
  125. case Qt::Key_Control:
  126. case Qt::Key_Alt:
  127. case Qt::Key_Meta:
  128. break;
  129. #ifdef __APPLE__
  130. case Qt::Key_CapsLock:
  131. // kVK_CapsLock == 57
  132. hotkey.key = obs_key_from_virtual_key(57);
  133. pressed = true;
  134. break;
  135. #endif
  136. case Qt::Key_Enter:
  137. case Qt::Key_Escape:
  138. case Qt::Key_Return:
  139. if (dialog && pressed)
  140. return false;
  141. default:
  142. hotkey.key = obs_key_from_virtual_key(
  143. event->nativeVirtualKey());
  144. }
  145. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  146. event->modifiers());
  147. obs_hotkey_inject_event(hotkey, pressed);
  148. return true;
  149. };
  150. switch (event->type()) {
  151. case QEvent::MouseButtonPress:
  152. case QEvent::MouseButtonRelease:
  153. return mouse_event(*static_cast<QMouseEvent*>(event));
  154. /*case QEvent::MouseButtonDblClick:
  155. case QEvent::Wheel:*/
  156. case QEvent::KeyPress:
  157. case QEvent::KeyRelease:
  158. return key_event(static_cast<QKeyEvent*>(event));
  159. default:
  160. return false;
  161. }
  162. });
  163. }
  164. string CurrentTimeString()
  165. {
  166. using namespace std::chrono;
  167. struct tm tstruct;
  168. char buf[80];
  169. auto tp = system_clock::now();
  170. auto now = system_clock::to_time_t(tp);
  171. tstruct = *localtime(&now);
  172. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  173. if (ratio_less<system_clock::period, seconds::period>::value &&
  174. written && (sizeof(buf) - written) > 5) {
  175. auto tp_secs =
  176. time_point_cast<seconds>(tp);
  177. auto millis =
  178. duration_cast<milliseconds>(tp - tp_secs).count();
  179. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  180. static_cast<unsigned>(millis));
  181. }
  182. return buf;
  183. }
  184. string CurrentDateTimeString()
  185. {
  186. time_t now = time(0);
  187. struct tm tstruct;
  188. char buf[80];
  189. tstruct = *localtime(&now);
  190. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  191. return buf;
  192. }
  193. static inline void LogString(fstream &logFile, const char *timeString,
  194. char *str)
  195. {
  196. logFile << timeString << str << endl;
  197. }
  198. static inline void LogStringChunk(fstream &logFile, char *str)
  199. {
  200. char *nextLine = str;
  201. string timeString = CurrentTimeString();
  202. timeString += ": ";
  203. while (*nextLine) {
  204. char *nextLine = strchr(str, '\n');
  205. if (!nextLine)
  206. break;
  207. if (nextLine != str && nextLine[-1] == '\r') {
  208. nextLine[-1] = 0;
  209. } else {
  210. nextLine[0] = 0;
  211. }
  212. LogString(logFile, timeString.c_str(), str);
  213. nextLine++;
  214. str = nextLine;
  215. }
  216. LogString(logFile, timeString.c_str(), str);
  217. }
  218. #define MAX_REPEATED_LINES 30
  219. #define MAX_CHAR_VARIATION (255 * 3)
  220. static inline int sum_chars(const char *str)
  221. {
  222. int val = 0;
  223. for (; *str != 0; str++)
  224. val += *str;
  225. return val;
  226. }
  227. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  228. const char *output_str)
  229. {
  230. static mutex log_mutex;
  231. static const char *last_msg_ptr = nullptr;
  232. static int last_char_sum = 0;
  233. static char cmp_str[4096];
  234. static int rep_count = 0;
  235. int new_sum = sum_chars(output_str);
  236. lock_guard<mutex> guard(log_mutex);
  237. if (unfiltered_log) {
  238. return false;
  239. }
  240. if (last_msg_ptr == msg) {
  241. int diff = std::abs(new_sum - last_char_sum);
  242. if (diff < MAX_CHAR_VARIATION) {
  243. return (rep_count++ >= MAX_REPEATED_LINES);
  244. }
  245. }
  246. if (rep_count > MAX_REPEATED_LINES) {
  247. logFile << CurrentTimeString() <<
  248. ": Last log entry repeated for " <<
  249. to_string(rep_count - MAX_REPEATED_LINES) <<
  250. " more lines" << endl;
  251. }
  252. last_msg_ptr = msg;
  253. strcpy(cmp_str, output_str);
  254. last_char_sum = new_sum;
  255. rep_count = 0;
  256. return false;
  257. }
  258. static void do_log(int log_level, const char *msg, va_list args, void *param)
  259. {
  260. fstream &logFile = *static_cast<fstream*>(param);
  261. char str[4096];
  262. #ifndef _WIN32
  263. va_list args2;
  264. va_copy(args2, args);
  265. #endif
  266. vsnprintf(str, 4095, msg, args);
  267. #ifdef _WIN32
  268. if (IsDebuggerPresent()) {
  269. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  270. if (wNum > 1) {
  271. static wstring wide_buf;
  272. static mutex wide_mutex;
  273. lock_guard<mutex> lock(wide_mutex);
  274. wide_buf.reserve(wNum + 1);
  275. wide_buf.resize(wNum - 1);
  276. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  277. wNum);
  278. wide_buf.push_back('\n');
  279. OutputDebugStringW(wide_buf.c_str());
  280. }
  281. }
  282. #else
  283. def_log_handler(log_level, msg, args2, nullptr);
  284. #endif
  285. if (too_many_repeated_entries(logFile, msg, str))
  286. return;
  287. if (log_level <= LOG_INFO || log_verbose)
  288. LogStringChunk(logFile, str);
  289. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  290. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  291. __debugbreak();
  292. #endif
  293. }
  294. #define DEFAULT_LANG "en-US"
  295. bool OBSApp::InitGlobalConfigDefaults()
  296. {
  297. config_set_default_string(globalConfig, "General", "Language",
  298. DEFAULT_LANG);
  299. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  300. config_set_default_string(globalConfig, "General", "ProcessPriority",
  301. "Normal");
  302. config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
  303. true);
  304. #if _WIN32
  305. config_set_default_string(globalConfig, "Video", "Renderer",
  306. "Direct3D 11");
  307. #else
  308. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  309. #endif
  310. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  311. true);
  312. config_set_default_bool(globalConfig, "BasicWindow",
  313. "PreviewProgramMode", false);
  314. config_set_default_bool(globalConfig, "BasicWindow",
  315. "SceneDuplicationMode", true);
  316. config_set_default_bool(globalConfig, "BasicWindow",
  317. "SwapScenesMode", true);
  318. config_set_default_bool(globalConfig, "BasicWindow",
  319. "SnappingEnabled", true);
  320. config_set_default_bool(globalConfig, "BasicWindow",
  321. "ScreenSnapping", true);
  322. config_set_default_bool(globalConfig, "BasicWindow",
  323. "SourceSnapping", true);
  324. config_set_default_bool(globalConfig, "BasicWindow",
  325. "CenterSnapping", false);
  326. config_set_default_double(globalConfig, "BasicWindow",
  327. "SnapDistance", 10.0);
  328. config_set_default_bool(globalConfig, "BasicWindow",
  329. "RecordWhenStreaming", false);
  330. config_set_default_bool(globalConfig, "BasicWindow",
  331. "KeepRecordingWhenStreamStops", false);
  332. config_set_default_bool(globalConfig, "BasicWindow",
  333. "SysTrayEnabled", true);
  334. config_set_default_bool(globalConfig, "BasicWindow",
  335. "SysTrayWhenStarted", false);
  336. config_set_default_bool(globalConfig, "BasicWindow",
  337. "SaveProjectors", false);
  338. config_set_default_bool(globalConfig, "BasicWindow",
  339. "ShowTransitions", true);
  340. config_set_default_bool(globalConfig, "BasicWindow",
  341. "ShowListboxToolbars", true);
  342. config_set_default_bool(globalConfig, "BasicWindow",
  343. "ShowStatusBar", true);
  344. #ifdef _WIN32
  345. config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
  346. true);
  347. #endif
  348. #ifdef __APPLE__
  349. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  350. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  351. true);
  352. #endif
  353. return true;
  354. }
  355. static bool do_mkdir(const char *path)
  356. {
  357. if (os_mkdirs(path) == MKDIR_ERROR) {
  358. OBSErrorBox(NULL, "Failed to create directory %s", path);
  359. return false;
  360. }
  361. return true;
  362. }
  363. static bool MakeUserDirs()
  364. {
  365. char path[512];
  366. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  367. return false;
  368. if (!do_mkdir(path))
  369. return false;
  370. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  371. return false;
  372. if (!do_mkdir(path))
  373. return false;
  374. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  375. return false;
  376. if (!do_mkdir(path))
  377. return false;
  378. #ifdef _WIN32
  379. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  380. return false;
  381. if (!do_mkdir(path))
  382. return false;
  383. if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  384. return false;
  385. if (!do_mkdir(path))
  386. return false;
  387. #endif
  388. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  389. return false;
  390. if (!do_mkdir(path))
  391. return false;
  392. return true;
  393. }
  394. static bool MakeUserProfileDirs()
  395. {
  396. char path[512];
  397. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  398. return false;
  399. if (!do_mkdir(path))
  400. return false;
  401. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  402. return false;
  403. if (!do_mkdir(path))
  404. return false;
  405. return true;
  406. }
  407. static string GetProfileDirFromName(const char *name)
  408. {
  409. string outputPath;
  410. os_glob_t *glob;
  411. char path[512];
  412. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  413. return outputPath;
  414. strcat(path, "/*");
  415. if (os_glob(path, 0, &glob) != 0)
  416. return outputPath;
  417. for (size_t i = 0; i < glob->gl_pathc; i++) {
  418. struct os_globent ent = glob->gl_pathv[i];
  419. if (!ent.directory)
  420. continue;
  421. strcpy(path, ent.path);
  422. strcat(path, "/basic.ini");
  423. ConfigFile config;
  424. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  425. continue;
  426. const char *curName = config_get_string(config, "General",
  427. "Name");
  428. if (astrcmpi(curName, name) == 0) {
  429. outputPath = ent.path;
  430. break;
  431. }
  432. }
  433. os_globfree(glob);
  434. if (!outputPath.empty()) {
  435. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  436. const char *start = strrchr(outputPath.c_str(), '/');
  437. if (start)
  438. outputPath.erase(0, start - outputPath.c_str() + 1);
  439. }
  440. return outputPath;
  441. }
  442. static string GetSceneCollectionFileFromName(const char *name)
  443. {
  444. string outputPath;
  445. os_glob_t *glob;
  446. char path[512];
  447. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  448. return outputPath;
  449. strcat(path, "/*.json");
  450. if (os_glob(path, 0, &glob) != 0)
  451. return outputPath;
  452. for (size_t i = 0; i < glob->gl_pathc; i++) {
  453. struct os_globent ent = glob->gl_pathv[i];
  454. if (ent.directory)
  455. continue;
  456. obs_data_t *data =
  457. obs_data_create_from_json_file_safe(ent.path, "bak");
  458. const char *curName = obs_data_get_string(data, "name");
  459. if (astrcmpi(name, curName) == 0) {
  460. outputPath = ent.path;
  461. obs_data_release(data);
  462. break;
  463. }
  464. obs_data_release(data);
  465. }
  466. os_globfree(glob);
  467. if (!outputPath.empty()) {
  468. outputPath.resize(outputPath.size() - 5);
  469. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  470. const char *start = strrchr(outputPath.c_str(), '/');
  471. if (start)
  472. outputPath.erase(0, start - outputPath.c_str() + 1);
  473. }
  474. return outputPath;
  475. }
  476. bool OBSApp::InitGlobalConfig()
  477. {
  478. char path[512];
  479. int len = GetConfigPath(path, sizeof(path),
  480. "obs-studio/global.ini");
  481. if (len <= 0) {
  482. return false;
  483. }
  484. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  485. if (errorcode != CONFIG_SUCCESS) {
  486. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  487. return false;
  488. }
  489. if (!opt_starting_collection.empty()) {
  490. string path = GetSceneCollectionFileFromName(
  491. opt_starting_collection.c_str());
  492. if (!path.empty()) {
  493. config_set_string(globalConfig,
  494. "Basic", "SceneCollection",
  495. opt_starting_collection.c_str());
  496. config_set_string(globalConfig,
  497. "Basic", "SceneCollectionFile",
  498. path.c_str());
  499. }
  500. }
  501. if (!opt_starting_profile.empty()) {
  502. string path = GetProfileDirFromName(
  503. opt_starting_profile.c_str());
  504. if (!path.empty()) {
  505. config_set_string(globalConfig, "Basic", "Profile",
  506. opt_starting_profile.c_str());
  507. config_set_string(globalConfig, "Basic", "ProfileDir",
  508. path.c_str());
  509. }
  510. }
  511. return InitGlobalConfigDefaults();
  512. }
  513. bool OBSApp::InitLocale()
  514. {
  515. ProfileScope("OBSApp::InitLocale");
  516. const char *lang = config_get_string(globalConfig, "General",
  517. "Language");
  518. locale = lang;
  519. string englishPath;
  520. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  521. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  522. return false;
  523. }
  524. textLookup = text_lookup_create(englishPath.c_str());
  525. if (!textLookup) {
  526. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  527. englishPath.c_str());
  528. return false;
  529. }
  530. bool userLocale = config_has_user_value(globalConfig, "General",
  531. "Language");
  532. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  533. if (userLocale && defaultLang)
  534. return true;
  535. if (!userLocale && defaultLang) {
  536. for (auto &locale_ : GetPreferredLocales()) {
  537. if (locale_ == lang)
  538. return true;
  539. stringstream file;
  540. file << "locale/" << locale_ << ".ini";
  541. string path;
  542. if (!GetDataFilePath(file.str().c_str(), path))
  543. continue;
  544. if (!text_lookup_add(textLookup, path.c_str()))
  545. continue;
  546. blog(LOG_INFO, "Using preferred locale '%s'",
  547. locale_.c_str());
  548. locale = locale_;
  549. return true;
  550. }
  551. return true;
  552. }
  553. stringstream file;
  554. file << "locale/" << lang << ".ini";
  555. string path;
  556. if (GetDataFilePath(file.str().c_str(), path)) {
  557. if (!text_lookup_add(textLookup, path.c_str()))
  558. blog(LOG_ERROR, "Failed to add locale file '%s'",
  559. path.c_str());
  560. } else {
  561. blog(LOG_ERROR, "Could not find locale file '%s'",
  562. file.str().c_str());
  563. }
  564. return true;
  565. }
  566. bool OBSApp::SetTheme(std::string name, std::string path)
  567. {
  568. theme = name;
  569. /* Check user dir first, then preinstalled themes. */
  570. if (path == "") {
  571. char userDir[512];
  572. name = "themes/" + name + ".qss";
  573. string temp = "obs-studio/" + name;
  574. int ret = GetConfigPath(userDir, sizeof(userDir),
  575. temp.c_str());
  576. if (ret > 0 && QFile::exists(userDir)) {
  577. path = string(userDir);
  578. } else if (!GetDataFilePath(name.c_str(), path)) {
  579. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  580. return false;
  581. }
  582. }
  583. QString mpath = QString("file:///") + path.c_str();
  584. setStyleSheet(mpath);
  585. return true;
  586. }
  587. bool OBSApp::InitTheme()
  588. {
  589. const char *themeName = config_get_string(globalConfig, "General",
  590. "Theme");
  591. if (!themeName)
  592. themeName = "Default";
  593. stringstream t;
  594. t << themeName;
  595. return SetTheme(t.str());
  596. }
  597. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  598. : QApplication(argc, argv),
  599. profilerNameStore(store)
  600. {
  601. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  602. }
  603. OBSApp::~OBSApp()
  604. {
  605. #ifdef _WIN32
  606. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  607. "DisableAudioDucking");
  608. if (disableAudioDucking)
  609. DisableAudioDucking(false);
  610. #endif
  611. #ifdef __APPLE__
  612. bool vsyncDiabled = config_get_bool(globalConfig, "Video",
  613. "DisableOSXVSync");
  614. bool resetVSync = config_get_bool(globalConfig, "Video",
  615. "ResetOSXVSyncOnExit");
  616. if (vsyncDiabled && resetVSync)
  617. EnableOSXVSync(true);
  618. #endif
  619. os_inhibit_sleep_set_active(sleepInhibitor, false);
  620. os_inhibit_sleep_destroy(sleepInhibitor);
  621. }
  622. static void move_basic_to_profiles(void)
  623. {
  624. char path[512];
  625. char new_path[512];
  626. os_glob_t *glob;
  627. /* if not first time use */
  628. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  629. return;
  630. if (!os_file_exists(path))
  631. return;
  632. /* if the profiles directory doesn't already exist */
  633. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  634. return;
  635. if (os_file_exists(new_path))
  636. return;
  637. if (os_mkdir(new_path) == MKDIR_ERROR)
  638. return;
  639. strcat(new_path, "/");
  640. strcat(new_path, Str("Untitled"));
  641. if (os_mkdir(new_path) == MKDIR_ERROR)
  642. return;
  643. strcat(path, "/*.*");
  644. if (os_glob(path, 0, &glob) != 0)
  645. return;
  646. strcpy(path, new_path);
  647. for (size_t i = 0; i < glob->gl_pathc; i++) {
  648. struct os_globent ent = glob->gl_pathv[i];
  649. char *file;
  650. if (ent.directory)
  651. continue;
  652. file = strrchr(ent.path, '/');
  653. if (!file++)
  654. continue;
  655. if (astrcmpi(file, "scenes.json") == 0)
  656. continue;
  657. strcpy(new_path, path);
  658. strcat(new_path, "/");
  659. strcat(new_path, file);
  660. os_rename(ent.path, new_path);
  661. }
  662. os_globfree(glob);
  663. }
  664. static void move_basic_to_scene_collections(void)
  665. {
  666. char path[512];
  667. char new_path[512];
  668. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  669. return;
  670. if (!os_file_exists(path))
  671. return;
  672. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  673. return;
  674. if (os_file_exists(new_path))
  675. return;
  676. if (os_mkdir(new_path) == MKDIR_ERROR)
  677. return;
  678. strcat(path, "/scenes.json");
  679. strcat(new_path, "/");
  680. strcat(new_path, Str("Untitled"));
  681. strcat(new_path, ".json");
  682. os_rename(path, new_path);
  683. }
  684. void OBSApp::AppInit()
  685. {
  686. ProfileScope("OBSApp::AppInit");
  687. if (!InitApplicationBundle())
  688. throw "Failed to initialize application bundle";
  689. if (!MakeUserDirs())
  690. throw "Failed to create required user directories";
  691. if (!InitGlobalConfig())
  692. throw "Failed to initialize global config";
  693. if (!InitLocale())
  694. throw "Failed to load locale";
  695. if (!InitTheme())
  696. throw "Failed to load theme";
  697. config_set_default_string(globalConfig, "Basic", "Profile",
  698. Str("Untitled"));
  699. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  700. Str("Untitled"));
  701. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  702. Str("Untitled"));
  703. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  704. Str("Untitled"));
  705. #ifdef _WIN32
  706. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  707. "DisableAudioDucking");
  708. if (disableAudioDucking)
  709. DisableAudioDucking(true);
  710. #endif
  711. #ifdef __APPLE__
  712. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  713. EnableOSXVSync(false);
  714. #endif
  715. move_basic_to_profiles();
  716. move_basic_to_scene_collections();
  717. if (!MakeUserProfileDirs())
  718. throw "Failed to create profile directories";
  719. }
  720. const char *OBSApp::GetRenderModule() const
  721. {
  722. const char *renderer = config_get_string(globalConfig, "Video",
  723. "Renderer");
  724. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  725. DL_D3D11 : DL_OPENGL;
  726. }
  727. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  728. {
  729. char path[512];
  730. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  731. return false;
  732. return obs_startup(locale, path, store);
  733. }
  734. bool OBSApp::OBSInit()
  735. {
  736. ProfileScope("OBSApp::OBSInit");
  737. bool licenseAccepted = config_get_bool(globalConfig, "General",
  738. "LicenseAccepted");
  739. OBSLicenseAgreement agreement(nullptr);
  740. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  741. if (!licenseAccepted) {
  742. config_set_bool(globalConfig, "General",
  743. "LicenseAccepted", true);
  744. config_save(globalConfig);
  745. }
  746. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  747. return false;
  748. blog(LOG_INFO, "Portable mode: %s",
  749. portable_mode ? "true" : "false");
  750. mainWindow = new OBSBasic();
  751. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  752. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  753. mainWindow->OBSInit();
  754. connect(this, &QGuiApplication::applicationStateChanged,
  755. [](Qt::ApplicationState state)
  756. {
  757. obs_hotkey_enable_background_press(
  758. state != Qt::ApplicationActive);
  759. });
  760. obs_hotkey_enable_background_press(
  761. applicationState() != Qt::ApplicationActive);
  762. return true;
  763. } else {
  764. return false;
  765. }
  766. }
  767. string OBSApp::GetVersionString() const
  768. {
  769. stringstream ver;
  770. #ifdef HAVE_OBSCONFIG_H
  771. ver << OBS_VERSION;
  772. #else
  773. ver << LIBOBS_API_MAJOR_VER << "." <<
  774. LIBOBS_API_MINOR_VER << "." <<
  775. LIBOBS_API_PATCH_VER;
  776. #endif
  777. ver << " (";
  778. #ifdef _WIN32
  779. if (sizeof(void*) == 8)
  780. ver << "64bit, ";
  781. ver << "windows)";
  782. #elif __APPLE__
  783. ver << "mac)";
  784. #elif __FreeBSD__
  785. ver << "freebsd)";
  786. #else /* assume linux for the time being */
  787. ver << "linux)";
  788. #endif
  789. return ver.str();
  790. }
  791. bool OBSApp::IsPortableMode()
  792. {
  793. return portable_mode;
  794. }
  795. #ifdef __APPLE__
  796. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  797. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  798. #elif _WIN32
  799. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  800. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  801. #else
  802. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  803. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  804. #endif
  805. const char *OBSApp::InputAudioSource() const
  806. {
  807. return INPUT_AUDIO_SOURCE;
  808. }
  809. const char *OBSApp::OutputAudioSource() const
  810. {
  811. return OUTPUT_AUDIO_SOURCE;
  812. }
  813. const char *OBSApp::GetLastLog() const
  814. {
  815. return lastLogFile.c_str();
  816. }
  817. const char *OBSApp::GetCurrentLog() const
  818. {
  819. return currentLogFile.c_str();
  820. }
  821. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  822. {
  823. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  824. if (cb(lookupVal, out))
  825. return true;
  826. }
  827. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  828. }
  829. QString OBSTranslator::translate(const char *context, const char *sourceText,
  830. const char *disambiguation, int n) const
  831. {
  832. const char *out = nullptr;
  833. if (!App()->TranslateString(sourceText, &out))
  834. return QString(sourceText);
  835. UNUSED_PARAMETER(context);
  836. UNUSED_PARAMETER(disambiguation);
  837. UNUSED_PARAMETER(n);
  838. return QT_UTF8(out);
  839. }
  840. static bool get_token(lexer *lex, string &str, base_token_type type)
  841. {
  842. base_token token;
  843. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  844. return false;
  845. if (token.type != type)
  846. return false;
  847. str.assign(token.text.array, token.text.len);
  848. return true;
  849. }
  850. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  851. {
  852. base_token token;
  853. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  854. return false;
  855. if (token.type != type)
  856. return false;
  857. return strref_cmp(&token.text, str) == 0;
  858. }
  859. static uint64_t convert_log_name(const char *name)
  860. {
  861. BaseLexer lex;
  862. string year, month, day, hour, minute, second;
  863. lexer_start(lex, name);
  864. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  865. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  866. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  867. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  868. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  869. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  870. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  871. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  872. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  873. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  874. stringstream timestring;
  875. timestring << year << month << day << hour << minute << second;
  876. return std::stoull(timestring.str());
  877. }
  878. static void delete_oldest_file(const char *location)
  879. {
  880. BPtr<char> logDir(GetConfigPathPtr(location));
  881. string oldestLog;
  882. uint64_t oldest_ts = (uint64_t)-1;
  883. struct os_dirent *entry;
  884. unsigned int maxLogs = (unsigned int)config_get_uint(
  885. App()->GlobalConfig(), "General", "MaxLogs");
  886. os_dir_t *dir = os_opendir(logDir);
  887. if (dir) {
  888. unsigned int count = 0;
  889. while ((entry = os_readdir(dir)) != NULL) {
  890. if (entry->directory || *entry->d_name == '.')
  891. continue;
  892. uint64_t ts = convert_log_name(entry->d_name);
  893. if (ts) {
  894. if (ts < oldest_ts) {
  895. oldestLog = entry->d_name;
  896. oldest_ts = ts;
  897. }
  898. count++;
  899. }
  900. }
  901. os_closedir(dir);
  902. if (count > maxLogs) {
  903. stringstream delPath;
  904. delPath << logDir << "/" << oldestLog;
  905. os_unlink(delPath.str().c_str());
  906. }
  907. }
  908. }
  909. static void get_last_log(void)
  910. {
  911. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  912. struct os_dirent *entry;
  913. os_dir_t *dir = os_opendir(logDir);
  914. uint64_t highest_ts = 0;
  915. if (dir) {
  916. while ((entry = os_readdir(dir)) != NULL) {
  917. if (entry->directory || *entry->d_name == '.')
  918. continue;
  919. uint64_t ts = convert_log_name(entry->d_name);
  920. if (ts > highest_ts) {
  921. lastLogFile = entry->d_name;
  922. highest_ts = ts;
  923. }
  924. }
  925. os_closedir(dir);
  926. }
  927. }
  928. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  929. {
  930. time_t now = time(0);
  931. char file[256] = {};
  932. struct tm *cur_time;
  933. cur_time = localtime(&now);
  934. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  935. cur_time->tm_year+1900,
  936. cur_time->tm_mon+1,
  937. cur_time->tm_mday,
  938. noSpace ? '_' : ' ',
  939. cur_time->tm_hour,
  940. cur_time->tm_min,
  941. cur_time->tm_sec,
  942. extension);
  943. return string(file);
  944. }
  945. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  946. const char *format)
  947. {
  948. BPtr<char> filename = os_generate_formatted_filename(extension,
  949. !noSpace, format);
  950. return string(filename);
  951. }
  952. vector<pair<string, string>> GetLocaleNames()
  953. {
  954. string path;
  955. if (!GetDataFilePath("locale.ini", path))
  956. throw "Could not find locale.ini path";
  957. ConfigFile ini;
  958. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  959. throw "Could not open locale.ini";
  960. size_t sections = config_num_sections(ini);
  961. vector<pair<string, string>> names;
  962. names.reserve(sections);
  963. for (size_t i = 0; i < sections; i++) {
  964. const char *tag = config_get_section(ini, i);
  965. const char *name = config_get_string(ini, tag, "Name");
  966. names.emplace_back(tag, name);
  967. }
  968. return names;
  969. }
  970. static void create_log_file(fstream &logFile)
  971. {
  972. stringstream dst;
  973. get_last_log();
  974. currentLogFile = GenerateTimeDateFilename("txt");
  975. dst << "obs-studio/logs/" << currentLogFile.c_str();
  976. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  977. logFile.open(path,
  978. ios_base::in | ios_base::out | ios_base::trunc);
  979. if (logFile.is_open()) {
  980. delete_oldest_file("obs-studio/logs");
  981. base_set_log_handler(do_log, &logFile);
  982. } else {
  983. blog(LOG_ERROR, "Failed to open log file");
  984. }
  985. }
  986. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  987. {
  988. profiler_name_store_free(store);
  989. };
  990. using ProfilerNameStore =
  991. std::unique_ptr<profiler_name_store_t,
  992. decltype(ProfilerNameStoreRelease)>;
  993. ProfilerNameStore CreateNameStore()
  994. {
  995. return ProfilerNameStore{profiler_name_store_create(),
  996. ProfilerNameStoreRelease};
  997. }
  998. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  999. {
  1000. profile_snapshot_free(snap);
  1001. };
  1002. using ProfilerSnapshot =
  1003. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1004. ProfilerSnapshot GetSnapshot()
  1005. {
  1006. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1007. }
  1008. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1009. {
  1010. if (currentLogFile.empty())
  1011. return;
  1012. auto pos = currentLogFile.rfind('.');
  1013. if (pos == currentLogFile.npos)
  1014. return;
  1015. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1016. ostringstream dst;
  1017. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1018. dst.write(currentLogFile.c_str(), pos);
  1019. dst.write(LITERAL_SIZE(".csv.gz"));
  1020. #undef LITERAL_SIZE
  1021. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1022. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1023. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1024. static_cast<const char*>(path));
  1025. }
  1026. static auto ProfilerFree = [](void *)
  1027. {
  1028. profiler_stop();
  1029. auto snap = GetSnapshot();
  1030. profiler_print(snap.get());
  1031. profiler_print_time_between_calls(snap.get());
  1032. SaveProfilerData(snap);
  1033. profiler_free();
  1034. };
  1035. static const char *run_program_init = "run_program_init";
  1036. static int run_program(fstream &logFile, int argc, char *argv[])
  1037. {
  1038. int ret = -1;
  1039. auto profilerNameStore = CreateNameStore();
  1040. std::unique_ptr<void, decltype(ProfilerFree)>
  1041. prof_release(static_cast<void*>(&ProfilerFree),
  1042. ProfilerFree);
  1043. profiler_start();
  1044. profile_register_root(run_program_init, 0);
  1045. ScopeProfiler prof{run_program_init};
  1046. QCoreApplication::addLibraryPath(".");
  1047. OBSApp program(argc, argv, profilerNameStore.get());
  1048. try {
  1049. program.AppInit();
  1050. OBSTranslator translator;
  1051. create_log_file(logFile);
  1052. delete_oldest_file("obs-studio/profiler_data");
  1053. program.installTranslator(&translator);
  1054. if (!program.OBSInit())
  1055. return 0;
  1056. prof.Stop();
  1057. return program.exec();
  1058. } catch (const char *error) {
  1059. blog(LOG_ERROR, "%s", error);
  1060. OBSErrorBox(nullptr, "%s", error);
  1061. }
  1062. return ret;
  1063. }
  1064. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1065. #ifdef _WIN32
  1066. #define CRASH_MESSAGE \
  1067. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1068. "to the clipboard? (Crash logs will still be saved to the " \
  1069. "%appdata%\\obs-studio\\crashes directory)"
  1070. static void main_crash_handler(const char *format, va_list args, void *param)
  1071. {
  1072. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1073. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1074. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1075. delete_oldest_file("obs-studio/crashes");
  1076. string name = "obs-studio/crashes/Crash ";
  1077. name += GenerateTimeDateFilename("txt");
  1078. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1079. fstream file;
  1080. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1081. ios_base::binary);
  1082. file << text;
  1083. file.close();
  1084. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1085. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1086. if (ret == IDYES) {
  1087. size_t len = strlen(text);
  1088. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1089. memcpy(GlobalLock(mem), text, len);
  1090. GlobalUnlock(mem);
  1091. OpenClipboard(0);
  1092. EmptyClipboard();
  1093. SetClipboardData(CF_TEXT, mem);
  1094. CloseClipboard();
  1095. }
  1096. exit(-1);
  1097. UNUSED_PARAMETER(param);
  1098. }
  1099. static void load_debug_privilege(void)
  1100. {
  1101. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1102. TOKEN_PRIVILEGES tp;
  1103. HANDLE token;
  1104. LUID val;
  1105. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1106. return;
  1107. }
  1108. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1109. tp.PrivilegeCount = 1;
  1110. tp.Privileges[0].Luid = val;
  1111. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1112. AdjustTokenPrivileges(token, false, &tp,
  1113. sizeof(tp), NULL, NULL);
  1114. }
  1115. CloseHandle(token);
  1116. }
  1117. #endif
  1118. #ifdef __APPLE__
  1119. #define BASE_PATH ".."
  1120. #else
  1121. #define BASE_PATH "../.."
  1122. #endif
  1123. #define CONFIG_PATH BASE_PATH "/config"
  1124. #ifndef OBS_UNIX_STRUCTURE
  1125. #define OBS_UNIX_STRUCTURE 0
  1126. #endif
  1127. int GetConfigPath(char *path, size_t size, const char *name)
  1128. {
  1129. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1130. if (name && *name) {
  1131. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1132. } else {
  1133. return snprintf(path, size, CONFIG_PATH);
  1134. }
  1135. } else {
  1136. return os_get_config_path(path, size, name);
  1137. }
  1138. }
  1139. char *GetConfigPathPtr(const char *name)
  1140. {
  1141. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1142. char path[512];
  1143. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1144. return bstrdup(path);
  1145. } else {
  1146. return NULL;
  1147. }
  1148. } else {
  1149. return os_get_config_path_ptr(name);
  1150. }
  1151. }
  1152. int GetProgramDataPath(char *path, size_t size, const char *name)
  1153. {
  1154. return os_get_program_data_path(path, size, name);
  1155. }
  1156. char *GetProgramDataPathPtr(const char *name)
  1157. {
  1158. return os_get_program_data_path_ptr(name);
  1159. }
  1160. bool GetFileSafeName(const char *name, std::string &file)
  1161. {
  1162. size_t base_len = strlen(name);
  1163. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1164. std::wstring wfile;
  1165. if (!len)
  1166. return false;
  1167. wfile.resize(len);
  1168. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1169. for (size_t i = wfile.size(); i > 0; i--) {
  1170. size_t im1 = i - 1;
  1171. if (iswspace(wfile[im1])) {
  1172. wfile[im1] = '_';
  1173. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1174. wfile.erase(im1, 1);
  1175. }
  1176. }
  1177. if (wfile.size() == 0)
  1178. wfile = L"characters_only";
  1179. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1180. if (!len)
  1181. return false;
  1182. file.resize(len);
  1183. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1184. return true;
  1185. }
  1186. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1187. {
  1188. size_t len = path.size();
  1189. if (extension) {
  1190. path += ".";
  1191. path += extension;
  1192. }
  1193. if (!os_file_exists(path.c_str()))
  1194. return true;
  1195. int index = 1;
  1196. do {
  1197. path.resize(len);
  1198. path += std::to_string(++index);
  1199. if (extension) {
  1200. path += ".";
  1201. path += extension;
  1202. }
  1203. } while (os_file_exists(path.c_str()));
  1204. return true;
  1205. }
  1206. bool WindowPositionValid(QRect rect)
  1207. {
  1208. for (QScreen* screen: QGuiApplication::screens()) {
  1209. if (screen->availableGeometry().intersects(rect))
  1210. return true;
  1211. }
  1212. return false;
  1213. }
  1214. static inline bool arg_is(const char *arg,
  1215. const char *long_form, const char *short_form)
  1216. {
  1217. return (long_form && strcmp(arg, long_form) == 0) ||
  1218. (short_form && strcmp(arg, short_form) == 0);
  1219. }
  1220. #if !defined(_WIN32) && !defined(__APPLE__)
  1221. #define IS_UNIX 1
  1222. #endif
  1223. /* if using XDG and was previously using an older build of OBS, move config
  1224. * files to XDG directory */
  1225. #if defined(USE_XDG) && defined(IS_UNIX)
  1226. static void move_to_xdg(void)
  1227. {
  1228. char old_path[512];
  1229. char new_path[512];
  1230. char *home = getenv("HOME");
  1231. if (!home)
  1232. return;
  1233. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1234. return;
  1235. /* make base xdg path if it doesn't already exist */
  1236. if (GetConfigPath(new_path, 512, "") <= 0)
  1237. return;
  1238. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1239. return;
  1240. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1241. return;
  1242. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1243. rename(old_path, new_path);
  1244. }
  1245. }
  1246. #endif
  1247. static bool update_ffmpeg_output(ConfigFile &config)
  1248. {
  1249. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1250. return false;
  1251. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1252. if (!url)
  1253. return false;
  1254. bool isActualURL = strstr(url, "://") != nullptr;
  1255. if (isActualURL)
  1256. return false;
  1257. string urlStr = url;
  1258. string extension;
  1259. for (size_t i = urlStr.length(); i > 0; i--) {
  1260. size_t idx = i - 1;
  1261. if (urlStr[idx] == '.') {
  1262. extension = &urlStr[i];
  1263. }
  1264. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1265. urlStr[idx] = 0;
  1266. break;
  1267. }
  1268. }
  1269. if (urlStr.empty() || extension.empty())
  1270. return false;
  1271. config_remove_value(config, "AdvOut", "FFURL");
  1272. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1273. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1274. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1275. return true;
  1276. }
  1277. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1278. {
  1279. bool changed = false;
  1280. if (config_has_user_value(config, sec, "Reconnect")) {
  1281. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1282. config_set_bool(config, "Output", "Reconnect", reconnect);
  1283. changed = true;
  1284. }
  1285. if (config_has_user_value(config, sec, "RetryDelay")) {
  1286. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1287. config_set_uint(config, "Output", "RetryDelay", delay);
  1288. changed = true;
  1289. }
  1290. if (config_has_user_value(config, sec, "MaxRetries")) {
  1291. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1292. config_set_uint(config, "Output", "MaxRetries", retries);
  1293. changed = true;
  1294. }
  1295. return changed;
  1296. }
  1297. static bool update_reconnect(ConfigFile &config)
  1298. {
  1299. if (!config_has_user_value(config, "Output", "Mode"))
  1300. return false;
  1301. const char *mode = config_get_string(config, "Output", "Mode");
  1302. if (!mode)
  1303. return false;
  1304. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1305. "AdvOut" : "SimpleOutput";
  1306. if (move_reconnect_settings(config, section)) {
  1307. config_remove_value(config, "SimpleOutput", "Reconnect");
  1308. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1309. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1310. config_remove_value(config, "AdvOut", "Reconnect");
  1311. config_remove_value(config, "AdvOut", "RetryDelay");
  1312. config_remove_value(config, "AdvOut", "MaxRetries");
  1313. return true;
  1314. }
  1315. return false;
  1316. }
  1317. static void convert_x264_settings(obs_data_t *data)
  1318. {
  1319. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1320. if (use_bufsize) {
  1321. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1322. if (buffer_size == 0)
  1323. obs_data_set_string(data, "rate_control", "CRF");
  1324. }
  1325. }
  1326. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1327. {
  1328. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1329. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1330. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1331. bool modified = false;
  1332. bool cbr = true;
  1333. if (cbr_item) {
  1334. cbr = obs_data_item_get_bool(cbr_item);
  1335. obs_data_item_unset_user_value(cbr_item);
  1336. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1337. modified = true;
  1338. }
  1339. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1340. if (!cbr_item)
  1341. obs_data_set_string(data, "rate_control", "CBR");
  1342. else if (!cbr)
  1343. convert_x264_settings(data);
  1344. modified = true;
  1345. }
  1346. if (modified)
  1347. obs_data_save_json_safe(data, file, "tmp", "bak");
  1348. obs_data_item_release(&rc_item);
  1349. obs_data_item_release(&cbr_item);
  1350. obs_data_release(data);
  1351. }
  1352. static void upgrade_settings(void)
  1353. {
  1354. char path[512];
  1355. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1356. if (pathlen <= 0)
  1357. return;
  1358. if (!os_file_exists(path))
  1359. return;
  1360. os_dir_t *dir = os_opendir(path);
  1361. if (!dir)
  1362. return;
  1363. struct os_dirent *ent = os_readdir(dir);
  1364. while (ent) {
  1365. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1366. strcmp(ent->d_name, "..") != 0) {
  1367. strcat(path, "/");
  1368. strcat(path, ent->d_name);
  1369. strcat(path, "/basic.ini");
  1370. ConfigFile config;
  1371. int ret;
  1372. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1373. if (ret == CONFIG_SUCCESS) {
  1374. if (update_ffmpeg_output(config) ||
  1375. update_reconnect(config)) {
  1376. config_save_safe(config, "tmp",
  1377. nullptr);
  1378. }
  1379. }
  1380. if (config) {
  1381. const char *sEnc = config_get_string(config,
  1382. "AdvOut", "Encoder");
  1383. const char *rEnc = config_get_string(config,
  1384. "AdvOut", "RecEncoder");
  1385. /* replace "cbr" option with "rate_control" for
  1386. * each profile's encoder data */
  1387. path[pathlen] = 0;
  1388. strcat(path, "/");
  1389. strcat(path, ent->d_name);
  1390. strcat(path, "/recordEncoder.json");
  1391. convert_14_2_encoder_setting(rEnc, path);
  1392. path[pathlen] = 0;
  1393. strcat(path, "/");
  1394. strcat(path, ent->d_name);
  1395. strcat(path, "/streamEncoder.json");
  1396. convert_14_2_encoder_setting(sEnc, path);
  1397. }
  1398. path[pathlen] = 0;
  1399. }
  1400. ent = os_readdir(dir);
  1401. }
  1402. os_closedir(dir);
  1403. }
  1404. int main(int argc, char *argv[])
  1405. {
  1406. #ifndef _WIN32
  1407. signal(SIGPIPE, SIG_IGN);
  1408. #endif
  1409. #ifdef _WIN32
  1410. load_debug_privilege();
  1411. base_set_crash_handler(main_crash_handler, nullptr);
  1412. #endif
  1413. base_get_log_handler(&def_log_handler, nullptr);
  1414. #if defined(USE_XDG) && defined(IS_UNIX)
  1415. move_to_xdg();
  1416. #endif
  1417. for (int i = 1; i < argc; i++) {
  1418. if (arg_is(argv[i], "--portable", "-p")) {
  1419. portable_mode = true;
  1420. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1421. log_verbose = true;
  1422. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  1423. opt_always_on_top = true;
  1424. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1425. unfiltered_log = true;
  1426. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1427. opt_start_streaming = true;
  1428. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1429. opt_start_recording = true;
  1430. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1431. opt_start_replaybuffer = true;
  1432. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1433. if (++i < argc) opt_starting_collection = argv[i];
  1434. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1435. if (++i < argc) opt_starting_profile = argv[i];
  1436. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1437. if (++i < argc) opt_starting_scene = argv[i];
  1438. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1439. opt_minimize_tray = true;
  1440. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1441. opt_studio_mode = true;
  1442. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  1443. opt_allow_opengl = true;
  1444. } else if (arg_is(argv[i], "--help", "-h")) {
  1445. std::cout <<
  1446. "--help, -h: Get list of available commands.\n\n" <<
  1447. "--startstreaming: Automatically start streaming.\n" <<
  1448. "--startrecording: Automatically start recording.\n" <<
  1449. "--startreplaybuffer: Start replay buffer.\n\n" <<
  1450. "--collection <string>: Use specific scene collection."
  1451. << "\n" <<
  1452. "--profile <string>: Use specific profile.\n" <<
  1453. "--scene <string>: Start with specific scene.\n\n" <<
  1454. "--studio-mode: Enable studio mode.\n" <<
  1455. "--minimize-to-tray: Minimize to system tray.\n" <<
  1456. "--portable, -p: Use portable mode.\n\n" <<
  1457. "--verbose: Make log more verbose.\n" <<
  1458. "--always-on-top: Start in 'always on top' mode.\n\n" <<
  1459. "--unfiltered_log: Make log unfiltered.\n\n" <<
  1460. "--allow-opengl: Allow OpenGL on Windows.\n\n" <<
  1461. "--version, -V: Get current version.\n";
  1462. exit(0);
  1463. } else if (arg_is(argv[i], "--version", "-V")) {
  1464. std::cout << "OBS Studio - " <<
  1465. App()->GetVersionString() << "\n";
  1466. exit(0);
  1467. }
  1468. }
  1469. #if !OBS_UNIX_STRUCTURE
  1470. if (!portable_mode) {
  1471. portable_mode =
  1472. os_file_exists(BASE_PATH "/portable_mode") ||
  1473. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1474. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1475. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1476. }
  1477. #endif
  1478. upgrade_settings();
  1479. fstream logFile;
  1480. curl_global_init(CURL_GLOBAL_ALL);
  1481. int ret = run_program(logFile, argc, argv);
  1482. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1483. base_set_log_handler(nullptr, nullptr);
  1484. return ret;
  1485. }