obs-app.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 <qt-wrappers.hpp>
  30. #include <slider-ignorewheel.hpp>
  31. #include <QDir>
  32. #include <QFile>
  33. #include <QGuiApplication>
  34. #include <QScreen>
  35. #include <QProcess>
  36. #include <QAccessible>
  37. #include "obs-app.hpp"
  38. #include "obs-proxy-style.hpp"
  39. #include "log-viewer.hpp"
  40. #include "volume-control.hpp"
  41. #include "window-basic-main.hpp"
  42. #ifdef __APPLE__
  43. #include "window-permissions.hpp"
  44. #endif
  45. #include "window-basic-settings.hpp"
  46. #include "platform.hpp"
  47. #include <fstream>
  48. #include <curl/curl.h>
  49. #ifdef _WIN32
  50. #include <windows.h>
  51. #include <filesystem>
  52. #include <util/windows/win-version.h>
  53. #else
  54. #include <signal.h>
  55. #include <pthread.h>
  56. #include <sys/types.h>
  57. #include <sys/socket.h>
  58. #include <unistd.h>
  59. #endif
  60. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  61. #include "update/models/branches.hpp"
  62. #endif
  63. #if !defined(_WIN32) && !defined(__APPLE__)
  64. #include <obs-nix-platform.h>
  65. #include <qpa/qplatformnativeinterface.h>
  66. #endif
  67. #include <iostream>
  68. #include "ui-config.h"
  69. using namespace std;
  70. static log_handler_t def_log_handler;
  71. static string currentLogFile;
  72. static string lastLogFile;
  73. static string lastCrashLogFile;
  74. bool portable_mode = false;
  75. bool steam = false;
  76. bool safe_mode = false;
  77. bool disable_3p_plugins = false;
  78. bool unclean_shutdown = false;
  79. bool disable_shutdown_check = false;
  80. static bool multi = false;
  81. static bool log_verbose = false;
  82. static bool unfiltered_log = false;
  83. bool opt_start_streaming = false;
  84. bool opt_start_recording = false;
  85. bool opt_studio_mode = false;
  86. bool opt_start_replaybuffer = false;
  87. bool opt_start_virtualcam = false;
  88. bool opt_minimize_tray = false;
  89. bool opt_allow_opengl = false;
  90. bool opt_always_on_top = false;
  91. bool opt_disable_updater = false;
  92. bool opt_disable_missing_files_check = false;
  93. string opt_starting_collection;
  94. string opt_starting_profile;
  95. string opt_starting_scene;
  96. bool restart = false;
  97. bool restart_safe = false;
  98. QStringList arguments;
  99. QPointer<OBSLogViewer> obsLogViewer;
  100. #ifndef _WIN32
  101. int OBSApp::sigintFd[2];
  102. #endif
  103. // GPU hint exports for AMD/NVIDIA laptops
  104. #ifdef _MSC_VER
  105. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  106. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  107. #endif
  108. QObject *CreateShortcutFilter()
  109. {
  110. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  111. auto mouse_event = [](QMouseEvent &event) {
  112. if (!App()->HotkeysEnabledInFocus() &&
  113. event.button() != Qt::LeftButton)
  114. return true;
  115. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  116. bool pressed = event.type() == QEvent::MouseButtonPress;
  117. switch (event.button()) {
  118. case Qt::NoButton:
  119. case Qt::LeftButton:
  120. case Qt::RightButton:
  121. case Qt::AllButtons:
  122. case Qt::MouseButtonMask:
  123. return false;
  124. case Qt::MiddleButton:
  125. hotkey.key = OBS_KEY_MOUSE3;
  126. break;
  127. #define MAP_BUTTON(i, j) \
  128. case Qt::ExtraButton##i: \
  129. hotkey.key = OBS_KEY_MOUSE##j; \
  130. break;
  131. MAP_BUTTON(1, 4);
  132. MAP_BUTTON(2, 5);
  133. MAP_BUTTON(3, 6);
  134. MAP_BUTTON(4, 7);
  135. MAP_BUTTON(5, 8);
  136. MAP_BUTTON(6, 9);
  137. MAP_BUTTON(7, 10);
  138. MAP_BUTTON(8, 11);
  139. MAP_BUTTON(9, 12);
  140. MAP_BUTTON(10, 13);
  141. MAP_BUTTON(11, 14);
  142. MAP_BUTTON(12, 15);
  143. MAP_BUTTON(13, 16);
  144. MAP_BUTTON(14, 17);
  145. MAP_BUTTON(15, 18);
  146. MAP_BUTTON(16, 19);
  147. MAP_BUTTON(17, 20);
  148. MAP_BUTTON(18, 21);
  149. MAP_BUTTON(19, 22);
  150. MAP_BUTTON(20, 23);
  151. MAP_BUTTON(21, 24);
  152. MAP_BUTTON(22, 25);
  153. MAP_BUTTON(23, 26);
  154. MAP_BUTTON(24, 27);
  155. #undef MAP_BUTTON
  156. }
  157. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  158. event.modifiers());
  159. obs_hotkey_inject_event(hotkey, pressed);
  160. return true;
  161. };
  162. auto key_event = [&](QKeyEvent *event) {
  163. int key = event->key();
  164. bool enabledInFocus = App()->HotkeysEnabledInFocus();
  165. if (key != Qt::Key_Enter && key != Qt::Key_Escape &&
  166. key != Qt::Key_Return && !enabledInFocus)
  167. return true;
  168. QDialog *dialog = qobject_cast<QDialog *>(obj);
  169. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  170. bool pressed = event->type() == QEvent::KeyPress;
  171. switch (key) {
  172. case Qt::Key_Shift:
  173. case Qt::Key_Control:
  174. case Qt::Key_Alt:
  175. case Qt::Key_Meta:
  176. break;
  177. #ifdef __APPLE__
  178. case Qt::Key_CapsLock:
  179. // kVK_CapsLock == 57
  180. hotkey.key = obs_key_from_virtual_key(57);
  181. pressed = true;
  182. break;
  183. #endif
  184. case Qt::Key_Enter:
  185. case Qt::Key_Escape:
  186. case Qt::Key_Return:
  187. if (dialog && pressed)
  188. return false;
  189. if (!enabledInFocus)
  190. return true;
  191. /* Falls through. */
  192. default:
  193. hotkey.key = obs_key_from_virtual_key(
  194. event->nativeVirtualKey());
  195. }
  196. if (event->isAutoRepeat())
  197. return true;
  198. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  199. event->modifiers());
  200. obs_hotkey_inject_event(hotkey, pressed);
  201. return true;
  202. };
  203. switch (event->type()) {
  204. case QEvent::MouseButtonPress:
  205. case QEvent::MouseButtonRelease:
  206. return mouse_event(*static_cast<QMouseEvent *>(event));
  207. /*case QEvent::MouseButtonDblClick:
  208. case QEvent::Wheel:*/
  209. case QEvent::KeyPress:
  210. case QEvent::KeyRelease:
  211. return key_event(static_cast<QKeyEvent *>(event));
  212. default:
  213. return false;
  214. }
  215. });
  216. }
  217. string CurrentTimeString()
  218. {
  219. using namespace std::chrono;
  220. struct tm tstruct;
  221. char buf[80];
  222. auto tp = system_clock::now();
  223. auto now = system_clock::to_time_t(tp);
  224. tstruct = *localtime(&now);
  225. size_t written = strftime(buf, sizeof(buf), "%T", &tstruct);
  226. if (ratio_less<system_clock::period, seconds::period>::value &&
  227. written && (sizeof(buf) - written) > 5) {
  228. auto tp_secs = time_point_cast<seconds>(tp);
  229. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  230. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  231. static_cast<unsigned>(millis));
  232. }
  233. return buf;
  234. }
  235. string CurrentDateTimeString()
  236. {
  237. time_t now = time(0);
  238. struct tm tstruct;
  239. char buf[80];
  240. tstruct = *localtime(&now);
  241. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  242. return buf;
  243. }
  244. static void LogString(fstream &logFile, const char *timeString, char *str,
  245. int log_level)
  246. {
  247. static mutex logfile_mutex;
  248. string msg;
  249. msg += timeString;
  250. msg += str;
  251. logfile_mutex.lock();
  252. logFile << msg << endl;
  253. logfile_mutex.unlock();
  254. if (!!obsLogViewer)
  255. QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine",
  256. Qt::QueuedConnection,
  257. Q_ARG(int, log_level),
  258. Q_ARG(QString, QString(msg.c_str())));
  259. }
  260. static inline void LogStringChunk(fstream &logFile, char *str, int log_level)
  261. {
  262. char *nextLine = str;
  263. string timeString = CurrentTimeString();
  264. timeString += ": ";
  265. while (*nextLine) {
  266. char *nextLine = strchr(str, '\n');
  267. if (!nextLine)
  268. break;
  269. if (nextLine != str && nextLine[-1] == '\r') {
  270. nextLine[-1] = 0;
  271. } else {
  272. nextLine[0] = 0;
  273. }
  274. LogString(logFile, timeString.c_str(), str, log_level);
  275. nextLine++;
  276. str = nextLine;
  277. }
  278. LogString(logFile, timeString.c_str(), str, log_level);
  279. }
  280. #define MAX_REPEATED_LINES 30
  281. #define MAX_CHAR_VARIATION (255 * 3)
  282. static inline int sum_chars(const char *str)
  283. {
  284. int val = 0;
  285. for (; *str != 0; str++)
  286. val += *str;
  287. return val;
  288. }
  289. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  290. const char *output_str)
  291. {
  292. static mutex log_mutex;
  293. static const char *last_msg_ptr = nullptr;
  294. static int last_char_sum = 0;
  295. static int rep_count = 0;
  296. int new_sum = sum_chars(output_str);
  297. lock_guard<mutex> guard(log_mutex);
  298. if (unfiltered_log) {
  299. return false;
  300. }
  301. if (last_msg_ptr == msg) {
  302. int diff = std::abs(new_sum - last_char_sum);
  303. if (diff < MAX_CHAR_VARIATION) {
  304. return (rep_count++ >= MAX_REPEATED_LINES);
  305. }
  306. }
  307. if (rep_count > MAX_REPEATED_LINES) {
  308. logFile << CurrentTimeString()
  309. << ": Last log entry repeated for "
  310. << to_string(rep_count - MAX_REPEATED_LINES)
  311. << " more lines" << endl;
  312. }
  313. last_msg_ptr = msg;
  314. last_char_sum = new_sum;
  315. rep_count = 0;
  316. return false;
  317. }
  318. static void do_log(int log_level, const char *msg, va_list args, void *param)
  319. {
  320. fstream &logFile = *static_cast<fstream *>(param);
  321. char str[8192];
  322. #ifndef _WIN32
  323. va_list args2;
  324. va_copy(args2, args);
  325. #endif
  326. vsnprintf(str, sizeof(str), msg, args);
  327. #ifdef _WIN32
  328. if (IsDebuggerPresent()) {
  329. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  330. if (wNum > 1) {
  331. static wstring wide_buf;
  332. static mutex wide_mutex;
  333. lock_guard<mutex> lock(wide_mutex);
  334. wide_buf.reserve(wNum + 1);
  335. wide_buf.resize(wNum - 1);
  336. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  337. wNum);
  338. wide_buf.push_back('\n');
  339. OutputDebugStringW(wide_buf.c_str());
  340. }
  341. }
  342. #endif
  343. #if !defined(_WIN32) && defined(_DEBUG)
  344. def_log_handler(log_level, msg, args2, nullptr);
  345. #endif
  346. if (log_level <= LOG_INFO || log_verbose) {
  347. #if !defined(_WIN32) && !defined(_DEBUG)
  348. def_log_handler(log_level, msg, args2, nullptr);
  349. #endif
  350. if (!too_many_repeated_entries(logFile, msg, str))
  351. LogStringChunk(logFile, str, log_level);
  352. }
  353. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  354. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  355. __debugbreak();
  356. #endif
  357. #ifndef _WIN32
  358. va_end(args2);
  359. #endif
  360. }
  361. #define DEFAULT_LANG "en-US"
  362. bool OBSApp::InitGlobalConfigDefaults()
  363. {
  364. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  365. config_set_default_int(globalConfig, "General", "InfoIncrement", -1);
  366. config_set_default_string(globalConfig, "General", "ProcessPriority",
  367. "Normal");
  368. config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
  369. true);
  370. config_set_default_bool(globalConfig, "General", "ConfirmOnExit", true);
  371. #if _WIN32
  372. config_set_default_string(globalConfig, "Video", "Renderer",
  373. "Direct3D 11");
  374. #else
  375. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  376. #endif
  377. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  378. true);
  379. config_set_default_bool(globalConfig, "BasicWindow",
  380. "PreviewProgramMode", false);
  381. config_set_default_bool(globalConfig, "BasicWindow",
  382. "SceneDuplicationMode", true);
  383. config_set_default_bool(globalConfig, "BasicWindow", "SwapScenesMode",
  384. true);
  385. config_set_default_bool(globalConfig, "BasicWindow", "SnappingEnabled",
  386. true);
  387. config_set_default_bool(globalConfig, "BasicWindow", "ScreenSnapping",
  388. true);
  389. config_set_default_bool(globalConfig, "BasicWindow", "SourceSnapping",
  390. true);
  391. config_set_default_bool(globalConfig, "BasicWindow", "CenterSnapping",
  392. false);
  393. config_set_default_double(globalConfig, "BasicWindow", "SnapDistance",
  394. 10.0);
  395. config_set_default_bool(globalConfig, "BasicWindow",
  396. "SpacingHelpersEnabled", true);
  397. config_set_default_bool(globalConfig, "BasicWindow",
  398. "RecordWhenStreaming", false);
  399. config_set_default_bool(globalConfig, "BasicWindow",
  400. "KeepRecordingWhenStreamStops", false);
  401. config_set_default_bool(globalConfig, "BasicWindow", "SysTrayEnabled",
  402. true);
  403. config_set_default_bool(globalConfig, "BasicWindow",
  404. "SysTrayWhenStarted", false);
  405. config_set_default_bool(globalConfig, "BasicWindow", "SaveProjectors",
  406. false);
  407. config_set_default_bool(globalConfig, "BasicWindow", "ShowTransitions",
  408. true);
  409. config_set_default_bool(globalConfig, "BasicWindow",
  410. "ShowListboxToolbars", true);
  411. config_set_default_bool(globalConfig, "BasicWindow", "ShowStatusBar",
  412. true);
  413. config_set_default_bool(globalConfig, "BasicWindow", "ShowSourceIcons",
  414. true);
  415. config_set_default_bool(globalConfig, "BasicWindow",
  416. "ShowContextToolbars", true);
  417. config_set_default_bool(globalConfig, "BasicWindow", "StudioModeLabels",
  418. true);
  419. config_set_default_string(globalConfig, "General", "HotkeyFocusType",
  420. "NeverDisableHotkeys");
  421. config_set_default_bool(globalConfig, "BasicWindow",
  422. "VerticalVolControl", false);
  423. config_set_default_bool(globalConfig, "BasicWindow",
  424. "MultiviewMouseSwitch", true);
  425. config_set_default_bool(globalConfig, "BasicWindow",
  426. "MultiviewDrawNames", true);
  427. config_set_default_bool(globalConfig, "BasicWindow",
  428. "MultiviewDrawAreas", true);
  429. #ifdef _WIN32
  430. config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
  431. true);
  432. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  433. true);
  434. #endif
  435. #ifdef __APPLE__
  436. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  437. true);
  438. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  439. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  440. true);
  441. #endif
  442. config_set_default_bool(globalConfig, "BasicWindow",
  443. "MediaControlsCountdownTimer", true);
  444. return true;
  445. }
  446. static bool do_mkdir(const char *path)
  447. {
  448. if (os_mkdirs(path) == MKDIR_ERROR) {
  449. OBSErrorBox(NULL, "Failed to create directory %s", path);
  450. return false;
  451. }
  452. return true;
  453. }
  454. static bool MakeUserDirs()
  455. {
  456. char path[512];
  457. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  458. return false;
  459. if (!do_mkdir(path))
  460. return false;
  461. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  462. return false;
  463. if (!do_mkdir(path))
  464. return false;
  465. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  466. return false;
  467. if (!do_mkdir(path))
  468. return false;
  469. #ifdef _WIN32
  470. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  471. return false;
  472. if (!do_mkdir(path))
  473. return false;
  474. #endif
  475. #ifdef WHATSNEW_ENABLED
  476. if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  477. return false;
  478. if (!do_mkdir(path))
  479. return false;
  480. #endif
  481. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  482. return false;
  483. if (!do_mkdir(path))
  484. return false;
  485. return true;
  486. }
  487. static bool MakeUserProfileDirs()
  488. {
  489. char path[512];
  490. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  491. return false;
  492. if (!do_mkdir(path))
  493. return false;
  494. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  495. return false;
  496. if (!do_mkdir(path))
  497. return false;
  498. return true;
  499. }
  500. static string GetProfileDirFromName(const char *name)
  501. {
  502. string outputPath;
  503. os_glob_t *glob;
  504. char path[512];
  505. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  506. return outputPath;
  507. strcat(path, "/*");
  508. if (os_glob(path, 0, &glob) != 0)
  509. return outputPath;
  510. for (size_t i = 0; i < glob->gl_pathc; i++) {
  511. struct os_globent ent = glob->gl_pathv[i];
  512. if (!ent.directory)
  513. continue;
  514. strcpy(path, ent.path);
  515. strcat(path, "/basic.ini");
  516. ConfigFile config;
  517. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  518. continue;
  519. const char *curName =
  520. config_get_string(config, "General", "Name");
  521. if (astrcmpi(curName, name) == 0) {
  522. outputPath = ent.path;
  523. break;
  524. }
  525. }
  526. os_globfree(glob);
  527. if (!outputPath.empty()) {
  528. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  529. const char *start = strrchr(outputPath.c_str(), '/');
  530. if (start)
  531. outputPath.erase(0, start - outputPath.c_str() + 1);
  532. }
  533. return outputPath;
  534. }
  535. static string GetSceneCollectionFileFromName(const char *name)
  536. {
  537. string outputPath;
  538. os_glob_t *glob;
  539. char path[512];
  540. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  541. return outputPath;
  542. strcat(path, "/*.json");
  543. if (os_glob(path, 0, &glob) != 0)
  544. return outputPath;
  545. for (size_t i = 0; i < glob->gl_pathc; i++) {
  546. struct os_globent ent = glob->gl_pathv[i];
  547. if (ent.directory)
  548. continue;
  549. OBSDataAutoRelease data =
  550. obs_data_create_from_json_file_safe(ent.path, "bak");
  551. const char *curName = obs_data_get_string(data, "name");
  552. if (astrcmpi(name, curName) == 0) {
  553. outputPath = ent.path;
  554. break;
  555. }
  556. }
  557. os_globfree(glob);
  558. if (!outputPath.empty()) {
  559. outputPath.resize(outputPath.size() - 5);
  560. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  561. const char *start = strrchr(outputPath.c_str(), '/');
  562. if (start)
  563. outputPath.erase(0, start - outputPath.c_str() + 1);
  564. }
  565. return outputPath;
  566. }
  567. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  568. {
  569. if (!layout)
  570. return false;
  571. if (astrcmpi(layout, "horizontaltop") == 0) {
  572. config_set_int(
  573. globalConfig, "BasicWindow", "MultiviewLayout",
  574. static_cast<int>(
  575. MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  576. return true;
  577. }
  578. if (astrcmpi(layout, "horizontalbottom") == 0) {
  579. config_set_int(
  580. globalConfig, "BasicWindow", "MultiviewLayout",
  581. static_cast<int>(
  582. MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  583. return true;
  584. }
  585. if (astrcmpi(layout, "verticalleft") == 0) {
  586. config_set_int(
  587. globalConfig, "BasicWindow", "MultiviewLayout",
  588. static_cast<int>(
  589. MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  590. return true;
  591. }
  592. if (astrcmpi(layout, "verticalright") == 0) {
  593. config_set_int(
  594. globalConfig, "BasicWindow", "MultiviewLayout",
  595. static_cast<int>(
  596. MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  597. return true;
  598. }
  599. return false;
  600. }
  601. bool OBSApp::InitGlobalConfig()
  602. {
  603. char path[512];
  604. bool changed = false;
  605. int len = GetConfigPath(path, sizeof(path), "obs-studio/global.ini");
  606. if (len <= 0) {
  607. return false;
  608. }
  609. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  610. if (errorcode != CONFIG_SUCCESS) {
  611. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  612. return false;
  613. }
  614. if (!opt_starting_collection.empty()) {
  615. string path = GetSceneCollectionFileFromName(
  616. opt_starting_collection.c_str());
  617. if (!path.empty()) {
  618. config_set_string(globalConfig, "Basic",
  619. "SceneCollection",
  620. opt_starting_collection.c_str());
  621. config_set_string(globalConfig, "Basic",
  622. "SceneCollectionFile", path.c_str());
  623. changed = true;
  624. }
  625. }
  626. if (!opt_starting_profile.empty()) {
  627. string path =
  628. GetProfileDirFromName(opt_starting_profile.c_str());
  629. if (!path.empty()) {
  630. config_set_string(globalConfig, "Basic", "Profile",
  631. opt_starting_profile.c_str());
  632. config_set_string(globalConfig, "Basic", "ProfileDir",
  633. path.c_str());
  634. changed = true;
  635. }
  636. }
  637. uint32_t lastVersion =
  638. config_get_int(globalConfig, "General", "LastVersion");
  639. if (!config_has_user_value(globalConfig, "General", "Pre19Defaults")) {
  640. bool useOldDefaults = lastVersion &&
  641. lastVersion <
  642. MAKE_SEMANTIC_VERSION(19, 0, 0);
  643. config_set_bool(globalConfig, "General", "Pre19Defaults",
  644. useOldDefaults);
  645. changed = true;
  646. }
  647. if (!config_has_user_value(globalConfig, "General", "Pre21Defaults")) {
  648. bool useOldDefaults = lastVersion &&
  649. lastVersion <
  650. MAKE_SEMANTIC_VERSION(21, 0, 0);
  651. config_set_bool(globalConfig, "General", "Pre21Defaults",
  652. useOldDefaults);
  653. changed = true;
  654. }
  655. if (!config_has_user_value(globalConfig, "General", "Pre23Defaults")) {
  656. bool useOldDefaults = lastVersion &&
  657. lastVersion <
  658. MAKE_SEMANTIC_VERSION(23, 0, 0);
  659. config_set_bool(globalConfig, "General", "Pre23Defaults",
  660. useOldDefaults);
  661. changed = true;
  662. }
  663. #define PRE_24_1_DEFS "Pre24.1Defaults"
  664. if (!config_has_user_value(globalConfig, "General", PRE_24_1_DEFS)) {
  665. bool useOldDefaults = lastVersion &&
  666. lastVersion <
  667. MAKE_SEMANTIC_VERSION(24, 1, 0);
  668. config_set_bool(globalConfig, "General", PRE_24_1_DEFS,
  669. useOldDefaults);
  670. changed = true;
  671. }
  672. #undef PRE_24_1_DEFS
  673. if (config_has_user_value(globalConfig, "BasicWindow",
  674. "MultiviewLayout")) {
  675. const char *layout = config_get_string(
  676. globalConfig, "BasicWindow", "MultiviewLayout");
  677. changed |= UpdatePre22MultiviewLayout(layout);
  678. }
  679. if (lastVersion && lastVersion < MAKE_SEMANTIC_VERSION(24, 0, 0)) {
  680. bool disableHotkeysInFocus = config_get_bool(
  681. globalConfig, "General", "DisableHotkeysInFocus");
  682. if (disableHotkeysInFocus)
  683. config_set_string(globalConfig, "General",
  684. "HotkeyFocusType",
  685. "DisableHotkeysInFocus");
  686. changed = true;
  687. }
  688. if (changed)
  689. config_save_safe(globalConfig, "tmp", nullptr);
  690. return InitGlobalConfigDefaults();
  691. }
  692. bool OBSApp::InitLocale()
  693. {
  694. ProfileScope("OBSApp::InitLocale");
  695. const char *lang =
  696. config_get_string(globalConfig, "General", "Language");
  697. bool userLocale =
  698. config_has_user_value(globalConfig, "General", "Language");
  699. if (!userLocale || !lang || lang[0] == '\0')
  700. lang = DEFAULT_LANG;
  701. locale = lang;
  702. // set basic default application locale
  703. if (!locale.empty())
  704. QLocale::setDefault(QLocale(
  705. QString::fromStdString(locale).replace('-', '_')));
  706. string englishPath;
  707. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  708. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  709. return false;
  710. }
  711. textLookup = text_lookup_create(englishPath.c_str());
  712. if (!textLookup) {
  713. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  714. englishPath.c_str());
  715. return false;
  716. }
  717. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  718. if (userLocale && defaultLang)
  719. return true;
  720. if (!userLocale && defaultLang) {
  721. for (auto &locale_ : GetPreferredLocales()) {
  722. if (locale_ == lang)
  723. return true;
  724. stringstream file;
  725. file << "locale/" << locale_ << ".ini";
  726. string path;
  727. if (!GetDataFilePath(file.str().c_str(), path))
  728. continue;
  729. if (!text_lookup_add(textLookup, path.c_str()))
  730. continue;
  731. blog(LOG_INFO, "Using preferred locale '%s'",
  732. locale_.c_str());
  733. locale = locale_;
  734. // set application default locale to the new choosen one
  735. if (!locale.empty())
  736. QLocale::setDefault(QLocale(
  737. QString::fromStdString(locale).replace(
  738. '-', '_')));
  739. return true;
  740. }
  741. return true;
  742. }
  743. stringstream file;
  744. file << "locale/" << lang << ".ini";
  745. string path;
  746. if (GetDataFilePath(file.str().c_str(), path)) {
  747. if (!text_lookup_add(textLookup, path.c_str()))
  748. blog(LOG_ERROR, "Failed to add locale file '%s'",
  749. path.c_str());
  750. } else {
  751. blog(LOG_ERROR, "Could not find locale file '%s'",
  752. file.str().c_str());
  753. }
  754. return true;
  755. }
  756. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  757. void ParseBranchesJson(const std::string &jsonString, vector<UpdateBranch> &out,
  758. std::string &error)
  759. {
  760. JsonBranches branches;
  761. try {
  762. nlohmann::json json = nlohmann::json::parse(jsonString);
  763. branches = json.get<JsonBranches>();
  764. } catch (nlohmann::json::exception &e) {
  765. error = e.what();
  766. return;
  767. }
  768. for (const JsonBranch &json_branch : branches) {
  769. #ifdef _WIN32
  770. if (!json_branch.windows)
  771. continue;
  772. #elif defined(__APPLE__)
  773. if (!json_branch.macos)
  774. continue;
  775. #endif
  776. UpdateBranch branch = {
  777. QString::fromStdString(json_branch.name),
  778. QString::fromStdString(json_branch.display_name),
  779. QString::fromStdString(json_branch.description),
  780. json_branch.enabled,
  781. json_branch.visible,
  782. };
  783. out.push_back(branch);
  784. }
  785. }
  786. bool LoadBranchesFile(vector<UpdateBranch> &out)
  787. {
  788. string error;
  789. string branchesText;
  790. BPtr<char> branchesFilePath =
  791. GetConfigPathPtr("obs-studio/updates/branches.json");
  792. QFile branchesFile(branchesFilePath.Get());
  793. if (!branchesFile.open(QIODevice::ReadOnly)) {
  794. error = "Opening file failed.";
  795. goto fail;
  796. }
  797. branchesText = branchesFile.readAll();
  798. if (branchesText.empty()) {
  799. error = "File empty.";
  800. goto fail;
  801. }
  802. ParseBranchesJson(branchesText, out, error);
  803. if (error.empty())
  804. return !out.empty();
  805. fail:
  806. blog(LOG_WARNING, "Loading branches from file failed: %s",
  807. error.c_str());
  808. return false;
  809. }
  810. #endif
  811. void OBSApp::SetBranchData(const string &data)
  812. {
  813. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  814. string error;
  815. vector<UpdateBranch> result;
  816. ParseBranchesJson(data, result, error);
  817. if (!error.empty()) {
  818. blog(LOG_WARNING, "Reading branches JSON response failed: %s",
  819. error.c_str());
  820. return;
  821. }
  822. if (!result.empty())
  823. updateBranches = result;
  824. branches_loaded = true;
  825. #else
  826. UNUSED_PARAMETER(data);
  827. #endif
  828. }
  829. std::vector<UpdateBranch> OBSApp::GetBranches()
  830. {
  831. vector<UpdateBranch> out;
  832. /* Always ensure the default branch exists */
  833. out.push_back(UpdateBranch{"stable", "", "", true, true});
  834. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  835. if (!branches_loaded) {
  836. vector<UpdateBranch> result;
  837. if (LoadBranchesFile(result))
  838. updateBranches = result;
  839. branches_loaded = true;
  840. }
  841. #endif
  842. /* Copy additional branches to result (if any) */
  843. if (!updateBranches.empty())
  844. out.insert(out.end(), updateBranches.begin(),
  845. updateBranches.end());
  846. return out;
  847. }
  848. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  849. : QApplication(argc, argv),
  850. profilerNameStore(store)
  851. {
  852. /* fix float handling */
  853. #if defined(Q_OS_UNIX)
  854. if (!setlocale(LC_NUMERIC, "C"))
  855. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  856. #endif
  857. #ifndef _WIN32
  858. /* Handle SIGINT properly */
  859. socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd);
  860. snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
  861. connect(snInt, &QSocketNotifier::activated, this,
  862. &OBSApp::ProcessSigInt);
  863. #else
  864. connect(qApp, &QGuiApplication::commitDataRequest, this,
  865. &OBSApp::commitData);
  866. #endif
  867. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  868. #ifndef __APPLE__
  869. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  870. #endif
  871. setDesktopFileName("com.obsproject.Studio");
  872. }
  873. OBSApp::~OBSApp()
  874. {
  875. #ifdef _WIN32
  876. bool disableAudioDucking =
  877. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  878. if (disableAudioDucking)
  879. DisableAudioDucking(false);
  880. #else
  881. delete snInt;
  882. close(sigintFd[0]);
  883. close(sigintFd[1]);
  884. #endif
  885. #ifdef __APPLE__
  886. bool vsyncDisabled =
  887. config_get_bool(globalConfig, "Video", "DisableOSXVSync");
  888. bool resetVSync =
  889. config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
  890. if (vsyncDisabled && resetVSync)
  891. EnableOSXVSync(true);
  892. #endif
  893. os_inhibit_sleep_set_active(sleepInhibitor, false);
  894. os_inhibit_sleep_destroy(sleepInhibitor);
  895. if (libobs_initialized)
  896. obs_shutdown();
  897. }
  898. static void move_basic_to_profiles(void)
  899. {
  900. char path[512];
  901. char new_path[512];
  902. os_glob_t *glob;
  903. /* if not first time use */
  904. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  905. return;
  906. if (!os_file_exists(path))
  907. return;
  908. /* if the profiles directory doesn't already exist */
  909. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  910. return;
  911. if (os_file_exists(new_path))
  912. return;
  913. if (os_mkdir(new_path) == MKDIR_ERROR)
  914. return;
  915. strcat(new_path, "/");
  916. strcat(new_path, Str("Untitled"));
  917. if (os_mkdir(new_path) == MKDIR_ERROR)
  918. return;
  919. strcat(path, "/*.*");
  920. if (os_glob(path, 0, &glob) != 0)
  921. return;
  922. strcpy(path, new_path);
  923. for (size_t i = 0; i < glob->gl_pathc; i++) {
  924. struct os_globent ent = glob->gl_pathv[i];
  925. char *file;
  926. if (ent.directory)
  927. continue;
  928. file = strrchr(ent.path, '/');
  929. if (!file++)
  930. continue;
  931. if (astrcmpi(file, "scenes.json") == 0)
  932. continue;
  933. strcpy(new_path, path);
  934. strcat(new_path, "/");
  935. strcat(new_path, file);
  936. os_rename(ent.path, new_path);
  937. }
  938. os_globfree(glob);
  939. }
  940. static void move_basic_to_scene_collections(void)
  941. {
  942. char path[512];
  943. char new_path[512];
  944. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  945. return;
  946. if (!os_file_exists(path))
  947. return;
  948. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  949. return;
  950. if (os_file_exists(new_path))
  951. return;
  952. if (os_mkdir(new_path) == MKDIR_ERROR)
  953. return;
  954. strcat(path, "/scenes.json");
  955. strcat(new_path, "/");
  956. strcat(new_path, Str("Untitled"));
  957. strcat(new_path, ".json");
  958. os_rename(path, new_path);
  959. }
  960. void OBSApp::AppInit()
  961. {
  962. ProfileScope("OBSApp::AppInit");
  963. if (!MakeUserDirs())
  964. throw "Failed to create required user directories";
  965. if (!InitGlobalConfig())
  966. throw "Failed to initialize global config";
  967. if (!InitLocale())
  968. throw "Failed to load locale";
  969. if (!InitTheme())
  970. throw "Failed to load theme";
  971. config_set_default_string(globalConfig, "Basic", "Profile",
  972. Str("Untitled"));
  973. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  974. Str("Untitled"));
  975. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  976. Str("Untitled"));
  977. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  978. Str("Untitled"));
  979. config_set_default_bool(globalConfig, "Basic", "ConfigOnNewProfile",
  980. true);
  981. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  982. config_set_string(globalConfig, "Basic", "Profile",
  983. Str("Untitled"));
  984. config_set_string(globalConfig, "Basic", "ProfileDir",
  985. Str("Untitled"));
  986. }
  987. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  988. config_set_string(globalConfig, "Basic", "SceneCollection",
  989. Str("Untitled"));
  990. config_set_string(globalConfig, "Basic", "SceneCollectionFile",
  991. Str("Untitled"));
  992. }
  993. #ifdef _WIN32
  994. bool disableAudioDucking =
  995. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  996. if (disableAudioDucking)
  997. DisableAudioDucking(true);
  998. #endif
  999. #ifdef __APPLE__
  1000. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  1001. EnableOSXVSync(false);
  1002. #endif
  1003. UpdateHotkeyFocusSetting(false);
  1004. move_basic_to_profiles();
  1005. move_basic_to_scene_collections();
  1006. if (!MakeUserProfileDirs())
  1007. throw "Failed to create profile directories";
  1008. }
  1009. const char *OBSApp::GetRenderModule() const
  1010. {
  1011. const char *renderer =
  1012. config_get_string(globalConfig, "Video", "Renderer");
  1013. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1014. }
  1015. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1016. {
  1017. char path[512];
  1018. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1019. return false;
  1020. return obs_startup(locale, path, store);
  1021. }
  1022. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1023. {
  1024. obs_hotkey_enable_background_press(
  1025. (inFocus && enableHotkeysInFocus) ||
  1026. (!inFocus && enableHotkeysOutOfFocus));
  1027. }
  1028. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1029. {
  1030. enableHotkeysInFocus = true;
  1031. enableHotkeysOutOfFocus = true;
  1032. const char *hotkeyFocusType =
  1033. config_get_string(globalConfig, "General", "HotkeyFocusType");
  1034. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1035. enableHotkeysInFocus = false;
  1036. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1037. enableHotkeysOutOfFocus = false;
  1038. }
  1039. if (resetState)
  1040. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1041. }
  1042. void OBSApp::DisableHotkeys()
  1043. {
  1044. enableHotkeysInFocus = false;
  1045. enableHotkeysOutOfFocus = false;
  1046. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1047. }
  1048. Q_DECLARE_METATYPE(VoidFunc)
  1049. void OBSApp::Exec(VoidFunc func)
  1050. {
  1051. func();
  1052. }
  1053. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  1054. {
  1055. auto doTask = [=]() {
  1056. /* to get clang-format to behave */
  1057. task(param);
  1058. };
  1059. QMetaObject::invokeMethod(App(), "Exec",
  1060. wait ? WaitConnection() : Qt::AutoConnection,
  1061. Q_ARG(VoidFunc, doTask));
  1062. }
  1063. bool OBSApp::OBSInit()
  1064. {
  1065. ProfileScope("OBSApp::OBSInit");
  1066. qRegisterMetaType<VoidFunc>("VoidFunc");
  1067. #if !defined(_WIN32) && !defined(__APPLE__)
  1068. if (QApplication::platformName() == "xcb") {
  1069. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  1070. blog(LOG_INFO, "Using EGL/X11");
  1071. }
  1072. #ifdef ENABLE_WAYLAND
  1073. if (QApplication::platformName().contains("wayland")) {
  1074. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  1075. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1076. blog(LOG_INFO, "Platform: Wayland");
  1077. }
  1078. #endif
  1079. QPlatformNativeInterface *native =
  1080. QGuiApplication::platformNativeInterface();
  1081. obs_set_nix_platform_display(
  1082. native->nativeResourceForIntegration("display"));
  1083. #endif
  1084. #ifdef __APPLE__
  1085. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1086. #endif
  1087. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1088. return false;
  1089. libobs_initialized = true;
  1090. obs_set_ui_task_handler(ui_task_handler);
  1091. #if defined(_WIN32) || defined(__APPLE__)
  1092. bool browserHWAccel =
  1093. config_get_bool(globalConfig, "General", "BrowserHWAccel");
  1094. OBSDataAutoRelease settings = obs_data_create();
  1095. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1096. obs_apply_private_data(settings);
  1097. blog(LOG_INFO, "Current Date/Time: %s",
  1098. CurrentDateTimeString().c_str());
  1099. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1100. browserHWAccel ? "true" : "false");
  1101. #endif
  1102. #ifdef _WIN32
  1103. bool hideFromCapture = config_get_bool(globalConfig, "BasicWindow",
  1104. "HideOBSWindowsFromCapture");
  1105. blog(LOG_INFO, "Hide OBS windows from screen capture: %s",
  1106. hideFromCapture ? "true" : "false");
  1107. #endif
  1108. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(),
  1109. QT_VERSION_STR);
  1110. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1111. if (safe_mode) {
  1112. blog(LOG_WARNING, "Safe Mode enabled.");
  1113. } else if (disable_3p_plugins) {
  1114. blog(LOG_WARNING, "Third-party plugins disabled.");
  1115. }
  1116. setQuitOnLastWindowClosed(false);
  1117. mainWindow = new OBSBasic();
  1118. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1119. connect(mainWindow, &OBSBasic::destroyed, this, &OBSApp::quit);
  1120. mainWindow->OBSInit();
  1121. connect(this, &QGuiApplication::applicationStateChanged,
  1122. [this](Qt::ApplicationState state) {
  1123. ResetHotkeyState(state == Qt::ApplicationActive);
  1124. });
  1125. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1126. return true;
  1127. }
  1128. string OBSApp::GetVersionString(bool platform) const
  1129. {
  1130. stringstream ver;
  1131. #ifdef HAVE_OBSCONFIG_H
  1132. ver << obs_get_version_string();
  1133. #else
  1134. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1135. << LIBOBS_API_PATCH_VER;
  1136. #endif
  1137. if (platform) {
  1138. ver << " (";
  1139. #ifdef _WIN32
  1140. if (sizeof(void *) == 8)
  1141. ver << "64-bit, ";
  1142. else
  1143. ver << "32-bit, ";
  1144. ver << "windows)";
  1145. #elif __APPLE__
  1146. ver << "mac)";
  1147. #elif __OpenBSD__
  1148. ver << "openbsd)";
  1149. #elif __FreeBSD__
  1150. ver << "freebsd)";
  1151. #else /* assume linux for the time being */
  1152. ver << "linux)";
  1153. #endif
  1154. }
  1155. return ver.str();
  1156. }
  1157. bool OBSApp::IsPortableMode()
  1158. {
  1159. return portable_mode;
  1160. }
  1161. bool OBSApp::IsUpdaterDisabled()
  1162. {
  1163. return opt_disable_updater;
  1164. }
  1165. bool OBSApp::IsMissingFilesCheckDisabled()
  1166. {
  1167. return opt_disable_missing_files_check;
  1168. }
  1169. #ifdef __APPLE__
  1170. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1171. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1172. #elif _WIN32
  1173. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1174. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1175. #else
  1176. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1177. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1178. #endif
  1179. const char *OBSApp::InputAudioSource() const
  1180. {
  1181. return INPUT_AUDIO_SOURCE;
  1182. }
  1183. const char *OBSApp::OutputAudioSource() const
  1184. {
  1185. return OUTPUT_AUDIO_SOURCE;
  1186. }
  1187. const char *OBSApp::GetLastLog() const
  1188. {
  1189. return lastLogFile.c_str();
  1190. }
  1191. const char *OBSApp::GetCurrentLog() const
  1192. {
  1193. return currentLogFile.c_str();
  1194. }
  1195. const char *OBSApp::GetLastCrashLog() const
  1196. {
  1197. return lastCrashLogFile.c_str();
  1198. }
  1199. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1200. {
  1201. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1202. if (cb(lookupVal, out))
  1203. return true;
  1204. }
  1205. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1206. }
  1207. // Global handler to receive all QEvent::Show events so we can apply
  1208. // display affinity on any newly created windows and dialogs without
  1209. // caring where they are coming from (e.g. plugins).
  1210. bool OBSApp::notify(QObject *receiver, QEvent *e)
  1211. {
  1212. QWidget *w;
  1213. QWindow *window;
  1214. int windowType;
  1215. if (!receiver->isWidgetType())
  1216. goto skip;
  1217. if (e->type() != QEvent::Show)
  1218. goto skip;
  1219. w = qobject_cast<QWidget *>(receiver);
  1220. if (!w->isWindow())
  1221. goto skip;
  1222. window = w->windowHandle();
  1223. if (!window)
  1224. goto skip;
  1225. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  1226. if (windowType == Qt::WindowType::Dialog ||
  1227. windowType == Qt::WindowType::Window ||
  1228. windowType == Qt::WindowType::Tool) {
  1229. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1230. if (main)
  1231. main->SetDisplayAffinity(window);
  1232. }
  1233. skip:
  1234. return QApplication::notify(receiver, e);
  1235. }
  1236. QString OBSTranslator::translate(const char *, const char *sourceText,
  1237. const char *, int) const
  1238. {
  1239. const char *out = nullptr;
  1240. QString str(sourceText);
  1241. str.replace(" ", "");
  1242. if (!App()->TranslateString(QT_TO_UTF8(str), &out))
  1243. return QString(sourceText);
  1244. return QT_UTF8(out);
  1245. }
  1246. static bool get_token(lexer *lex, string &str, base_token_type type)
  1247. {
  1248. base_token token;
  1249. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1250. return false;
  1251. if (token.type != type)
  1252. return false;
  1253. str.assign(token.text.array, token.text.len);
  1254. return true;
  1255. }
  1256. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1257. {
  1258. base_token token;
  1259. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1260. return false;
  1261. if (token.type != type)
  1262. return false;
  1263. return strref_cmp(&token.text, str) == 0;
  1264. }
  1265. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1266. {
  1267. BaseLexer lex;
  1268. string year, month, day, hour, minute, second;
  1269. lexer_start(lex, name);
  1270. if (has_prefix) {
  1271. string temp;
  1272. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1273. return 0;
  1274. }
  1275. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1276. return 0;
  1277. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1278. return 0;
  1279. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1280. return 0;
  1281. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1282. return 0;
  1283. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1284. return 0;
  1285. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1286. return 0;
  1287. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1288. return 0;
  1289. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1290. return 0;
  1291. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1292. return 0;
  1293. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1294. return 0;
  1295. stringstream timestring;
  1296. timestring << year << month << day << hour << minute << second;
  1297. return std::stoull(timestring.str());
  1298. }
  1299. static void delete_oldest_file(bool has_prefix, const char *location)
  1300. {
  1301. BPtr<char> logDir(GetConfigPathPtr(location));
  1302. string oldestLog;
  1303. uint64_t oldest_ts = (uint64_t)-1;
  1304. struct os_dirent *entry;
  1305. unsigned int maxLogs = (unsigned int)config_get_uint(
  1306. App()->GlobalConfig(), "General", "MaxLogs");
  1307. os_dir_t *dir = os_opendir(logDir);
  1308. if (dir) {
  1309. unsigned int count = 0;
  1310. while ((entry = os_readdir(dir)) != NULL) {
  1311. if (entry->directory || *entry->d_name == '.')
  1312. continue;
  1313. uint64_t ts =
  1314. convert_log_name(has_prefix, entry->d_name);
  1315. if (ts) {
  1316. if (ts < oldest_ts) {
  1317. oldestLog = entry->d_name;
  1318. oldest_ts = ts;
  1319. }
  1320. count++;
  1321. }
  1322. }
  1323. os_closedir(dir);
  1324. if (count > maxLogs) {
  1325. stringstream delPath;
  1326. delPath << logDir << "/" << oldestLog;
  1327. os_unlink(delPath.str().c_str());
  1328. }
  1329. }
  1330. }
  1331. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1332. std::string &last)
  1333. {
  1334. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1335. struct os_dirent *entry;
  1336. os_dir_t *dir = os_opendir(logDir);
  1337. uint64_t highest_ts = 0;
  1338. if (dir) {
  1339. while ((entry = os_readdir(dir)) != NULL) {
  1340. if (entry->directory || *entry->d_name == '.')
  1341. continue;
  1342. uint64_t ts =
  1343. convert_log_name(has_prefix, entry->d_name);
  1344. if (ts > highest_ts) {
  1345. last = entry->d_name;
  1346. highest_ts = ts;
  1347. }
  1348. }
  1349. os_closedir(dir);
  1350. }
  1351. }
  1352. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1353. {
  1354. time_t now = time(0);
  1355. char file[256] = {};
  1356. struct tm *cur_time;
  1357. cur_time = localtime(&now);
  1358. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1359. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1360. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1361. cur_time->tm_min, cur_time->tm_sec, extension);
  1362. return string(file);
  1363. }
  1364. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1365. const char *format)
  1366. {
  1367. BPtr<char> filename =
  1368. os_generate_formatted_filename(extension, !noSpace, format);
  1369. return string(filename);
  1370. }
  1371. static void FindBestFilename(string &strPath, bool noSpace)
  1372. {
  1373. int num = 2;
  1374. if (!os_file_exists(strPath.c_str()))
  1375. return;
  1376. const char *ext = strrchr(strPath.c_str(), '.');
  1377. if (!ext)
  1378. return;
  1379. int extStart = int(ext - strPath.c_str());
  1380. for (;;) {
  1381. string testPath = strPath;
  1382. string numStr;
  1383. numStr = noSpace ? "_" : " (";
  1384. numStr += to_string(num++);
  1385. if (!noSpace)
  1386. numStr += ")";
  1387. testPath.insert(extStart, numStr);
  1388. if (!os_file_exists(testPath.c_str())) {
  1389. strPath = testPath;
  1390. break;
  1391. }
  1392. }
  1393. }
  1394. static void ensure_directory_exists(string &path)
  1395. {
  1396. replace(path.begin(), path.end(), '\\', '/');
  1397. size_t last = path.rfind('/');
  1398. if (last == string::npos)
  1399. return;
  1400. string directory = path.substr(0, last);
  1401. os_mkdirs(directory.c_str());
  1402. }
  1403. static void remove_reserved_file_characters(string &s)
  1404. {
  1405. replace(s.begin(), s.end(), '\\', '/');
  1406. replace(s.begin(), s.end(), '*', '_');
  1407. replace(s.begin(), s.end(), '?', '_');
  1408. replace(s.begin(), s.end(), '"', '_');
  1409. replace(s.begin(), s.end(), '|', '_');
  1410. replace(s.begin(), s.end(), ':', '_');
  1411. replace(s.begin(), s.end(), '>', '_');
  1412. replace(s.begin(), s.end(), '<', '_');
  1413. }
  1414. string GetFormatString(const char *format, const char *prefix,
  1415. const char *suffix)
  1416. {
  1417. string f;
  1418. f = format;
  1419. if (prefix && *prefix) {
  1420. string str_prefix = prefix;
  1421. if (str_prefix.back() != ' ')
  1422. str_prefix += " ";
  1423. size_t insert_pos = 0;
  1424. size_t tmp;
  1425. tmp = f.find_last_of('/');
  1426. if (tmp != string::npos && tmp > insert_pos)
  1427. insert_pos = tmp + 1;
  1428. tmp = f.find_last_of('\\');
  1429. if (tmp != string::npos && tmp > insert_pos)
  1430. insert_pos = tmp + 1;
  1431. f.insert(insert_pos, str_prefix);
  1432. }
  1433. if (suffix && *suffix) {
  1434. if (*suffix != ' ')
  1435. f += " ";
  1436. f += suffix;
  1437. }
  1438. remove_reserved_file_characters(f);
  1439. return f;
  1440. }
  1441. string GetFormatExt(const char *container)
  1442. {
  1443. string ext = container;
  1444. if (ext == "fragmented_mp4")
  1445. ext = "mp4";
  1446. if (ext == "hybrid_mp4")
  1447. ext = "mp4";
  1448. else if (ext == "fragmented_mov")
  1449. ext = "mov";
  1450. else if (ext == "hls")
  1451. ext = "m3u8";
  1452. else if (ext == "mpegts")
  1453. ext = "ts";
  1454. return ext;
  1455. }
  1456. string GetOutputFilename(const char *path, const char *container, bool noSpace,
  1457. bool overwrite, const char *format)
  1458. {
  1459. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1460. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1461. if (!dir) {
  1462. if (main->isVisible())
  1463. OBSMessageBox::warning(main,
  1464. QTStr("Output.BadPath.Title"),
  1465. QTStr("Output.BadPath.Text"));
  1466. else
  1467. main->SysTrayNotify(QTStr("Output.BadPath.Text"),
  1468. QSystemTrayIcon::Warning);
  1469. return "";
  1470. }
  1471. os_closedir(dir);
  1472. string strPath;
  1473. strPath += path;
  1474. char lastChar = strPath.back();
  1475. if (lastChar != '/' && lastChar != '\\')
  1476. strPath += "/";
  1477. string ext = GetFormatExt(container);
  1478. strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format);
  1479. ensure_directory_exists(strPath);
  1480. if (!overwrite)
  1481. FindBestFilename(strPath, noSpace);
  1482. return strPath;
  1483. }
  1484. vector<pair<string, string>> GetLocaleNames()
  1485. {
  1486. string path;
  1487. if (!GetDataFilePath("locale.ini", path))
  1488. throw "Could not find locale.ini path";
  1489. ConfigFile ini;
  1490. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1491. throw "Could not open locale.ini";
  1492. size_t sections = config_num_sections(ini);
  1493. vector<pair<string, string>> names;
  1494. names.reserve(sections);
  1495. for (size_t i = 0; i < sections; i++) {
  1496. const char *tag = config_get_section(ini, i);
  1497. const char *name = config_get_string(ini, tag, "Name");
  1498. names.emplace_back(tag, name);
  1499. }
  1500. return names;
  1501. }
  1502. static void create_log_file(fstream &logFile)
  1503. {
  1504. stringstream dst;
  1505. get_last_log(false, "obs-studio/logs", lastLogFile);
  1506. #ifdef _WIN32
  1507. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1508. #endif
  1509. currentLogFile = GenerateTimeDateFilename("txt");
  1510. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1511. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1512. #ifdef _WIN32
  1513. BPtr<wchar_t> wpath;
  1514. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1515. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1516. #else
  1517. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1518. #endif
  1519. if (logFile.is_open()) {
  1520. delete_oldest_file(false, "obs-studio/logs");
  1521. base_set_log_handler(do_log, &logFile);
  1522. } else {
  1523. blog(LOG_ERROR, "Failed to open log file");
  1524. }
  1525. }
  1526. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1527. profiler_name_store_free(store);
  1528. };
  1529. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1530. decltype(ProfilerNameStoreRelease)>;
  1531. ProfilerNameStore CreateNameStore()
  1532. {
  1533. return ProfilerNameStore{profiler_name_store_create(),
  1534. ProfilerNameStoreRelease};
  1535. }
  1536. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1537. profile_snapshot_free(snap);
  1538. };
  1539. using ProfilerSnapshot =
  1540. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1541. ProfilerSnapshot GetSnapshot()
  1542. {
  1543. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1544. }
  1545. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1546. {
  1547. if (currentLogFile.empty())
  1548. return;
  1549. auto pos = currentLogFile.rfind('.');
  1550. if (pos == currentLogFile.npos)
  1551. return;
  1552. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1553. ostringstream dst;
  1554. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1555. dst.write(currentLogFile.c_str(), pos);
  1556. dst.write(LITERAL_SIZE(".csv.gz"));
  1557. #undef LITERAL_SIZE
  1558. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1559. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1560. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1561. static_cast<const char *>(path));
  1562. }
  1563. static auto ProfilerFree = [](void *) {
  1564. profiler_stop();
  1565. auto snap = GetSnapshot();
  1566. profiler_print(snap.get());
  1567. profiler_print_time_between_calls(snap.get());
  1568. SaveProfilerData(snap);
  1569. profiler_free();
  1570. };
  1571. QAccessibleInterface *accessibleFactory(const QString &classname,
  1572. QObject *object)
  1573. {
  1574. if (classname == QLatin1String("VolumeSlider") && object &&
  1575. object->isWidgetType())
  1576. return new VolumeAccessibleInterface(
  1577. static_cast<QWidget *>(object));
  1578. return nullptr;
  1579. }
  1580. static const char *run_program_init = "run_program_init";
  1581. static int run_program(fstream &logFile, int argc, char *argv[])
  1582. {
  1583. int ret = -1;
  1584. auto profilerNameStore = CreateNameStore();
  1585. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1586. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1587. profiler_start();
  1588. profile_register_root(run_program_init, 0);
  1589. ScopeProfiler prof{run_program_init};
  1590. #ifdef _WIN32
  1591. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
  1592. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1593. #endif
  1594. QCoreApplication::addLibraryPath(".");
  1595. #if __APPLE__
  1596. InstallNSApplicationSubclass();
  1597. InstallNSThreadLocks();
  1598. if (!isInBundle()) {
  1599. blog(LOG_ERROR,
  1600. "OBS cannot be run as a standalone binary on macOS. Run the Application bundle instead.");
  1601. return ret;
  1602. }
  1603. #endif
  1604. #if !defined(_WIN32) && !defined(__APPLE__)
  1605. /* NOTE: Users blindly set this, but this theme is incompatble with Qt6 and
  1606. * crashes loading saved geometry. Just turn off this theme and let users complain OBS
  1607. * looks ugly instead of crashing. */
  1608. const char *platform_theme = getenv("QT_QPA_PLATFORMTHEME");
  1609. if (platform_theme && strcmp(platform_theme, "qt5ct") == 0)
  1610. unsetenv("QT_QPA_PLATFORMTHEME");
  1611. #if defined(ENABLE_WAYLAND) && defined(USE_XDG) && \
  1612. QT_VERSION < QT_VERSION_CHECK(6, 3, 0)
  1613. /* NOTE: Qt doesn't use the Wayland platform on GNOME, so we have to
  1614. * force it using the QT_QPA_PLATFORM env var. It's still possible to
  1615. * use other QPA platforms using this env var, or the -platform command
  1616. * line option. Remove after Qt 6.3 is everywhere. */
  1617. const char *desktop = getenv("XDG_CURRENT_DESKTOP");
  1618. const char *session_type = getenv("XDG_SESSION_TYPE");
  1619. if (session_type && desktop && strstr(desktop, "GNOME") != nullptr &&
  1620. strcmp(session_type, "wayland") == 0)
  1621. setenv("QT_QPA_PLATFORM", "wayland", false);
  1622. #endif
  1623. #endif
  1624. /* NOTE: This disables an optimisation in Qt that attempts to determine if
  1625. * any "siblings" intersect with a widget when determining the approximate
  1626. * visible/unobscured area. However, by Qt's own admission this is slow
  1627. * and in the case of OBS it significantly slows down lists with many
  1628. * elements (e.g. Hotkeys) and it is actually faster to disable it. */
  1629. qputenv("QT_NO_SUBTRACTOPAQUESIBLINGS", "1");
  1630. OBSApp program(argc, argv, profilerNameStore.get());
  1631. try {
  1632. QAccessible::installFactory(accessibleFactory);
  1633. QFontDatabase::addApplicationFont(
  1634. ":/fonts/OpenSans-Regular.ttf");
  1635. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Bold.ttf");
  1636. QFontDatabase::addApplicationFont(
  1637. ":/fonts/OpenSans-Italic.ttf");
  1638. bool created_log = false;
  1639. program.AppInit();
  1640. delete_oldest_file(false, "obs-studio/profiler_data");
  1641. OBSTranslator translator;
  1642. program.installTranslator(&translator);
  1643. /* --------------------------------------- */
  1644. /* check and warn if already running */
  1645. bool cancel_launch = false;
  1646. bool already_running = false;
  1647. #ifdef _WIN32
  1648. RunOnceMutex rom =
  1649. #endif
  1650. CheckIfAlreadyRunning(already_running);
  1651. if (!already_running) {
  1652. goto run;
  1653. }
  1654. if (!multi) {
  1655. QMessageBox mb(QMessageBox::Question,
  1656. QTStr("AlreadyRunning.Title"),
  1657. QTStr("AlreadyRunning.Text"));
  1658. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"),
  1659. QMessageBox::YesRole);
  1660. QPushButton *cancelButton = mb.addButton(
  1661. QTStr("Cancel"), QMessageBox::NoRole);
  1662. mb.setDefaultButton(cancelButton);
  1663. mb.exec();
  1664. cancel_launch = mb.clickedButton() == cancelButton;
  1665. }
  1666. if (cancel_launch)
  1667. return 0;
  1668. if (!created_log) {
  1669. create_log_file(logFile);
  1670. created_log = true;
  1671. }
  1672. if (multi) {
  1673. blog(LOG_INFO, "User enabled --multi flag and is now "
  1674. "running multiple instances of OBS.");
  1675. } else {
  1676. blog(LOG_WARNING, "================================");
  1677. blog(LOG_WARNING, "Warning: OBS is already running!");
  1678. blog(LOG_WARNING, "================================");
  1679. blog(LOG_WARNING, "User is now running multiple "
  1680. "instances of OBS!");
  1681. /* Clear unclean_shutdown flag as multiple instances
  1682. * running from the same config will lead to a
  1683. * false-positive detection.*/
  1684. unclean_shutdown = false;
  1685. }
  1686. /* --------------------------------------- */
  1687. run:
  1688. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1689. // Mounted by termina during chromeOS linux container startup
  1690. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1691. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1692. if (crosDir) {
  1693. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1694. QMessageBox mb(QMessageBox::Critical,
  1695. QTStr("ChromeOS.Title"),
  1696. QTStr("ChromeOS.Text"), buttons,
  1697. nullptr);
  1698. mb.exec();
  1699. return 0;
  1700. }
  1701. #endif
  1702. if (!created_log)
  1703. create_log_file(logFile);
  1704. if (unclean_shutdown) {
  1705. blog(LOG_WARNING,
  1706. "[Safe Mode] Unclean shutdown detected!");
  1707. }
  1708. if (unclean_shutdown && !safe_mode) {
  1709. QMessageBox mb(QMessageBox::Warning,
  1710. QTStr("AutoSafeMode.Title"),
  1711. QTStr("AutoSafeMode.Text"));
  1712. QPushButton *launchSafeButton =
  1713. mb.addButton(QTStr("AutoSafeMode.LaunchSafe"),
  1714. QMessageBox::AcceptRole);
  1715. QPushButton *launchNormalButton =
  1716. mb.addButton(QTStr("AutoSafeMode.LaunchNormal"),
  1717. QMessageBox::RejectRole);
  1718. mb.setDefaultButton(launchNormalButton);
  1719. mb.exec();
  1720. safe_mode = mb.clickedButton() == launchSafeButton;
  1721. if (safe_mode) {
  1722. blog(LOG_INFO,
  1723. "[Safe Mode] User has launched in Safe Mode.");
  1724. } else {
  1725. blog(LOG_WARNING,
  1726. "[Safe Mode] User elected to launch normally.");
  1727. }
  1728. }
  1729. qInstallMessageHandler([](QtMsgType type,
  1730. const QMessageLogContext &,
  1731. const QString &message) {
  1732. switch (type) {
  1733. #ifdef _DEBUG
  1734. case QtDebugMsg:
  1735. blog(LOG_DEBUG, "%s", QT_TO_UTF8(message));
  1736. break;
  1737. case QtInfoMsg:
  1738. blog(LOG_INFO, "%s", QT_TO_UTF8(message));
  1739. break;
  1740. #else
  1741. case QtDebugMsg:
  1742. case QtInfoMsg:
  1743. break;
  1744. #endif
  1745. case QtWarningMsg:
  1746. blog(LOG_WARNING, "%s", QT_TO_UTF8(message));
  1747. break;
  1748. case QtCriticalMsg:
  1749. case QtFatalMsg:
  1750. blog(LOG_ERROR, "%s", QT_TO_UTF8(message));
  1751. break;
  1752. }
  1753. });
  1754. #ifdef __APPLE__
  1755. MacPermissionStatus audio_permission =
  1756. CheckPermission(kAudioDeviceAccess);
  1757. MacPermissionStatus video_permission =
  1758. CheckPermission(kVideoDeviceAccess);
  1759. MacPermissionStatus accessibility_permission =
  1760. CheckPermission(kAccessibility);
  1761. MacPermissionStatus screen_permission =
  1762. CheckPermission(kScreenCapture);
  1763. int permissionsDialogLastShown =
  1764. config_get_int(GetGlobalConfig(), "General",
  1765. "MacOSPermissionsDialogLastShown");
  1766. if (permissionsDialogLastShown <
  1767. MACOS_PERMISSIONS_DIALOG_VERSION) {
  1768. OBSPermissions check(nullptr, screen_permission,
  1769. video_permission, audio_permission,
  1770. accessibility_permission);
  1771. check.exec();
  1772. }
  1773. #endif
  1774. #ifdef _WIN32
  1775. if (IsRunningOnWine()) {
  1776. QMessageBox mb(QMessageBox::Question,
  1777. QTStr("Wine.Title"), QTStr("Wine.Text"));
  1778. mb.setTextFormat(Qt::RichText);
  1779. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"),
  1780. QMessageBox::AcceptRole);
  1781. QPushButton *closeButton =
  1782. mb.addButton(QMessageBox::Close);
  1783. mb.setDefaultButton(closeButton);
  1784. mb.exec();
  1785. if (mb.clickedButton() == closeButton)
  1786. return 0;
  1787. }
  1788. #endif
  1789. if (argc > 1) {
  1790. stringstream stor;
  1791. stor << argv[1];
  1792. for (int i = 2; i < argc; ++i) {
  1793. stor << " " << argv[i];
  1794. }
  1795. blog(LOG_INFO, "Command Line Arguments: %s",
  1796. stor.str().c_str());
  1797. }
  1798. if (!program.OBSInit())
  1799. return 0;
  1800. prof.Stop();
  1801. ret = program.exec();
  1802. } catch (const char *error) {
  1803. blog(LOG_ERROR, "%s", error);
  1804. OBSErrorBox(nullptr, "%s", error);
  1805. }
  1806. if (restart || restart_safe) {
  1807. arguments = qApp->arguments();
  1808. if (restart_safe) {
  1809. arguments.append("--safe-mode");
  1810. } else {
  1811. arguments.removeAll("--safe-mode");
  1812. }
  1813. }
  1814. return ret;
  1815. }
  1816. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1817. #ifdef _WIN32
  1818. #define CRASH_MESSAGE \
  1819. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1820. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1821. static void main_crash_handler(const char *format, va_list args,
  1822. void * /* param */)
  1823. {
  1824. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1825. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1826. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1827. string crashFilePath = "obs-studio/crashes";
  1828. delete_oldest_file(true, crashFilePath.c_str());
  1829. string name = crashFilePath + "/";
  1830. name += "Crash " + GenerateTimeDateFilename("txt");
  1831. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1832. fstream file;
  1833. #ifdef _WIN32
  1834. BPtr<wchar_t> wpath;
  1835. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1836. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1837. ios_base::binary);
  1838. #else
  1839. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1840. ios_base::binary);
  1841. #endif
  1842. file << text;
  1843. file.close();
  1844. string pathString(path.Get());
  1845. #ifdef _WIN32
  1846. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1847. #endif
  1848. string absolutePath =
  1849. canonical(filesystem::path(pathString)).u8string();
  1850. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1851. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1852. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
  1853. absolutePath.c_str());
  1854. string finalMessage =
  1855. string(message_buffer.get(), message_buffer.get() + size);
  1856. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
  1857. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1858. if (ret == IDYES) {
  1859. size_t len = strlen(text);
  1860. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1861. memcpy(GlobalLock(mem), text, len);
  1862. GlobalUnlock(mem);
  1863. OpenClipboard(0);
  1864. EmptyClipboard();
  1865. SetClipboardData(CF_TEXT, mem);
  1866. CloseClipboard();
  1867. }
  1868. exit(-1);
  1869. }
  1870. static void load_debug_privilege(void)
  1871. {
  1872. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1873. TOKEN_PRIVILEGES tp;
  1874. HANDLE token;
  1875. LUID val;
  1876. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1877. return;
  1878. }
  1879. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1880. tp.PrivilegeCount = 1;
  1881. tp.Privileges[0].Luid = val;
  1882. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1883. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1884. NULL);
  1885. }
  1886. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1887. tp.PrivilegeCount = 1;
  1888. tp.Privileges[0].Luid = val;
  1889. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1890. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1891. NULL)) {
  1892. blog(LOG_INFO, "Could not set privilege to "
  1893. "increase GPU priority");
  1894. }
  1895. }
  1896. CloseHandle(token);
  1897. }
  1898. #endif
  1899. #ifdef __APPLE__
  1900. #define BASE_PATH ".."
  1901. #else
  1902. #define BASE_PATH "../.."
  1903. #endif
  1904. #define CONFIG_PATH BASE_PATH "/config"
  1905. #if defined(LINUX_PORTABLE) || defined(_WIN32)
  1906. #define ALLOW_PORTABLE_MODE 1
  1907. #else
  1908. #define ALLOW_PORTABLE_MODE 0
  1909. #endif
  1910. int GetConfigPath(char *path, size_t size, const char *name)
  1911. {
  1912. #if ALLOW_PORTABLE_MODE
  1913. if (portable_mode) {
  1914. if (name && *name) {
  1915. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1916. } else {
  1917. return snprintf(path, size, CONFIG_PATH);
  1918. }
  1919. } else {
  1920. return os_get_config_path(path, size, name);
  1921. }
  1922. #else
  1923. return os_get_config_path(path, size, name);
  1924. #endif
  1925. }
  1926. char *GetConfigPathPtr(const char *name)
  1927. {
  1928. #if ALLOW_PORTABLE_MODE
  1929. if (portable_mode) {
  1930. char path[512];
  1931. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1932. return bstrdup(path);
  1933. } else {
  1934. return NULL;
  1935. }
  1936. } else {
  1937. return os_get_config_path_ptr(name);
  1938. }
  1939. #else
  1940. return os_get_config_path_ptr(name);
  1941. #endif
  1942. }
  1943. int GetProgramDataPath(char *path, size_t size, const char *name)
  1944. {
  1945. return os_get_program_data_path(path, size, name);
  1946. }
  1947. char *GetProgramDataPathPtr(const char *name)
  1948. {
  1949. return os_get_program_data_path_ptr(name);
  1950. }
  1951. bool GetFileSafeName(const char *name, std::string &file)
  1952. {
  1953. size_t base_len = strlen(name);
  1954. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1955. std::wstring wfile;
  1956. if (!len)
  1957. return false;
  1958. wfile.resize(len);
  1959. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1960. for (size_t i = wfile.size(); i > 0; i--) {
  1961. size_t im1 = i - 1;
  1962. if (iswspace(wfile[im1])) {
  1963. wfile[im1] = '_';
  1964. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1965. wfile.erase(im1, 1);
  1966. }
  1967. }
  1968. if (wfile.size() == 0)
  1969. wfile = L"characters_only";
  1970. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1971. if (!len)
  1972. return false;
  1973. file.resize(len);
  1974. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1975. return true;
  1976. }
  1977. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1978. {
  1979. size_t len = path.size();
  1980. if (extension) {
  1981. path += ".";
  1982. path += extension;
  1983. }
  1984. if (!os_file_exists(path.c_str()))
  1985. return true;
  1986. int index = 1;
  1987. do {
  1988. path.resize(len);
  1989. path += std::to_string(++index);
  1990. if (extension) {
  1991. path += ".";
  1992. path += extension;
  1993. }
  1994. } while (os_file_exists(path.c_str()));
  1995. return true;
  1996. }
  1997. bool GetUnusedSceneCollectionFile(std::string &name, std::string &file)
  1998. {
  1999. char path[512];
  2000. int ret;
  2001. if (!GetFileSafeName(name.c_str(), file)) {
  2002. blog(LOG_WARNING, "Failed to create safe file name for '%s'",
  2003. name.c_str());
  2004. return false;
  2005. }
  2006. ret = GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes/");
  2007. if (ret <= 0) {
  2008. blog(LOG_WARNING, "Failed to get scene collection config path");
  2009. return false;
  2010. }
  2011. file.insert(0, path);
  2012. if (!GetClosestUnusedFileName(file, "json")) {
  2013. blog(LOG_WARNING, "Failed to get closest file name for %s",
  2014. file.c_str());
  2015. return false;
  2016. }
  2017. file.erase(file.size() - 5, 5);
  2018. file.erase(0, strlen(path));
  2019. return true;
  2020. }
  2021. bool WindowPositionValid(QRect rect)
  2022. {
  2023. for (QScreen *screen : QGuiApplication::screens()) {
  2024. if (screen->availableGeometry().intersects(rect))
  2025. return true;
  2026. }
  2027. return false;
  2028. }
  2029. static inline bool arg_is(const char *arg, const char *long_form,
  2030. const char *short_form)
  2031. {
  2032. return (long_form && strcmp(arg, long_form) == 0) ||
  2033. (short_form && strcmp(arg, short_form) == 0);
  2034. }
  2035. static void check_safe_mode_sentinel(void)
  2036. {
  2037. #ifndef NDEBUG
  2038. /* Safe Mode detection is disabled in Debug builds to keep developers
  2039. * somewhat sane. */
  2040. return;
  2041. #else
  2042. if (disable_shutdown_check)
  2043. return;
  2044. BPtr sentinelPath = GetConfigPathPtr("obs-studio/safe_mode");
  2045. if (os_file_exists(sentinelPath)) {
  2046. unclean_shutdown = true;
  2047. return;
  2048. }
  2049. os_quick_write_utf8_file(sentinelPath, nullptr, 0, false);
  2050. #endif
  2051. }
  2052. static void delete_safe_mode_sentinel(void)
  2053. {
  2054. BPtr sentinelPath = GetConfigPathPtr("obs-studio/safe_mode");
  2055. os_unlink(sentinelPath);
  2056. }
  2057. #ifndef _WIN32
  2058. void OBSApp::SigIntSignalHandler(int s)
  2059. {
  2060. /* Handles SIGINT and writes to a socket. Qt will read
  2061. * from the socket in the main thread event loop and trigger
  2062. * a call to the ProcessSigInt slot, where we can safely run
  2063. * shutdown code without signal safety issues. */
  2064. UNUSED_PARAMETER(s);
  2065. char a = 1;
  2066. send(sigintFd[0], &a, sizeof(a), 0);
  2067. }
  2068. #endif
  2069. void OBSApp::ProcessSigInt(void)
  2070. {
  2071. /* This looks weird, but we can't ifdef a Qt slot function so
  2072. * the SIGINT handler simply does nothing on Windows. */
  2073. #ifndef _WIN32
  2074. char tmp;
  2075. recv(sigintFd[1], &tmp, sizeof(tmp), 0);
  2076. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  2077. if (main)
  2078. main->close();
  2079. #endif
  2080. }
  2081. #ifdef _WIN32
  2082. void OBSApp::commitData(QSessionManager &manager)
  2083. {
  2084. if (auto main = App()->GetMainWindow()) {
  2085. QMetaObject::invokeMethod(main, "close", Qt::QueuedConnection);
  2086. manager.cancel();
  2087. }
  2088. }
  2089. #endif
  2090. #ifdef _WIN32
  2091. static constexpr char vcRunErrorTitle[] = "Outdated Visual C++ Runtime";
  2092. static constexpr char vcRunErrorMsg[] =
  2093. "OBS Studio requires a newer version of the Microsoft Visual C++ "
  2094. "Redistributables.\n\nYou will now be directed to the download page.";
  2095. static constexpr char vcRunInstallerUrl[] =
  2096. "https://obsproject.com/visual-studio-2022-runtimes";
  2097. static bool vc_runtime_outdated()
  2098. {
  2099. win_version_info ver;
  2100. if (!get_dll_ver(L"msvcp140.dll", &ver))
  2101. return true;
  2102. /* Major is always 14 (hence 140.dll), so we only care about minor. */
  2103. if (ver.minor >= 40)
  2104. return false;
  2105. int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle,
  2106. MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL);
  2107. if (choice == IDOK) {
  2108. /* Open the URL in the default browser. */
  2109. ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL,
  2110. SW_SHOWNORMAL);
  2111. }
  2112. return true;
  2113. }
  2114. #endif
  2115. int main(int argc, char *argv[])
  2116. {
  2117. #ifndef _WIN32
  2118. signal(SIGPIPE, SIG_IGN);
  2119. struct sigaction sig_handler;
  2120. sig_handler.sa_handler = OBSApp::SigIntSignalHandler;
  2121. sigemptyset(&sig_handler.sa_mask);
  2122. sig_handler.sa_flags = 0;
  2123. sigaction(SIGINT, &sig_handler, NULL);
  2124. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  2125. a closed pipe. */
  2126. sigset_t sigpipe_mask;
  2127. sigemptyset(&sigpipe_mask);
  2128. sigaddset(&sigpipe_mask, SIGPIPE);
  2129. sigset_t saved_mask;
  2130. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  2131. perror("pthread_sigmask");
  2132. exit(1);
  2133. }
  2134. #endif
  2135. #ifdef _WIN32
  2136. // Abort as early as possible if MSVC runtime is outdated
  2137. if (vc_runtime_outdated())
  2138. return 1;
  2139. // Try to keep this as early as possible
  2140. install_dll_blocklist_hook();
  2141. obs_init_win32_crash_handler();
  2142. SetErrorMode(SEM_FAILCRITICALERRORS);
  2143. load_debug_privilege();
  2144. base_set_crash_handler(main_crash_handler, nullptr);
  2145. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  2146. if (hRtwq) {
  2147. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  2148. PFN_RtwqStartup func =
  2149. (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  2150. func();
  2151. }
  2152. #endif
  2153. base_get_log_handler(&def_log_handler, nullptr);
  2154. obs_set_cmdline_args(argc, argv);
  2155. for (int i = 1; i < argc; i++) {
  2156. if (arg_is(argv[i], "--multi", "-m")) {
  2157. multi = true;
  2158. disable_shutdown_check = true;
  2159. #if ALLOW_PORTABLE_MODE
  2160. } else if (arg_is(argv[i], "--portable", "-p")) {
  2161. portable_mode = true;
  2162. #endif
  2163. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2164. log_verbose = true;
  2165. } else if (arg_is(argv[i], "--safe-mode", nullptr)) {
  2166. safe_mode = true;
  2167. } else if (arg_is(argv[i], "--only-bundled-plugins", nullptr)) {
  2168. disable_3p_plugins = true;
  2169. } else if (arg_is(argv[i], "--disable-shutdown-check",
  2170. nullptr)) {
  2171. /* This exists mostly to bypass the dialog during development. */
  2172. disable_shutdown_check = true;
  2173. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2174. opt_always_on_top = true;
  2175. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2176. unfiltered_log = true;
  2177. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2178. opt_start_streaming = true;
  2179. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2180. opt_start_recording = true;
  2181. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2182. opt_start_replaybuffer = true;
  2183. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2184. opt_start_virtualcam = true;
  2185. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2186. if (++i < argc)
  2187. opt_starting_collection = argv[i];
  2188. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2189. if (++i < argc)
  2190. opt_starting_profile = argv[i];
  2191. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2192. if (++i < argc)
  2193. opt_starting_scene = argv[i];
  2194. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2195. opt_minimize_tray = true;
  2196. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2197. opt_studio_mode = true;
  2198. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2199. opt_allow_opengl = true;
  2200. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2201. opt_disable_updater = true;
  2202. } else if (arg_is(argv[i], "--disable-missing-files-check",
  2203. nullptr)) {
  2204. opt_disable_missing_files_check = true;
  2205. } else if (arg_is(argv[i], "--steam", nullptr)) {
  2206. steam = true;
  2207. } else if (arg_is(argv[i], "--help", "-h")) {
  2208. std::string help =
  2209. "--help, -h: Get list of available commands.\n\n"
  2210. "--startstreaming: Automatically start streaming.\n"
  2211. "--startrecording: Automatically start recording.\n"
  2212. "--startreplaybuffer: Start replay buffer.\n"
  2213. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2214. "--collection <string>: Use specific scene collection."
  2215. "\n"
  2216. "--profile <string>: Use specific profile.\n"
  2217. "--scene <string>: Start with specific scene.\n\n"
  2218. "--studio-mode: Enable studio mode.\n"
  2219. "--minimize-to-tray: Minimize to system tray.\n"
  2220. #if ALLOW_PORTABLE_MODE
  2221. "--portable, -p: Use portable mode.\n"
  2222. #endif
  2223. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2224. "--safe-mode: Run in Safe Mode (disables third-party plugins, scripting, and WebSockets).\n"
  2225. "--only-bundled-plugins: Only load included (first-party) plugins\n"
  2226. "--disable-shutdown-check: Disable unclean shutdown detection.\n"
  2227. "--verbose: Make log more verbose.\n"
  2228. "--always-on-top: Start in 'always on top' mode.\n\n"
  2229. "--unfiltered_log: Make log unfiltered.\n\n"
  2230. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2231. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n";
  2232. #ifdef _WIN32
  2233. MessageBoxA(NULL, help.c_str(), "Help",
  2234. MB_OK | MB_ICONASTERISK);
  2235. #else
  2236. std::cout << help
  2237. << "--version, -V: Get current version.\n";
  2238. #endif
  2239. exit(0);
  2240. } else if (arg_is(argv[i], "--version", "-V")) {
  2241. std::cout << "OBS Studio - "
  2242. << App()->GetVersionString(false) << "\n";
  2243. exit(0);
  2244. }
  2245. }
  2246. #if ALLOW_PORTABLE_MODE
  2247. if (!portable_mode) {
  2248. portable_mode =
  2249. os_file_exists(BASE_PATH "/portable_mode") ||
  2250. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2251. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2252. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2253. }
  2254. if (!opt_disable_updater) {
  2255. opt_disable_updater =
  2256. os_file_exists(BASE_PATH "/disable_updater") ||
  2257. os_file_exists(BASE_PATH "/disable_updater.txt");
  2258. }
  2259. if (!opt_disable_missing_files_check) {
  2260. opt_disable_missing_files_check =
  2261. os_file_exists(BASE_PATH
  2262. "/disable_missing_files_check") ||
  2263. os_file_exists(BASE_PATH
  2264. "/disable_missing_files_check.txt");
  2265. }
  2266. #endif
  2267. check_safe_mode_sentinel();
  2268. fstream logFile;
  2269. curl_global_init(CURL_GLOBAL_ALL);
  2270. int ret = run_program(logFile, argc, argv);
  2271. #ifdef _WIN32
  2272. if (hRtwq) {
  2273. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  2274. PFN_RtwqShutdown func =
  2275. (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  2276. func();
  2277. FreeLibrary(hRtwq);
  2278. }
  2279. log_blocked_dlls();
  2280. #endif
  2281. delete_safe_mode_sentinel();
  2282. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2283. base_set_log_handler(nullptr, nullptr);
  2284. if (restart || restart_safe) {
  2285. auto executable = arguments.takeFirst();
  2286. QProcess::startDetached(executable, arguments);
  2287. }
  2288. return ret;
  2289. }