obs-app.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  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. logFile.open(path,
  994. ios_base::in | ios_base::out | ios_base::trunc);
  995. if (logFile.is_open()) {
  996. delete_oldest_file("obs-studio/logs");
  997. base_set_log_handler(do_log, &logFile);
  998. } else {
  999. blog(LOG_ERROR, "Failed to open log file");
  1000. }
  1001. }
  1002. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  1003. {
  1004. profiler_name_store_free(store);
  1005. };
  1006. using ProfilerNameStore =
  1007. std::unique_ptr<profiler_name_store_t,
  1008. decltype(ProfilerNameStoreRelease)>;
  1009. ProfilerNameStore CreateNameStore()
  1010. {
  1011. return ProfilerNameStore{profiler_name_store_create(),
  1012. ProfilerNameStoreRelease};
  1013. }
  1014. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  1015. {
  1016. profile_snapshot_free(snap);
  1017. };
  1018. using ProfilerSnapshot =
  1019. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1020. ProfilerSnapshot GetSnapshot()
  1021. {
  1022. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1023. }
  1024. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1025. {
  1026. if (currentLogFile.empty())
  1027. return;
  1028. auto pos = currentLogFile.rfind('.');
  1029. if (pos == currentLogFile.npos)
  1030. return;
  1031. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1032. ostringstream dst;
  1033. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1034. dst.write(currentLogFile.c_str(), pos);
  1035. dst.write(LITERAL_SIZE(".csv.gz"));
  1036. #undef LITERAL_SIZE
  1037. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1038. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1039. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1040. static_cast<const char*>(path));
  1041. }
  1042. static auto ProfilerFree = [](void *)
  1043. {
  1044. profiler_stop();
  1045. auto snap = GetSnapshot();
  1046. profiler_print(snap.get());
  1047. profiler_print_time_between_calls(snap.get());
  1048. SaveProfilerData(snap);
  1049. profiler_free();
  1050. };
  1051. static const char *run_program_init = "run_program_init";
  1052. static int run_program(fstream &logFile, int argc, char *argv[])
  1053. {
  1054. int ret = -1;
  1055. auto profilerNameStore = CreateNameStore();
  1056. std::unique_ptr<void, decltype(ProfilerFree)>
  1057. prof_release(static_cast<void*>(&ProfilerFree),
  1058. ProfilerFree);
  1059. profiler_start();
  1060. profile_register_root(run_program_init, 0);
  1061. ScopeProfiler prof{run_program_init};
  1062. QCoreApplication::addLibraryPath(".");
  1063. OBSApp program(argc, argv, profilerNameStore.get());
  1064. try {
  1065. program.AppInit();
  1066. OBSTranslator translator;
  1067. create_log_file(logFile);
  1068. delete_oldest_file("obs-studio/profiler_data");
  1069. program.installTranslator(&translator);
  1070. #ifdef _WIN32
  1071. /* --------------------------------------- */
  1072. /* check and warn if already running */
  1073. bool already_running = false;
  1074. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1075. if (already_running) {
  1076. blog(LOG_WARNING, "\n================================");
  1077. blog(LOG_WARNING, "Warning: OBS is already running!");
  1078. blog(LOG_WARNING, "================================\n");
  1079. QMessageBox::StandardButtons buttons(
  1080. QMessageBox::Yes | QMessageBox::Cancel);
  1081. QMessageBox mb(QMessageBox::Question,
  1082. QTStr("AlreadyRunning.Title"),
  1083. QTStr("AlreadyRunning.Text"),
  1084. buttons,
  1085. nullptr);
  1086. mb.setButtonText(QMessageBox::Yes,
  1087. QTStr("AlreadyRunning.LaunchAnyway"));
  1088. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1089. mb.setDefaultButton(QMessageBox::Cancel);
  1090. QMessageBox::StandardButton button;
  1091. button = (QMessageBox::StandardButton)mb.exec();
  1092. if (button == QMessageBox::Cancel) {
  1093. blog(LOG_INFO, "User shut down the program "
  1094. "because OBS was already "
  1095. "running");
  1096. return 0;
  1097. }
  1098. blog(LOG_WARNING, "User is now running a secondary "
  1099. "instance of OBS!");
  1100. }
  1101. /* --------------------------------------- */
  1102. #endif
  1103. if (!program.OBSInit())
  1104. return 0;
  1105. prof.Stop();
  1106. return program.exec();
  1107. } catch (const char *error) {
  1108. blog(LOG_ERROR, "%s", error);
  1109. OBSErrorBox(nullptr, "%s", error);
  1110. }
  1111. return ret;
  1112. }
  1113. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1114. #ifdef _WIN32
  1115. #define CRASH_MESSAGE \
  1116. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1117. "to the clipboard? (Crash logs will still be saved to the " \
  1118. "%appdata%\\obs-studio\\crashes directory)"
  1119. static void main_crash_handler(const char *format, va_list args, void *param)
  1120. {
  1121. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1122. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1123. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1124. delete_oldest_file("obs-studio/crashes");
  1125. string name = "obs-studio/crashes/Crash ";
  1126. name += GenerateTimeDateFilename("txt");
  1127. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1128. fstream file;
  1129. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1130. ios_base::binary);
  1131. file << text;
  1132. file.close();
  1133. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1134. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1135. if (ret == IDYES) {
  1136. size_t len = strlen(text);
  1137. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1138. memcpy(GlobalLock(mem), text, len);
  1139. GlobalUnlock(mem);
  1140. OpenClipboard(0);
  1141. EmptyClipboard();
  1142. SetClipboardData(CF_TEXT, mem);
  1143. CloseClipboard();
  1144. }
  1145. exit(-1);
  1146. UNUSED_PARAMETER(param);
  1147. }
  1148. static void load_debug_privilege(void)
  1149. {
  1150. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1151. TOKEN_PRIVILEGES tp;
  1152. HANDLE token;
  1153. LUID val;
  1154. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1155. return;
  1156. }
  1157. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1158. tp.PrivilegeCount = 1;
  1159. tp.Privileges[0].Luid = val;
  1160. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1161. AdjustTokenPrivileges(token, false, &tp,
  1162. sizeof(tp), NULL, NULL);
  1163. }
  1164. CloseHandle(token);
  1165. }
  1166. #endif
  1167. #ifdef __APPLE__
  1168. #define BASE_PATH ".."
  1169. #else
  1170. #define BASE_PATH "../.."
  1171. #endif
  1172. #define CONFIG_PATH BASE_PATH "/config"
  1173. #ifndef OBS_UNIX_STRUCTURE
  1174. #define OBS_UNIX_STRUCTURE 0
  1175. #endif
  1176. int GetConfigPath(char *path, size_t size, const char *name)
  1177. {
  1178. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1179. if (name && *name) {
  1180. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1181. } else {
  1182. return snprintf(path, size, CONFIG_PATH);
  1183. }
  1184. } else {
  1185. return os_get_config_path(path, size, name);
  1186. }
  1187. }
  1188. char *GetConfigPathPtr(const char *name)
  1189. {
  1190. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1191. char path[512];
  1192. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1193. return bstrdup(path);
  1194. } else {
  1195. return NULL;
  1196. }
  1197. } else {
  1198. return os_get_config_path_ptr(name);
  1199. }
  1200. }
  1201. int GetProgramDataPath(char *path, size_t size, const char *name)
  1202. {
  1203. return os_get_program_data_path(path, size, name);
  1204. }
  1205. char *GetProgramDataPathPtr(const char *name)
  1206. {
  1207. return os_get_program_data_path_ptr(name);
  1208. }
  1209. bool GetFileSafeName(const char *name, std::string &file)
  1210. {
  1211. size_t base_len = strlen(name);
  1212. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1213. std::wstring wfile;
  1214. if (!len)
  1215. return false;
  1216. wfile.resize(len);
  1217. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1218. for (size_t i = wfile.size(); i > 0; i--) {
  1219. size_t im1 = i - 1;
  1220. if (iswspace(wfile[im1])) {
  1221. wfile[im1] = '_';
  1222. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1223. wfile.erase(im1, 1);
  1224. }
  1225. }
  1226. if (wfile.size() == 0)
  1227. wfile = L"characters_only";
  1228. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1229. if (!len)
  1230. return false;
  1231. file.resize(len);
  1232. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1233. return true;
  1234. }
  1235. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1236. {
  1237. size_t len = path.size();
  1238. if (extension) {
  1239. path += ".";
  1240. path += extension;
  1241. }
  1242. if (!os_file_exists(path.c_str()))
  1243. return true;
  1244. int index = 1;
  1245. do {
  1246. path.resize(len);
  1247. path += std::to_string(++index);
  1248. if (extension) {
  1249. path += ".";
  1250. path += extension;
  1251. }
  1252. } while (os_file_exists(path.c_str()));
  1253. return true;
  1254. }
  1255. bool WindowPositionValid(QRect rect)
  1256. {
  1257. for (QScreen* screen: QGuiApplication::screens()) {
  1258. if (screen->availableGeometry().intersects(rect))
  1259. return true;
  1260. }
  1261. return false;
  1262. }
  1263. static inline bool arg_is(const char *arg,
  1264. const char *long_form, const char *short_form)
  1265. {
  1266. return (long_form && strcmp(arg, long_form) == 0) ||
  1267. (short_form && strcmp(arg, short_form) == 0);
  1268. }
  1269. #if !defined(_WIN32) && !defined(__APPLE__)
  1270. #define IS_UNIX 1
  1271. #endif
  1272. /* if using XDG and was previously using an older build of OBS, move config
  1273. * files to XDG directory */
  1274. #if defined(USE_XDG) && defined(IS_UNIX)
  1275. static void move_to_xdg(void)
  1276. {
  1277. char old_path[512];
  1278. char new_path[512];
  1279. char *home = getenv("HOME");
  1280. if (!home)
  1281. return;
  1282. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1283. return;
  1284. /* make base xdg path if it doesn't already exist */
  1285. if (GetConfigPath(new_path, 512, "") <= 0)
  1286. return;
  1287. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1288. return;
  1289. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1290. return;
  1291. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1292. rename(old_path, new_path);
  1293. }
  1294. }
  1295. #endif
  1296. static bool update_ffmpeg_output(ConfigFile &config)
  1297. {
  1298. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1299. return false;
  1300. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1301. if (!url)
  1302. return false;
  1303. bool isActualURL = strstr(url, "://") != nullptr;
  1304. if (isActualURL)
  1305. return false;
  1306. string urlStr = url;
  1307. string extension;
  1308. for (size_t i = urlStr.length(); i > 0; i--) {
  1309. size_t idx = i - 1;
  1310. if (urlStr[idx] == '.') {
  1311. extension = &urlStr[i];
  1312. }
  1313. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1314. urlStr[idx] = 0;
  1315. break;
  1316. }
  1317. }
  1318. if (urlStr.empty() || extension.empty())
  1319. return false;
  1320. config_remove_value(config, "AdvOut", "FFURL");
  1321. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1322. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1323. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1324. return true;
  1325. }
  1326. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1327. {
  1328. bool changed = false;
  1329. if (config_has_user_value(config, sec, "Reconnect")) {
  1330. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1331. config_set_bool(config, "Output", "Reconnect", reconnect);
  1332. changed = true;
  1333. }
  1334. if (config_has_user_value(config, sec, "RetryDelay")) {
  1335. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1336. config_set_uint(config, "Output", "RetryDelay", delay);
  1337. changed = true;
  1338. }
  1339. if (config_has_user_value(config, sec, "MaxRetries")) {
  1340. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1341. config_set_uint(config, "Output", "MaxRetries", retries);
  1342. changed = true;
  1343. }
  1344. return changed;
  1345. }
  1346. static bool update_reconnect(ConfigFile &config)
  1347. {
  1348. if (!config_has_user_value(config, "Output", "Mode"))
  1349. return false;
  1350. const char *mode = config_get_string(config, "Output", "Mode");
  1351. if (!mode)
  1352. return false;
  1353. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1354. "AdvOut" : "SimpleOutput";
  1355. if (move_reconnect_settings(config, section)) {
  1356. config_remove_value(config, "SimpleOutput", "Reconnect");
  1357. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1358. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1359. config_remove_value(config, "AdvOut", "Reconnect");
  1360. config_remove_value(config, "AdvOut", "RetryDelay");
  1361. config_remove_value(config, "AdvOut", "MaxRetries");
  1362. return true;
  1363. }
  1364. return false;
  1365. }
  1366. static void convert_x264_settings(obs_data_t *data)
  1367. {
  1368. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1369. if (use_bufsize) {
  1370. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1371. if (buffer_size == 0)
  1372. obs_data_set_string(data, "rate_control", "CRF");
  1373. }
  1374. }
  1375. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1376. {
  1377. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1378. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1379. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1380. bool modified = false;
  1381. bool cbr = true;
  1382. if (cbr_item) {
  1383. cbr = obs_data_item_get_bool(cbr_item);
  1384. obs_data_item_unset_user_value(cbr_item);
  1385. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1386. modified = true;
  1387. }
  1388. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1389. if (!cbr_item)
  1390. obs_data_set_string(data, "rate_control", "CBR");
  1391. else if (!cbr)
  1392. convert_x264_settings(data);
  1393. modified = true;
  1394. }
  1395. if (modified)
  1396. obs_data_save_json_safe(data, file, "tmp", "bak");
  1397. obs_data_item_release(&rc_item);
  1398. obs_data_item_release(&cbr_item);
  1399. obs_data_release(data);
  1400. }
  1401. static void upgrade_settings(void)
  1402. {
  1403. char path[512];
  1404. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1405. if (pathlen <= 0)
  1406. return;
  1407. if (!os_file_exists(path))
  1408. return;
  1409. os_dir_t *dir = os_opendir(path);
  1410. if (!dir)
  1411. return;
  1412. struct os_dirent *ent = os_readdir(dir);
  1413. while (ent) {
  1414. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1415. strcmp(ent->d_name, "..") != 0) {
  1416. strcat(path, "/");
  1417. strcat(path, ent->d_name);
  1418. strcat(path, "/basic.ini");
  1419. ConfigFile config;
  1420. int ret;
  1421. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1422. if (ret == CONFIG_SUCCESS) {
  1423. if (update_ffmpeg_output(config) ||
  1424. update_reconnect(config)) {
  1425. config_save_safe(config, "tmp",
  1426. nullptr);
  1427. }
  1428. }
  1429. if (config) {
  1430. const char *sEnc = config_get_string(config,
  1431. "AdvOut", "Encoder");
  1432. const char *rEnc = config_get_string(config,
  1433. "AdvOut", "RecEncoder");
  1434. /* replace "cbr" option with "rate_control" for
  1435. * each profile's encoder data */
  1436. path[pathlen] = 0;
  1437. strcat(path, "/");
  1438. strcat(path, ent->d_name);
  1439. strcat(path, "/recordEncoder.json");
  1440. convert_14_2_encoder_setting(rEnc, path);
  1441. path[pathlen] = 0;
  1442. strcat(path, "/");
  1443. strcat(path, ent->d_name);
  1444. strcat(path, "/streamEncoder.json");
  1445. convert_14_2_encoder_setting(sEnc, path);
  1446. }
  1447. path[pathlen] = 0;
  1448. }
  1449. ent = os_readdir(dir);
  1450. }
  1451. os_closedir(dir);
  1452. }
  1453. int main(int argc, char *argv[])
  1454. {
  1455. #ifndef _WIN32
  1456. signal(SIGPIPE, SIG_IGN);
  1457. #endif
  1458. #ifdef _WIN32
  1459. load_debug_privilege();
  1460. base_set_crash_handler(main_crash_handler, nullptr);
  1461. #endif
  1462. base_get_log_handler(&def_log_handler, nullptr);
  1463. #if defined(USE_XDG) && defined(IS_UNIX)
  1464. move_to_xdg();
  1465. #endif
  1466. for (int i = 1; i < argc; i++) {
  1467. if (arg_is(argv[i], "--portable", "-p")) {
  1468. portable_mode = true;
  1469. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1470. log_verbose = true;
  1471. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  1472. opt_always_on_top = true;
  1473. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1474. unfiltered_log = true;
  1475. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1476. opt_start_streaming = true;
  1477. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1478. opt_start_recording = true;
  1479. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1480. opt_start_replaybuffer = true;
  1481. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1482. if (++i < argc) opt_starting_collection = argv[i];
  1483. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1484. if (++i < argc) opt_starting_profile = argv[i];
  1485. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1486. if (++i < argc) opt_starting_scene = argv[i];
  1487. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1488. opt_minimize_tray = true;
  1489. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1490. opt_studio_mode = true;
  1491. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  1492. opt_allow_opengl = true;
  1493. } else if (arg_is(argv[i], "--help", "-h")) {
  1494. std::cout <<
  1495. "--help, -h: Get list of available commands.\n\n" <<
  1496. "--startstreaming: Automatically start streaming.\n" <<
  1497. "--startrecording: Automatically start recording.\n" <<
  1498. "--startreplaybuffer: Start replay buffer.\n\n" <<
  1499. "--collection <string>: Use specific scene collection."
  1500. << "\n" <<
  1501. "--profile <string>: Use specific profile.\n" <<
  1502. "--scene <string>: Start with specific scene.\n\n" <<
  1503. "--studio-mode: Enable studio mode.\n" <<
  1504. "--minimize-to-tray: Minimize to system tray.\n" <<
  1505. "--portable, -p: Use portable mode.\n\n" <<
  1506. "--verbose: Make log more verbose.\n" <<
  1507. "--always-on-top: Start in 'always on top' mode.\n\n" <<
  1508. "--unfiltered_log: Make log unfiltered.\n\n" <<
  1509. "--allow-opengl: Allow OpenGL on Windows.\n\n" <<
  1510. "--version, -V: Get current version.\n";
  1511. exit(0);
  1512. } else if (arg_is(argv[i], "--version", "-V")) {
  1513. std::cout << "OBS Studio - " <<
  1514. App()->GetVersionString() << "\n";
  1515. exit(0);
  1516. }
  1517. }
  1518. #if !OBS_UNIX_STRUCTURE
  1519. if (!portable_mode) {
  1520. portable_mode =
  1521. os_file_exists(BASE_PATH "/portable_mode") ||
  1522. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1523. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1524. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1525. }
  1526. #endif
  1527. upgrade_settings();
  1528. fstream logFile;
  1529. curl_global_init(CURL_GLOBAL_ALL);
  1530. int ret = run_program(logFile, argc, argv);
  1531. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1532. base_set_log_handler(nullptr, nullptr);
  1533. return ret;
  1534. }