obs-app.cpp 54 KB

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