obs-app.cpp 38 KB

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