obs-app.cpp 35 KB

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