obs-app.cpp 83 KB

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