obs-app.cpp 85 KB

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