obs-app.cpp 33 KB

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