obs-app.cpp 64 KB

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