obs-app.cpp 83 KB

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