obs-app.cpp 40 KB

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