obs-app.cpp 85 KB

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