obs-app.cpp 83 KB

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