obs-app.cpp 45 KB

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