obs-app.cpp 84 KB

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