obs-app.cpp 76 KB

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