obs-app.cpp 45 KB

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