obs-app.cpp 46 KB

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