obs-app.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <time.h>
  15. #include <stdio.h>
  16. #include <wchar.h>
  17. #include <chrono>
  18. #include <ratio>
  19. #include <string>
  20. #include <sstream>
  21. #include <mutex>
  22. #include <util/bmem.h>
  23. #include <util/dstr.hpp>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <util/cf-parser.h>
  27. #include <obs-config.h>
  28. #include <obs.hpp>
  29. #include <QFile>
  30. #include <QGuiApplication>
  31. #include <QProxyStyle>
  32. #include <QScreen>
  33. #include <QProcess>
  34. #include <QAccessible>
  35. #include "qt-wrappers.hpp"
  36. #include "obs-app.hpp"
  37. #include "log-viewer.hpp"
  38. #include "slider-ignorewheel.hpp"
  39. #include "window-basic-main.hpp"
  40. #include "window-basic-settings.hpp"
  41. #include "crash-report.hpp"
  42. #include "platform.hpp"
  43. #include <fstream>
  44. #include <curl/curl.h>
  45. #ifdef _WIN32
  46. #include <windows.h>
  47. #include <filesystem>
  48. #else
  49. #include <signal.h>
  50. #include <pthread.h>
  51. #endif
  52. #if !defined(_WIN32) && !defined(__APPLE__)
  53. #include <obs-nix-platform.h>
  54. #include <QX11Info>
  55. #ifdef ENABLE_WAYLAND
  56. #include <qpa/qplatformnativeinterface.h>
  57. #endif
  58. #endif
  59. #include <iostream>
  60. #include "ui-config.h"
  61. using namespace std;
  62. static log_handler_t def_log_handler;
  63. static string currentLogFile;
  64. static string lastLogFile;
  65. static string lastCrashLogFile;
  66. bool portable_mode = false;
  67. static bool multi = false;
  68. static bool log_verbose = false;
  69. static bool unfiltered_log = false;
  70. bool opt_start_streaming = false;
  71. bool opt_start_recording = false;
  72. bool opt_studio_mode = false;
  73. bool opt_start_replaybuffer = false;
  74. bool opt_start_virtualcam = false;
  75. bool opt_minimize_tray = false;
  76. bool opt_allow_opengl = false;
  77. bool opt_always_on_top = false;
  78. bool opt_disable_high_dpi_scaling = false;
  79. bool opt_disable_updater = false;
  80. string opt_starting_collection;
  81. string opt_starting_profile;
  82. string opt_starting_scene;
  83. bool restart = false;
  84. QPointer<OBSLogViewer> obsLogViewer;
  85. // GPU hint exports for AMD/NVIDIA laptops
  86. #ifdef _MSC_VER
  87. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  88. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  89. #endif
  90. QObject *CreateShortcutFilter()
  91. {
  92. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  93. auto mouse_event = [](QMouseEvent &event) {
  94. if (!App()->HotkeysEnabledInFocus() &&
  95. event.button() != Qt::LeftButton)
  96. return true;
  97. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  98. bool pressed = event.type() == QEvent::MouseButtonPress;
  99. switch (event.button()) {
  100. case Qt::NoButton:
  101. case Qt::LeftButton:
  102. case Qt::RightButton:
  103. case Qt::AllButtons:
  104. case Qt::MouseButtonMask:
  105. return false;
  106. case Qt::MiddleButton:
  107. hotkey.key = OBS_KEY_MOUSE3;
  108. break;
  109. #define MAP_BUTTON(i, j) \
  110. case Qt::ExtraButton##i: \
  111. hotkey.key = OBS_KEY_MOUSE##j; \
  112. break;
  113. MAP_BUTTON(1, 4);
  114. MAP_BUTTON(2, 5);
  115. MAP_BUTTON(3, 6);
  116. MAP_BUTTON(4, 7);
  117. MAP_BUTTON(5, 8);
  118. MAP_BUTTON(6, 9);
  119. MAP_BUTTON(7, 10);
  120. MAP_BUTTON(8, 11);
  121. MAP_BUTTON(9, 12);
  122. MAP_BUTTON(10, 13);
  123. MAP_BUTTON(11, 14);
  124. MAP_BUTTON(12, 15);
  125. MAP_BUTTON(13, 16);
  126. MAP_BUTTON(14, 17);
  127. MAP_BUTTON(15, 18);
  128. MAP_BUTTON(16, 19);
  129. MAP_BUTTON(17, 20);
  130. MAP_BUTTON(18, 21);
  131. MAP_BUTTON(19, 22);
  132. MAP_BUTTON(20, 23);
  133. MAP_BUTTON(21, 24);
  134. MAP_BUTTON(22, 25);
  135. MAP_BUTTON(23, 26);
  136. MAP_BUTTON(24, 27);
  137. #undef MAP_BUTTON
  138. }
  139. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  140. event.modifiers());
  141. obs_hotkey_inject_event(hotkey, pressed);
  142. return true;
  143. };
  144. auto key_event = [&](QKeyEvent *event) {
  145. if (!App()->HotkeysEnabledInFocus())
  146. return true;
  147. QDialog *dialog = qobject_cast<QDialog *>(obj);
  148. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  149. bool pressed = event->type() == QEvent::KeyPress;
  150. switch (event->key()) {
  151. case Qt::Key_Shift:
  152. case Qt::Key_Control:
  153. case Qt::Key_Alt:
  154. case Qt::Key_Meta:
  155. break;
  156. #ifdef __APPLE__
  157. case Qt::Key_CapsLock:
  158. // kVK_CapsLock == 57
  159. hotkey.key = obs_key_from_virtual_key(57);
  160. pressed = true;
  161. break;
  162. #endif
  163. case Qt::Key_Enter:
  164. case Qt::Key_Escape:
  165. case Qt::Key_Return:
  166. if (dialog && pressed)
  167. return false;
  168. /* Falls through. */
  169. default:
  170. hotkey.key = obs_key_from_virtual_key(
  171. event->nativeVirtualKey());
  172. }
  173. if (event->isAutoRepeat())
  174. return true;
  175. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  176. event->modifiers());
  177. obs_hotkey_inject_event(hotkey, pressed);
  178. return true;
  179. };
  180. switch (event->type()) {
  181. case QEvent::MouseButtonPress:
  182. case QEvent::MouseButtonRelease:
  183. return mouse_event(*static_cast<QMouseEvent *>(event));
  184. /*case QEvent::MouseButtonDblClick:
  185. case QEvent::Wheel:*/
  186. case QEvent::KeyPress:
  187. case QEvent::KeyRelease:
  188. return key_event(static_cast<QKeyEvent *>(event));
  189. default:
  190. return false;
  191. }
  192. });
  193. }
  194. string CurrentTimeString()
  195. {
  196. using namespace std::chrono;
  197. struct tm tstruct;
  198. char buf[80];
  199. auto tp = system_clock::now();
  200. auto now = system_clock::to_time_t(tp);
  201. tstruct = *localtime(&now);
  202. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  203. if (ratio_less<system_clock::period, seconds::period>::value &&
  204. written && (sizeof(buf) - written) > 5) {
  205. auto tp_secs = time_point_cast<seconds>(tp);
  206. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  207. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  208. static_cast<unsigned>(millis));
  209. }
  210. return buf;
  211. }
  212. string CurrentDateTimeString()
  213. {
  214. time_t now = time(0);
  215. struct tm tstruct;
  216. char buf[80];
  217. tstruct = *localtime(&now);
  218. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  219. return buf;
  220. }
  221. static inline void LogString(fstream &logFile, const char *timeString,
  222. char *str, int log_level)
  223. {
  224. string msg;
  225. msg += timeString;
  226. msg += str;
  227. logFile << msg << endl;
  228. if (!!obsLogViewer)
  229. QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine",
  230. Qt::QueuedConnection,
  231. Q_ARG(int, log_level),
  232. Q_ARG(QString, QString(msg.c_str())));
  233. }
  234. static inline void LogStringChunk(fstream &logFile, char *str, int log_level)
  235. {
  236. char *nextLine = str;
  237. string timeString = CurrentTimeString();
  238. timeString += ": ";
  239. while (*nextLine) {
  240. char *nextLine = strchr(str, '\n');
  241. if (!nextLine)
  242. break;
  243. if (nextLine != str && nextLine[-1] == '\r') {
  244. nextLine[-1] = 0;
  245. } else {
  246. nextLine[0] = 0;
  247. }
  248. LogString(logFile, timeString.c_str(), str, log_level);
  249. nextLine++;
  250. str = nextLine;
  251. }
  252. LogString(logFile, timeString.c_str(), str, log_level);
  253. }
  254. #define MAX_REPEATED_LINES 30
  255. #define MAX_CHAR_VARIATION (255 * 3)
  256. static inline int sum_chars(const char *str)
  257. {
  258. int val = 0;
  259. for (; *str != 0; str++)
  260. val += *str;
  261. return val;
  262. }
  263. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  264. const char *output_str)
  265. {
  266. static mutex log_mutex;
  267. static const char *last_msg_ptr = nullptr;
  268. static int last_char_sum = 0;
  269. static char cmp_str[4096];
  270. static int rep_count = 0;
  271. int new_sum = sum_chars(output_str);
  272. lock_guard<mutex> guard(log_mutex);
  273. if (unfiltered_log) {
  274. return false;
  275. }
  276. if (last_msg_ptr == msg) {
  277. int diff = std::abs(new_sum - last_char_sum);
  278. if (diff < MAX_CHAR_VARIATION) {
  279. return (rep_count++ >= MAX_REPEATED_LINES);
  280. }
  281. }
  282. if (rep_count > MAX_REPEATED_LINES) {
  283. logFile << CurrentTimeString()
  284. << ": Last log entry repeated for "
  285. << to_string(rep_count - MAX_REPEATED_LINES)
  286. << " more lines" << endl;
  287. }
  288. last_msg_ptr = msg;
  289. strcpy(cmp_str, output_str);
  290. last_char_sum = new_sum;
  291. rep_count = 0;
  292. return false;
  293. }
  294. static void do_log(int log_level, const char *msg, va_list args, void *param)
  295. {
  296. fstream &logFile = *static_cast<fstream *>(param);
  297. char str[4096];
  298. #ifndef _WIN32
  299. va_list args2;
  300. va_copy(args2, args);
  301. #endif
  302. vsnprintf(str, 4095, msg, args);
  303. #ifdef _WIN32
  304. if (IsDebuggerPresent()) {
  305. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  306. if (wNum > 1) {
  307. static wstring wide_buf;
  308. static mutex wide_mutex;
  309. lock_guard<mutex> lock(wide_mutex);
  310. wide_buf.reserve(wNum + 1);
  311. wide_buf.resize(wNum - 1);
  312. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  313. wNum);
  314. wide_buf.push_back('\n');
  315. OutputDebugStringW(wide_buf.c_str());
  316. }
  317. }
  318. #else
  319. def_log_handler(log_level, msg, args2, nullptr);
  320. va_end(args2);
  321. #endif
  322. if (log_level <= LOG_INFO || log_verbose) {
  323. if (too_many_repeated_entries(logFile, msg, str))
  324. return;
  325. LogStringChunk(logFile, str, log_level);
  326. }
  327. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  328. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  329. __debugbreak();
  330. #endif
  331. }
  332. #define DEFAULT_LANG "en-US"
  333. bool OBSApp::InitGlobalConfigDefaults()
  334. {
  335. config_set_default_string(globalConfig, "General", "Language",
  336. DEFAULT_LANG);
  337. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  338. config_set_default_int(globalConfig, "General", "InfoIncrement", -1);
  339. config_set_default_string(globalConfig, "General", "ProcessPriority",
  340. "Normal");
  341. config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
  342. true);
  343. #if _WIN32
  344. config_set_default_string(globalConfig, "Video", "Renderer",
  345. "Direct3D 11");
  346. #else
  347. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  348. #endif
  349. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  350. true);
  351. config_set_default_bool(globalConfig, "BasicWindow",
  352. "PreviewProgramMode", false);
  353. config_set_default_bool(globalConfig, "BasicWindow",
  354. "SceneDuplicationMode", true);
  355. config_set_default_bool(globalConfig, "BasicWindow", "SwapScenesMode",
  356. true);
  357. config_set_default_bool(globalConfig, "BasicWindow", "SnappingEnabled",
  358. true);
  359. config_set_default_bool(globalConfig, "BasicWindow", "ScreenSnapping",
  360. true);
  361. config_set_default_bool(globalConfig, "BasicWindow", "SourceSnapping",
  362. true);
  363. config_set_default_bool(globalConfig, "BasicWindow", "CenterSnapping",
  364. false);
  365. config_set_default_double(globalConfig, "BasicWindow", "SnapDistance",
  366. 10.0);
  367. config_set_default_bool(globalConfig, "BasicWindow",
  368. "RecordWhenStreaming", false);
  369. config_set_default_bool(globalConfig, "BasicWindow",
  370. "KeepRecordingWhenStreamStops", false);
  371. config_set_default_bool(globalConfig, "BasicWindow", "SysTrayEnabled",
  372. true);
  373. config_set_default_bool(globalConfig, "BasicWindow",
  374. "SysTrayWhenStarted", false);
  375. config_set_default_bool(globalConfig, "BasicWindow", "SaveProjectors",
  376. false);
  377. config_set_default_bool(globalConfig, "BasicWindow", "ShowTransitions",
  378. true);
  379. config_set_default_bool(globalConfig, "BasicWindow",
  380. "ShowListboxToolbars", true);
  381. config_set_default_bool(globalConfig, "BasicWindow", "ShowStatusBar",
  382. true);
  383. config_set_default_bool(globalConfig, "BasicWindow", "ShowSourceIcons",
  384. true);
  385. config_set_default_bool(globalConfig, "BasicWindow",
  386. "ShowContextToolbars", true);
  387. config_set_default_bool(globalConfig, "BasicWindow", "StudioModeLabels",
  388. true);
  389. if (!config_get_bool(globalConfig, "General", "Pre21Defaults")) {
  390. config_set_default_string(globalConfig, "General",
  391. "CurrentTheme", DEFAULT_THEME);
  392. }
  393. config_set_default_string(globalConfig, "General", "HotkeyFocusType",
  394. "NeverDisableHotkeys");
  395. config_set_default_bool(globalConfig, "BasicWindow",
  396. "VerticalVolControl", false);
  397. config_set_default_bool(globalConfig, "BasicWindow",
  398. "MultiviewMouseSwitch", true);
  399. config_set_default_bool(globalConfig, "BasicWindow",
  400. "MultiviewDrawNames", true);
  401. config_set_default_bool(globalConfig, "BasicWindow",
  402. "MultiviewDrawAreas", true);
  403. #ifdef _WIN32
  404. uint32_t winver = GetWindowsVersion();
  405. config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
  406. true);
  407. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  408. winver > 0x601);
  409. #endif
  410. #ifdef __APPLE__
  411. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  412. true);
  413. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  414. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  415. true);
  416. #endif
  417. config_set_default_bool(globalConfig, "BasicWindow",
  418. "MediaControlsCountdownTimer", true);
  419. return true;
  420. }
  421. static bool do_mkdir(const char *path)
  422. {
  423. if (os_mkdirs(path) == MKDIR_ERROR) {
  424. OBSErrorBox(NULL, "Failed to create directory %s", path);
  425. return false;
  426. }
  427. return true;
  428. }
  429. static bool MakeUserDirs()
  430. {
  431. char path[512];
  432. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  433. return false;
  434. if (!do_mkdir(path))
  435. return false;
  436. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  437. return false;
  438. if (!do_mkdir(path))
  439. return false;
  440. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  441. return false;
  442. if (!do_mkdir(path))
  443. return false;
  444. #ifdef _WIN32
  445. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  446. return false;
  447. if (!do_mkdir(path))
  448. return false;
  449. if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  450. return false;
  451. if (!do_mkdir(path))
  452. return false;
  453. #endif
  454. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  455. return false;
  456. if (!do_mkdir(path))
  457. return false;
  458. return true;
  459. }
  460. static bool MakeUserProfileDirs()
  461. {
  462. char path[512];
  463. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  464. return false;
  465. if (!do_mkdir(path))
  466. return false;
  467. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  468. return false;
  469. if (!do_mkdir(path))
  470. return false;
  471. return true;
  472. }
  473. static string GetProfileDirFromName(const char *name)
  474. {
  475. string outputPath;
  476. os_glob_t *glob;
  477. char path[512];
  478. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  479. return outputPath;
  480. strcat(path, "/*");
  481. if (os_glob(path, 0, &glob) != 0)
  482. return outputPath;
  483. for (size_t i = 0; i < glob->gl_pathc; i++) {
  484. struct os_globent ent = glob->gl_pathv[i];
  485. if (!ent.directory)
  486. continue;
  487. strcpy(path, ent.path);
  488. strcat(path, "/basic.ini");
  489. ConfigFile config;
  490. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  491. continue;
  492. const char *curName =
  493. config_get_string(config, "General", "Name");
  494. if (astrcmpi(curName, name) == 0) {
  495. outputPath = ent.path;
  496. break;
  497. }
  498. }
  499. os_globfree(glob);
  500. if (!outputPath.empty()) {
  501. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  502. const char *start = strrchr(outputPath.c_str(), '/');
  503. if (start)
  504. outputPath.erase(0, start - outputPath.c_str() + 1);
  505. }
  506. return outputPath;
  507. }
  508. static string GetSceneCollectionFileFromName(const char *name)
  509. {
  510. string outputPath;
  511. os_glob_t *glob;
  512. char path[512];
  513. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  514. return outputPath;
  515. strcat(path, "/*.json");
  516. if (os_glob(path, 0, &glob) != 0)
  517. return outputPath;
  518. for (size_t i = 0; i < glob->gl_pathc; i++) {
  519. struct os_globent ent = glob->gl_pathv[i];
  520. if (ent.directory)
  521. continue;
  522. obs_data_t *data =
  523. obs_data_create_from_json_file_safe(ent.path, "bak");
  524. const char *curName = obs_data_get_string(data, "name");
  525. if (astrcmpi(name, curName) == 0) {
  526. outputPath = ent.path;
  527. obs_data_release(data);
  528. break;
  529. }
  530. obs_data_release(data);
  531. }
  532. os_globfree(glob);
  533. if (!outputPath.empty()) {
  534. outputPath.resize(outputPath.size() - 5);
  535. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  536. const char *start = strrchr(outputPath.c_str(), '/');
  537. if (start)
  538. outputPath.erase(0, start - outputPath.c_str() + 1);
  539. }
  540. return outputPath;
  541. }
  542. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  543. {
  544. if (!layout)
  545. return false;
  546. if (astrcmpi(layout, "horizontaltop") == 0) {
  547. config_set_int(
  548. globalConfig, "BasicWindow", "MultiviewLayout",
  549. static_cast<int>(
  550. MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  551. return true;
  552. }
  553. if (astrcmpi(layout, "horizontalbottom") == 0) {
  554. config_set_int(
  555. globalConfig, "BasicWindow", "MultiviewLayout",
  556. static_cast<int>(
  557. MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  558. return true;
  559. }
  560. if (astrcmpi(layout, "verticalleft") == 0) {
  561. config_set_int(
  562. globalConfig, "BasicWindow", "MultiviewLayout",
  563. static_cast<int>(
  564. MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  565. return true;
  566. }
  567. if (astrcmpi(layout, "verticalright") == 0) {
  568. config_set_int(
  569. globalConfig, "BasicWindow", "MultiviewLayout",
  570. static_cast<int>(
  571. MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  572. return true;
  573. }
  574. return false;
  575. }
  576. bool OBSApp::InitGlobalConfig()
  577. {
  578. char path[512];
  579. bool changed = false;
  580. int len = GetConfigPath(path, sizeof(path), "obs-studio/global.ini");
  581. if (len <= 0) {
  582. return false;
  583. }
  584. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  585. if (errorcode != CONFIG_SUCCESS) {
  586. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  587. return false;
  588. }
  589. if (!opt_starting_collection.empty()) {
  590. string path = GetSceneCollectionFileFromName(
  591. opt_starting_collection.c_str());
  592. if (!path.empty()) {
  593. config_set_string(globalConfig, "Basic",
  594. "SceneCollection",
  595. opt_starting_collection.c_str());
  596. config_set_string(globalConfig, "Basic",
  597. "SceneCollectionFile", path.c_str());
  598. changed = true;
  599. }
  600. }
  601. if (!opt_starting_profile.empty()) {
  602. string path =
  603. GetProfileDirFromName(opt_starting_profile.c_str());
  604. if (!path.empty()) {
  605. config_set_string(globalConfig, "Basic", "Profile",
  606. opt_starting_profile.c_str());
  607. config_set_string(globalConfig, "Basic", "ProfileDir",
  608. path.c_str());
  609. changed = true;
  610. }
  611. }
  612. uint32_t lastVersion =
  613. config_get_int(globalConfig, "General", "LastVersion");
  614. if (!config_has_user_value(globalConfig, "General", "Pre19Defaults")) {
  615. bool useOldDefaults = lastVersion &&
  616. lastVersion <
  617. MAKE_SEMANTIC_VERSION(19, 0, 0);
  618. config_set_bool(globalConfig, "General", "Pre19Defaults",
  619. useOldDefaults);
  620. changed = true;
  621. }
  622. if (!config_has_user_value(globalConfig, "General", "Pre21Defaults")) {
  623. bool useOldDefaults = lastVersion &&
  624. lastVersion <
  625. MAKE_SEMANTIC_VERSION(21, 0, 0);
  626. config_set_bool(globalConfig, "General", "Pre21Defaults",
  627. useOldDefaults);
  628. changed = true;
  629. }
  630. if (!config_has_user_value(globalConfig, "General", "Pre23Defaults")) {
  631. bool useOldDefaults = lastVersion &&
  632. lastVersion <
  633. MAKE_SEMANTIC_VERSION(23, 0, 0);
  634. config_set_bool(globalConfig, "General", "Pre23Defaults",
  635. useOldDefaults);
  636. changed = true;
  637. }
  638. #define PRE_24_1_DEFS "Pre24.1Defaults"
  639. if (!config_has_user_value(globalConfig, "General", PRE_24_1_DEFS)) {
  640. bool useOldDefaults = lastVersion &&
  641. lastVersion <
  642. MAKE_SEMANTIC_VERSION(24, 1, 0);
  643. config_set_bool(globalConfig, "General", PRE_24_1_DEFS,
  644. useOldDefaults);
  645. changed = true;
  646. }
  647. #undef PRE_24_1_DEFS
  648. if (config_has_user_value(globalConfig, "BasicWindow",
  649. "MultiviewLayout")) {
  650. const char *layout = config_get_string(
  651. globalConfig, "BasicWindow", "MultiviewLayout");
  652. changed |= UpdatePre22MultiviewLayout(layout);
  653. }
  654. if (lastVersion && lastVersion < MAKE_SEMANTIC_VERSION(24, 0, 0)) {
  655. bool disableHotkeysInFocus = config_get_bool(
  656. globalConfig, "General", "DisableHotkeysInFocus");
  657. if (disableHotkeysInFocus)
  658. config_set_string(globalConfig, "General",
  659. "HotkeyFocusType",
  660. "DisableHotkeysInFocus");
  661. changed = true;
  662. }
  663. if (changed)
  664. config_save_safe(globalConfig, "tmp", nullptr);
  665. return InitGlobalConfigDefaults();
  666. }
  667. bool OBSApp::InitLocale()
  668. {
  669. ProfileScope("OBSApp::InitLocale");
  670. const char *lang =
  671. config_get_string(globalConfig, "General", "Language");
  672. locale = lang;
  673. string englishPath;
  674. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  675. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  676. return false;
  677. }
  678. textLookup = text_lookup_create(englishPath.c_str());
  679. if (!textLookup) {
  680. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  681. englishPath.c_str());
  682. return false;
  683. }
  684. bool userLocale =
  685. config_has_user_value(globalConfig, "General", "Language");
  686. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  687. if (userLocale && defaultLang)
  688. return true;
  689. if (!userLocale && defaultLang) {
  690. for (auto &locale_ : GetPreferredLocales()) {
  691. if (locale_ == lang)
  692. return true;
  693. stringstream file;
  694. file << "locale/" << locale_ << ".ini";
  695. string path;
  696. if (!GetDataFilePath(file.str().c_str(), path))
  697. continue;
  698. if (!text_lookup_add(textLookup, path.c_str()))
  699. continue;
  700. blog(LOG_INFO, "Using preferred locale '%s'",
  701. locale_.c_str());
  702. locale = locale_;
  703. return true;
  704. }
  705. return true;
  706. }
  707. stringstream file;
  708. file << "locale/" << lang << ".ini";
  709. string path;
  710. if (GetDataFilePath(file.str().c_str(), path)) {
  711. if (!text_lookup_add(textLookup, path.c_str()))
  712. blog(LOG_ERROR, "Failed to add locale file '%s'",
  713. path.c_str());
  714. } else {
  715. blog(LOG_ERROR, "Could not find locale file '%s'",
  716. file.str().c_str());
  717. }
  718. return true;
  719. }
  720. void OBSApp::AddExtraThemeColor(QPalette &pal, int group, const char *name,
  721. uint32_t color)
  722. {
  723. std::function<void(QPalette::ColorGroup)> func;
  724. #define DEF_PALETTE_ASSIGN(name) \
  725. do { \
  726. func = [&](QPalette::ColorGroup group) { \
  727. pal.setColor(group, QPalette::name, \
  728. QColor::fromRgb(color)); \
  729. }; \
  730. } while (false)
  731. if (astrcmpi(name, "alternateBase") == 0) {
  732. DEF_PALETTE_ASSIGN(AlternateBase);
  733. } else if (astrcmpi(name, "base") == 0) {
  734. DEF_PALETTE_ASSIGN(Base);
  735. } else if (astrcmpi(name, "brightText") == 0) {
  736. DEF_PALETTE_ASSIGN(BrightText);
  737. } else if (astrcmpi(name, "button") == 0) {
  738. DEF_PALETTE_ASSIGN(Button);
  739. } else if (astrcmpi(name, "buttonText") == 0) {
  740. DEF_PALETTE_ASSIGN(ButtonText);
  741. } else if (astrcmpi(name, "brightText") == 0) {
  742. DEF_PALETTE_ASSIGN(BrightText);
  743. } else if (astrcmpi(name, "dark") == 0) {
  744. DEF_PALETTE_ASSIGN(Dark);
  745. } else if (astrcmpi(name, "highlight") == 0) {
  746. DEF_PALETTE_ASSIGN(Highlight);
  747. } else if (astrcmpi(name, "highlightedText") == 0) {
  748. DEF_PALETTE_ASSIGN(HighlightedText);
  749. } else if (astrcmpi(name, "light") == 0) {
  750. DEF_PALETTE_ASSIGN(Light);
  751. } else if (astrcmpi(name, "link") == 0) {
  752. DEF_PALETTE_ASSIGN(Link);
  753. } else if (astrcmpi(name, "linkVisited") == 0) {
  754. DEF_PALETTE_ASSIGN(LinkVisited);
  755. } else if (astrcmpi(name, "mid") == 0) {
  756. DEF_PALETTE_ASSIGN(Mid);
  757. } else if (astrcmpi(name, "midlight") == 0) {
  758. DEF_PALETTE_ASSIGN(Midlight);
  759. } else if (astrcmpi(name, "shadow") == 0) {
  760. DEF_PALETTE_ASSIGN(Shadow);
  761. } else if (astrcmpi(name, "text") == 0 ||
  762. astrcmpi(name, "foreground") == 0) {
  763. DEF_PALETTE_ASSIGN(Text);
  764. } else if (astrcmpi(name, "toolTipBase") == 0) {
  765. DEF_PALETTE_ASSIGN(ToolTipBase);
  766. } else if (astrcmpi(name, "toolTipText") == 0) {
  767. DEF_PALETTE_ASSIGN(ToolTipText);
  768. } else if (astrcmpi(name, "windowText") == 0) {
  769. DEF_PALETTE_ASSIGN(WindowText);
  770. } else if (astrcmpi(name, "window") == 0 ||
  771. astrcmpi(name, "background") == 0) {
  772. DEF_PALETTE_ASSIGN(Window);
  773. } else {
  774. return;
  775. }
  776. #undef DEF_PALETTE_ASSIGN
  777. switch (group) {
  778. case QPalette::Disabled:
  779. case QPalette::Active:
  780. case QPalette::Inactive:
  781. func((QPalette::ColorGroup)group);
  782. break;
  783. default:
  784. func((QPalette::ColorGroup)QPalette::Disabled);
  785. func((QPalette::ColorGroup)QPalette::Active);
  786. func((QPalette::ColorGroup)QPalette::Inactive);
  787. }
  788. }
  789. struct CFParser {
  790. cf_parser cfp = {};
  791. inline ~CFParser() { cf_parser_free(&cfp); }
  792. inline operator cf_parser *() { return &cfp; }
  793. inline cf_parser *operator->() { return &cfp; }
  794. };
  795. void OBSApp::ParseExtraThemeData(const char *path)
  796. {
  797. BPtr<char> data = os_quick_read_utf8_file(path);
  798. QPalette pal = palette();
  799. CFParser cfp;
  800. int ret;
  801. cf_parser_parse(cfp, data, path);
  802. while (cf_go_to_token(cfp, "OBSTheme", nullptr)) {
  803. if (!cf_next_token(cfp))
  804. return;
  805. int group = -1;
  806. if (cf_token_is(cfp, ":")) {
  807. ret = cf_next_token_should_be(cfp, ":", nullptr,
  808. nullptr);
  809. if (ret != PARSE_SUCCESS)
  810. continue;
  811. if (!cf_next_token(cfp))
  812. return;
  813. if (cf_token_is(cfp, "disabled")) {
  814. group = QPalette::Disabled;
  815. } else if (cf_token_is(cfp, "active")) {
  816. group = QPalette::Active;
  817. } else if (cf_token_is(cfp, "inactive")) {
  818. group = QPalette::Inactive;
  819. } else {
  820. continue;
  821. }
  822. if (!cf_next_token(cfp))
  823. return;
  824. }
  825. if (!cf_token_is(cfp, "{"))
  826. continue;
  827. for (;;) {
  828. if (!cf_next_token(cfp))
  829. return;
  830. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name",
  831. nullptr);
  832. if (ret != PARSE_SUCCESS)
  833. break;
  834. DStr name;
  835. dstr_copy_strref(name, &cfp->cur_token->str);
  836. ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
  837. if (ret != PARSE_SUCCESS)
  838. continue;
  839. if (!cf_next_token(cfp))
  840. return;
  841. const char *array;
  842. uint32_t color = 0;
  843. if (cf_token_is(cfp, "#")) {
  844. array = cfp->cur_token->str.array;
  845. color = strtol(array + 1, nullptr, 16);
  846. } else if (cf_token_is(cfp, "rgb")) {
  847. ret = cf_next_token_should_be(cfp, "(", ";",
  848. nullptr);
  849. if (ret != PARSE_SUCCESS)
  850. continue;
  851. if (!cf_next_token(cfp))
  852. return;
  853. array = cfp->cur_token->str.array;
  854. color |= strtol(array, nullptr, 10) << 16;
  855. ret = cf_next_token_should_be(cfp, ",", ";",
  856. nullptr);
  857. if (ret != PARSE_SUCCESS)
  858. continue;
  859. if (!cf_next_token(cfp))
  860. return;
  861. array = cfp->cur_token->str.array;
  862. color |= strtol(array, nullptr, 10) << 8;
  863. ret = cf_next_token_should_be(cfp, ",", ";",
  864. nullptr);
  865. if (ret != PARSE_SUCCESS)
  866. continue;
  867. if (!cf_next_token(cfp))
  868. return;
  869. array = cfp->cur_token->str.array;
  870. color |= strtol(array, nullptr, 10);
  871. } else if (cf_token_is(cfp, "white")) {
  872. color = 0xFFFFFF;
  873. } else if (cf_token_is(cfp, "black")) {
  874. color = 0;
  875. }
  876. if (!cf_go_to_token(cfp, ";", nullptr))
  877. return;
  878. AddExtraThemeColor(pal, group, name->array, color);
  879. }
  880. ret = cf_token_should_be(cfp, "}", "}", nullptr);
  881. if (ret != PARSE_SUCCESS)
  882. continue;
  883. }
  884. setPalette(pal);
  885. }
  886. bool OBSApp::SetTheme(std::string name, std::string path)
  887. {
  888. theme = name;
  889. /* Check user dir first, then preinstalled themes. */
  890. if (path == "") {
  891. char userDir[512];
  892. name = "themes/" + name + ".qss";
  893. string temp = "obs-studio/" + name;
  894. int ret = GetConfigPath(userDir, sizeof(userDir), temp.c_str());
  895. if (ret > 0 && QFile::exists(userDir)) {
  896. path = string(userDir);
  897. } else if (!GetDataFilePath(name.c_str(), path)) {
  898. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  899. return false;
  900. }
  901. }
  902. QString mpath = QString("file:///") + path.c_str();
  903. setPalette(defaultPalette);
  904. setStyleSheet(mpath);
  905. ParseExtraThemeData(path.c_str());
  906. emit StyleChanged();
  907. return true;
  908. }
  909. bool OBSApp::InitTheme()
  910. {
  911. defaultPalette = palette();
  912. const char *themeName =
  913. config_get_string(globalConfig, "General", "CurrentTheme2");
  914. if (!themeName)
  915. /* Use deprecated "CurrentTheme" value if available */
  916. themeName = config_get_string(globalConfig, "General",
  917. "CurrentTheme");
  918. if (!themeName)
  919. /* Use deprecated "Theme" value if available */
  920. themeName = config_get_string(globalConfig, "General", "Theme");
  921. if (!themeName)
  922. themeName = DEFAULT_THEME;
  923. if (!themeName)
  924. themeName = "Dark";
  925. if (strcmp(themeName, "Default") == 0)
  926. themeName = "System";
  927. if (strcmp(themeName, "System") != 0 && SetTheme(themeName))
  928. return true;
  929. return SetTheme("System");
  930. }
  931. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  932. : QApplication(argc, argv), profilerNameStore(store)
  933. {
  934. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  935. #ifdef __APPLE__
  936. setWindowIcon(
  937. QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png")));
  938. #else
  939. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  940. #endif
  941. }
  942. OBSApp::~OBSApp()
  943. {
  944. #ifdef _WIN32
  945. bool disableAudioDucking =
  946. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  947. if (disableAudioDucking)
  948. DisableAudioDucking(false);
  949. #endif
  950. #ifdef __APPLE__
  951. bool vsyncDiabled =
  952. config_get_bool(globalConfig, "Video", "DisableOSXVSync");
  953. bool resetVSync =
  954. config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
  955. if (vsyncDiabled && resetVSync)
  956. EnableOSXVSync(true);
  957. #endif
  958. os_inhibit_sleep_set_active(sleepInhibitor, false);
  959. os_inhibit_sleep_destroy(sleepInhibitor);
  960. if (libobs_initialized)
  961. obs_shutdown();
  962. }
  963. static void move_basic_to_profiles(void)
  964. {
  965. char path[512];
  966. char new_path[512];
  967. os_glob_t *glob;
  968. /* if not first time use */
  969. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  970. return;
  971. if (!os_file_exists(path))
  972. return;
  973. /* if the profiles directory doesn't already exist */
  974. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  975. return;
  976. if (os_file_exists(new_path))
  977. return;
  978. if (os_mkdir(new_path) == MKDIR_ERROR)
  979. return;
  980. strcat(new_path, "/");
  981. strcat(new_path, Str("Untitled"));
  982. if (os_mkdir(new_path) == MKDIR_ERROR)
  983. return;
  984. strcat(path, "/*.*");
  985. if (os_glob(path, 0, &glob) != 0)
  986. return;
  987. strcpy(path, new_path);
  988. for (size_t i = 0; i < glob->gl_pathc; i++) {
  989. struct os_globent ent = glob->gl_pathv[i];
  990. char *file;
  991. if (ent.directory)
  992. continue;
  993. file = strrchr(ent.path, '/');
  994. if (!file++)
  995. continue;
  996. if (astrcmpi(file, "scenes.json") == 0)
  997. continue;
  998. strcpy(new_path, path);
  999. strcat(new_path, "/");
  1000. strcat(new_path, file);
  1001. os_rename(ent.path, new_path);
  1002. }
  1003. os_globfree(glob);
  1004. }
  1005. static void move_basic_to_scene_collections(void)
  1006. {
  1007. char path[512];
  1008. char new_path[512];
  1009. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  1010. return;
  1011. if (!os_file_exists(path))
  1012. return;
  1013. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  1014. return;
  1015. if (os_file_exists(new_path))
  1016. return;
  1017. if (os_mkdir(new_path) == MKDIR_ERROR)
  1018. return;
  1019. strcat(path, "/scenes.json");
  1020. strcat(new_path, "/");
  1021. strcat(new_path, Str("Untitled"));
  1022. strcat(new_path, ".json");
  1023. os_rename(path, new_path);
  1024. }
  1025. void OBSApp::AppInit()
  1026. {
  1027. ProfileScope("OBSApp::AppInit");
  1028. if (!InitApplicationBundle())
  1029. throw "Failed to initialize application bundle";
  1030. if (!MakeUserDirs())
  1031. throw "Failed to create required user directories";
  1032. if (!InitGlobalConfig())
  1033. throw "Failed to initialize global config";
  1034. if (!InitLocale())
  1035. throw "Failed to load locale";
  1036. if (!InitTheme())
  1037. throw "Failed to load theme";
  1038. config_set_default_string(globalConfig, "Basic", "Profile",
  1039. Str("Untitled"));
  1040. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  1041. Str("Untitled"));
  1042. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  1043. Str("Untitled"));
  1044. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  1045. Str("Untitled"));
  1046. config_set_default_bool(globalConfig, "Basic", "ConfigOnNewProfile",
  1047. true);
  1048. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  1049. config_set_string(globalConfig, "Basic", "Profile",
  1050. Str("Untitled"));
  1051. config_set_string(globalConfig, "Basic", "ProfileDir",
  1052. Str("Untitled"));
  1053. }
  1054. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  1055. config_set_string(globalConfig, "Basic", "SceneCollection",
  1056. Str("Untitled"));
  1057. config_set_string(globalConfig, "Basic", "SceneCollectionFile",
  1058. Str("Untitled"));
  1059. }
  1060. #ifdef _WIN32
  1061. bool disableAudioDucking =
  1062. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  1063. if (disableAudioDucking)
  1064. DisableAudioDucking(true);
  1065. #endif
  1066. #ifdef __APPLE__
  1067. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  1068. EnableOSXVSync(false);
  1069. #endif
  1070. UpdateHotkeyFocusSetting(false);
  1071. move_basic_to_profiles();
  1072. move_basic_to_scene_collections();
  1073. if (!MakeUserProfileDirs())
  1074. throw "Failed to create profile directories";
  1075. }
  1076. const char *OBSApp::GetRenderModule() const
  1077. {
  1078. const char *renderer =
  1079. config_get_string(globalConfig, "Video", "Renderer");
  1080. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1081. }
  1082. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1083. {
  1084. char path[512];
  1085. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1086. return false;
  1087. return obs_startup(locale, path, store);
  1088. }
  1089. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1090. {
  1091. obs_hotkey_enable_background_press(
  1092. (inFocus && enableHotkeysInFocus) ||
  1093. (!inFocus && enableHotkeysOutOfFocus));
  1094. }
  1095. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1096. {
  1097. enableHotkeysInFocus = true;
  1098. enableHotkeysOutOfFocus = true;
  1099. const char *hotkeyFocusType =
  1100. config_get_string(globalConfig, "General", "HotkeyFocusType");
  1101. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1102. enableHotkeysInFocus = false;
  1103. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1104. enableHotkeysOutOfFocus = false;
  1105. }
  1106. if (resetState)
  1107. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1108. }
  1109. void OBSApp::DisableHotkeys()
  1110. {
  1111. enableHotkeysInFocus = false;
  1112. enableHotkeysOutOfFocus = false;
  1113. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1114. }
  1115. Q_DECLARE_METATYPE(VoidFunc)
  1116. void OBSApp::Exec(VoidFunc func)
  1117. {
  1118. func();
  1119. }
  1120. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  1121. {
  1122. auto doTask = [=]() {
  1123. /* to get clang-format to behave */
  1124. task(param);
  1125. };
  1126. QMetaObject::invokeMethod(App(), "Exec",
  1127. wait ? WaitConnection() : Qt::AutoConnection,
  1128. Q_ARG(VoidFunc, doTask));
  1129. }
  1130. bool OBSApp::OBSInit()
  1131. {
  1132. ProfileScope("OBSApp::OBSInit");
  1133. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  1134. setAttribute(Qt::AA_UseHighDpiPixmaps);
  1135. #endif
  1136. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1137. qRegisterMetaType<VoidFunc>();
  1138. #if !defined(_WIN32) && !defined(__APPLE__)
  1139. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_GLX);
  1140. if (QApplication::platformName() == "xcb") {
  1141. if (getenv("OBS_USE_EGL")) {
  1142. blog(LOG_INFO, "Using EGL/X11");
  1143. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  1144. }
  1145. obs_set_nix_platform_display(QX11Info::display());
  1146. }
  1147. #ifdef ENABLE_WAYLAND
  1148. if (QApplication::platformName().contains("wayland")) {
  1149. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  1150. QPlatformNativeInterface *native =
  1151. QGuiApplication::platformNativeInterface();
  1152. obs_set_nix_platform_display(
  1153. native->nativeResourceForIntegration("display"));
  1154. blog(LOG_INFO, "Platform: Wayland");
  1155. }
  1156. #endif
  1157. #endif
  1158. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1159. return false;
  1160. libobs_initialized = true;
  1161. obs_set_ui_task_handler(ui_task_handler);
  1162. #if defined(_WIN32) || defined(__APPLE__)
  1163. bool browserHWAccel =
  1164. config_get_bool(globalConfig, "General", "BrowserHWAccel");
  1165. obs_data_t *settings = obs_data_create();
  1166. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1167. obs_apply_private_data(settings);
  1168. obs_data_release(settings);
  1169. blog(LOG_INFO, "Current Date/Time: %s",
  1170. CurrentDateTimeString().c_str());
  1171. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1172. browserHWAccel ? "true" : "false");
  1173. #endif
  1174. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1175. setQuitOnLastWindowClosed(false);
  1176. mainWindow = new OBSBasic();
  1177. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1178. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1179. mainWindow->OBSInit();
  1180. connect(this, &QGuiApplication::applicationStateChanged,
  1181. [this](Qt::ApplicationState state) {
  1182. ResetHotkeyState(state == Qt::ApplicationActive);
  1183. });
  1184. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1185. return true;
  1186. }
  1187. string OBSApp::GetVersionString() const
  1188. {
  1189. stringstream ver;
  1190. #ifdef HAVE_OBSCONFIG_H
  1191. ver << OBS_VERSION;
  1192. #else
  1193. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1194. << LIBOBS_API_PATCH_VER;
  1195. #endif
  1196. ver << " (";
  1197. #ifdef _WIN32
  1198. if (sizeof(void *) == 8)
  1199. ver << "64-bit, ";
  1200. else
  1201. ver << "32-bit, ";
  1202. ver << "windows)";
  1203. #elif __APPLE__
  1204. ver << "mac)";
  1205. #elif __OpenBSD__
  1206. ver << "openbsd)";
  1207. #elif __FreeBSD__
  1208. ver << "freebsd)";
  1209. #else /* assume linux for the time being */
  1210. ver << "linux)";
  1211. #endif
  1212. return ver.str();
  1213. }
  1214. bool OBSApp::IsPortableMode()
  1215. {
  1216. return portable_mode;
  1217. }
  1218. bool OBSApp::IsUpdaterDisabled()
  1219. {
  1220. return opt_disable_updater;
  1221. }
  1222. #ifdef __APPLE__
  1223. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1224. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1225. #elif _WIN32
  1226. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1227. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1228. #else
  1229. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1230. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1231. #endif
  1232. const char *OBSApp::InputAudioSource() const
  1233. {
  1234. return INPUT_AUDIO_SOURCE;
  1235. }
  1236. const char *OBSApp::OutputAudioSource() const
  1237. {
  1238. return OUTPUT_AUDIO_SOURCE;
  1239. }
  1240. const char *OBSApp::GetLastLog() const
  1241. {
  1242. return lastLogFile.c_str();
  1243. }
  1244. const char *OBSApp::GetCurrentLog() const
  1245. {
  1246. return currentLogFile.c_str();
  1247. }
  1248. const char *OBSApp::GetLastCrashLog() const
  1249. {
  1250. return lastCrashLogFile.c_str();
  1251. }
  1252. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1253. {
  1254. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1255. if (cb(lookupVal, out))
  1256. return true;
  1257. }
  1258. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1259. }
  1260. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1261. const char *disambiguation, int n) const
  1262. {
  1263. const char *out = nullptr;
  1264. if (!App()->TranslateString(sourceText, &out))
  1265. return QString(sourceText);
  1266. UNUSED_PARAMETER(context);
  1267. UNUSED_PARAMETER(disambiguation);
  1268. UNUSED_PARAMETER(n);
  1269. return QT_UTF8(out);
  1270. }
  1271. static bool get_token(lexer *lex, string &str, base_token_type type)
  1272. {
  1273. base_token token;
  1274. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1275. return false;
  1276. if (token.type != type)
  1277. return false;
  1278. str.assign(token.text.array, token.text.len);
  1279. return true;
  1280. }
  1281. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1282. {
  1283. base_token token;
  1284. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1285. return false;
  1286. if (token.type != type)
  1287. return false;
  1288. return strref_cmp(&token.text, str) == 0;
  1289. }
  1290. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1291. {
  1292. BaseLexer lex;
  1293. string year, month, day, hour, minute, second;
  1294. lexer_start(lex, name);
  1295. if (has_prefix) {
  1296. string temp;
  1297. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1298. return 0;
  1299. }
  1300. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1301. return 0;
  1302. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1303. return 0;
  1304. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1305. return 0;
  1306. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1307. return 0;
  1308. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1309. return 0;
  1310. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1311. return 0;
  1312. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1313. return 0;
  1314. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1315. return 0;
  1316. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1317. return 0;
  1318. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1319. return 0;
  1320. stringstream timestring;
  1321. timestring << year << month << day << hour << minute << second;
  1322. return std::stoull(timestring.str());
  1323. }
  1324. static void delete_oldest_file(bool has_prefix, const char *location)
  1325. {
  1326. BPtr<char> logDir(GetConfigPathPtr(location));
  1327. string oldestLog;
  1328. uint64_t oldest_ts = (uint64_t)-1;
  1329. struct os_dirent *entry;
  1330. unsigned int maxLogs = (unsigned int)config_get_uint(
  1331. App()->GlobalConfig(), "General", "MaxLogs");
  1332. os_dir_t *dir = os_opendir(logDir);
  1333. if (dir) {
  1334. unsigned int count = 0;
  1335. while ((entry = os_readdir(dir)) != NULL) {
  1336. if (entry->directory || *entry->d_name == '.')
  1337. continue;
  1338. uint64_t ts =
  1339. convert_log_name(has_prefix, entry->d_name);
  1340. if (ts) {
  1341. if (ts < oldest_ts) {
  1342. oldestLog = entry->d_name;
  1343. oldest_ts = ts;
  1344. }
  1345. count++;
  1346. }
  1347. }
  1348. os_closedir(dir);
  1349. if (count > maxLogs) {
  1350. stringstream delPath;
  1351. delPath << logDir << "/" << oldestLog;
  1352. os_unlink(delPath.str().c_str());
  1353. }
  1354. }
  1355. }
  1356. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1357. std::string &last)
  1358. {
  1359. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1360. struct os_dirent *entry;
  1361. os_dir_t *dir = os_opendir(logDir);
  1362. uint64_t highest_ts = 0;
  1363. if (dir) {
  1364. while ((entry = os_readdir(dir)) != NULL) {
  1365. if (entry->directory || *entry->d_name == '.')
  1366. continue;
  1367. uint64_t ts =
  1368. convert_log_name(has_prefix, entry->d_name);
  1369. if (ts > highest_ts) {
  1370. last = entry->d_name;
  1371. highest_ts = ts;
  1372. }
  1373. }
  1374. os_closedir(dir);
  1375. }
  1376. }
  1377. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1378. {
  1379. time_t now = time(0);
  1380. char file[256] = {};
  1381. struct tm *cur_time;
  1382. cur_time = localtime(&now);
  1383. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1384. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1385. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1386. cur_time->tm_min, cur_time->tm_sec, extension);
  1387. return string(file);
  1388. }
  1389. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1390. const char *format)
  1391. {
  1392. BPtr<char> filename =
  1393. os_generate_formatted_filename(extension, !noSpace, format);
  1394. return string(filename);
  1395. }
  1396. static void FindBestFilename(string &strPath, bool noSpace)
  1397. {
  1398. int num = 2;
  1399. if (!os_file_exists(strPath.c_str()))
  1400. return;
  1401. const char *ext = strrchr(strPath.c_str(), '.');
  1402. if (!ext)
  1403. return;
  1404. int extStart = int(ext - strPath.c_str());
  1405. for (;;) {
  1406. string testPath = strPath;
  1407. string numStr;
  1408. numStr = noSpace ? "_" : " (";
  1409. numStr += to_string(num++);
  1410. if (!noSpace)
  1411. numStr += ")";
  1412. testPath.insert(extStart, numStr);
  1413. if (!os_file_exists(testPath.c_str())) {
  1414. strPath = testPath;
  1415. break;
  1416. }
  1417. }
  1418. }
  1419. static void ensure_directory_exists(string &path)
  1420. {
  1421. replace(path.begin(), path.end(), '\\', '/');
  1422. size_t last = path.rfind('/');
  1423. if (last == string::npos)
  1424. return;
  1425. string directory = path.substr(0, last);
  1426. os_mkdirs(directory.c_str());
  1427. }
  1428. static void remove_reserved_file_characters(string &s)
  1429. {
  1430. replace(s.begin(), s.end(), '\\', '/');
  1431. replace(s.begin(), s.end(), '*', '_');
  1432. replace(s.begin(), s.end(), '?', '_');
  1433. replace(s.begin(), s.end(), '"', '_');
  1434. replace(s.begin(), s.end(), '|', '_');
  1435. replace(s.begin(), s.end(), ':', '_');
  1436. replace(s.begin(), s.end(), '>', '_');
  1437. replace(s.begin(), s.end(), '<', '_');
  1438. }
  1439. string GetFormatString(const char *format, const char *prefix,
  1440. const char *suffix)
  1441. {
  1442. string f;
  1443. if (prefix && *prefix) {
  1444. f += prefix;
  1445. if (f.back() != ' ')
  1446. f += " ";
  1447. }
  1448. f += format;
  1449. if (suffix && *suffix) {
  1450. if (*suffix != ' ')
  1451. f += " ";
  1452. f += suffix;
  1453. }
  1454. remove_reserved_file_characters(f);
  1455. return f;
  1456. }
  1457. string GetOutputFilename(const char *path, const char *ext, bool noSpace,
  1458. bool overwrite, const char *format)
  1459. {
  1460. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1461. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1462. if (!dir) {
  1463. if (main->isVisible())
  1464. OBSMessageBox::warning(main,
  1465. QTStr("Output.BadPath.Title"),
  1466. QTStr("Output.BadPath.Text"));
  1467. else
  1468. main->SysTrayNotify(QTStr("Output.BadPath.Text"),
  1469. QSystemTrayIcon::Warning);
  1470. return "";
  1471. }
  1472. os_closedir(dir);
  1473. string strPath;
  1474. strPath += path;
  1475. char lastChar = strPath.back();
  1476. if (lastChar != '/' && lastChar != '\\')
  1477. strPath += "/";
  1478. strPath += GenerateSpecifiedFilename(ext, noSpace, format);
  1479. ensure_directory_exists(strPath);
  1480. if (!overwrite)
  1481. FindBestFilename(strPath, noSpace);
  1482. return strPath;
  1483. }
  1484. vector<pair<string, string>> GetLocaleNames()
  1485. {
  1486. string path;
  1487. if (!GetDataFilePath("locale.ini", path))
  1488. throw "Could not find locale.ini path";
  1489. ConfigFile ini;
  1490. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1491. throw "Could not open locale.ini";
  1492. size_t sections = config_num_sections(ini);
  1493. vector<pair<string, string>> names;
  1494. names.reserve(sections);
  1495. for (size_t i = 0; i < sections; i++) {
  1496. const char *tag = config_get_section(ini, i);
  1497. const char *name = config_get_string(ini, tag, "Name");
  1498. names.emplace_back(tag, name);
  1499. }
  1500. return names;
  1501. }
  1502. static void create_log_file(fstream &logFile)
  1503. {
  1504. stringstream dst;
  1505. get_last_log(false, "obs-studio/logs", lastLogFile);
  1506. #ifdef _WIN32
  1507. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1508. #endif
  1509. currentLogFile = GenerateTimeDateFilename("txt");
  1510. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1511. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1512. #ifdef _WIN32
  1513. BPtr<wchar_t> wpath;
  1514. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1515. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1516. #else
  1517. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1518. #endif
  1519. if (logFile.is_open()) {
  1520. delete_oldest_file(false, "obs-studio/logs");
  1521. base_set_log_handler(do_log, &logFile);
  1522. } else {
  1523. blog(LOG_ERROR, "Failed to open log file");
  1524. }
  1525. }
  1526. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1527. profiler_name_store_free(store);
  1528. };
  1529. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1530. decltype(ProfilerNameStoreRelease)>;
  1531. ProfilerNameStore CreateNameStore()
  1532. {
  1533. return ProfilerNameStore{profiler_name_store_create(),
  1534. ProfilerNameStoreRelease};
  1535. }
  1536. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1537. profile_snapshot_free(snap);
  1538. };
  1539. using ProfilerSnapshot =
  1540. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1541. ProfilerSnapshot GetSnapshot()
  1542. {
  1543. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1544. }
  1545. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1546. {
  1547. if (currentLogFile.empty())
  1548. return;
  1549. auto pos = currentLogFile.rfind('.');
  1550. if (pos == currentLogFile.npos)
  1551. return;
  1552. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1553. ostringstream dst;
  1554. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1555. dst.write(currentLogFile.c_str(), pos);
  1556. dst.write(LITERAL_SIZE(".csv.gz"));
  1557. #undef LITERAL_SIZE
  1558. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1559. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1560. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1561. static_cast<const char *>(path));
  1562. }
  1563. static auto ProfilerFree = [](void *) {
  1564. profiler_stop();
  1565. auto snap = GetSnapshot();
  1566. profiler_print(snap.get());
  1567. profiler_print_time_between_calls(snap.get());
  1568. SaveProfilerData(snap);
  1569. profiler_free();
  1570. };
  1571. QAccessibleInterface *accessibleFactory(const QString &classname,
  1572. QObject *object)
  1573. {
  1574. if (classname == QLatin1String("VolumeSlider") && object &&
  1575. object->isWidgetType())
  1576. return new VolumeAccessibleInterface(
  1577. static_cast<QWidget *>(object));
  1578. return nullptr;
  1579. }
  1580. static const char *run_program_init = "run_program_init";
  1581. static int run_program(fstream &logFile, int argc, char *argv[])
  1582. {
  1583. int ret = -1;
  1584. auto profilerNameStore = CreateNameStore();
  1585. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1586. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1587. profiler_start();
  1588. profile_register_root(run_program_init, 0);
  1589. ScopeProfiler prof{run_program_init};
  1590. #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  1591. QGuiApplication::setAttribute(opt_disable_high_dpi_scaling
  1592. ? Qt::AA_DisableHighDpiScaling
  1593. : Qt::AA_EnableHighDpiScaling);
  1594. #endif
  1595. #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) && defined(_WIN32)
  1596. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
  1597. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1598. #endif
  1599. QCoreApplication::addLibraryPath(".");
  1600. #if __APPLE__
  1601. InstallNSApplicationSubclass();
  1602. #endif
  1603. OBSApp program(argc, argv, profilerNameStore.get());
  1604. try {
  1605. QAccessible::installFactory(accessibleFactory);
  1606. bool created_log = false;
  1607. program.AppInit();
  1608. delete_oldest_file(false, "obs-studio/profiler_data");
  1609. OBSTranslator translator;
  1610. program.installTranslator(&translator);
  1611. /* --------------------------------------- */
  1612. /* check and warn if already running */
  1613. bool cancel_launch = false;
  1614. bool already_running = false;
  1615. #if defined(_WIN32)
  1616. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1617. #elif defined(__APPLE__)
  1618. CheckAppWithSameBundleID(already_running);
  1619. #elif defined(__linux__)
  1620. RunningInstanceCheck(already_running);
  1621. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  1622. PIDFileCheck(already_running);
  1623. #endif
  1624. if (!already_running) {
  1625. goto run;
  1626. }
  1627. if (!multi) {
  1628. QMessageBox::StandardButtons buttons(
  1629. QMessageBox::Yes | QMessageBox::Cancel);
  1630. QMessageBox mb(QMessageBox::Question,
  1631. QTStr("AlreadyRunning.Title"),
  1632. QTStr("AlreadyRunning.Text"), buttons,
  1633. nullptr);
  1634. mb.setButtonText(QMessageBox::Yes,
  1635. QTStr("AlreadyRunning.LaunchAnyway"));
  1636. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1637. mb.setDefaultButton(QMessageBox::Cancel);
  1638. QMessageBox::StandardButton button;
  1639. button = (QMessageBox::StandardButton)mb.exec();
  1640. cancel_launch = button == QMessageBox::Cancel;
  1641. }
  1642. if (cancel_launch)
  1643. return 0;
  1644. if (!created_log) {
  1645. create_log_file(logFile);
  1646. created_log = true;
  1647. }
  1648. if (multi) {
  1649. blog(LOG_INFO, "User enabled --multi flag and is now "
  1650. "running multiple instances of OBS.");
  1651. } else {
  1652. blog(LOG_WARNING, "================================");
  1653. blog(LOG_WARNING, "Warning: OBS is already running!");
  1654. blog(LOG_WARNING, "================================");
  1655. blog(LOG_WARNING, "User is now running multiple "
  1656. "instances of OBS!");
  1657. }
  1658. /* --------------------------------------- */
  1659. run:
  1660. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1661. // Mounted by termina during chromeOS linux container startup
  1662. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1663. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1664. if (crosDir) {
  1665. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1666. QMessageBox mb(QMessageBox::Critical,
  1667. QTStr("ChromeOS.Title"),
  1668. QTStr("ChromeOS.Text"), buttons,
  1669. nullptr);
  1670. mb.exec();
  1671. return 0;
  1672. }
  1673. #endif
  1674. if (!created_log) {
  1675. create_log_file(logFile);
  1676. created_log = true;
  1677. }
  1678. if (argc > 1) {
  1679. stringstream stor;
  1680. stor << argv[1];
  1681. for (int i = 2; i < argc; ++i) {
  1682. stor << " " << argv[i];
  1683. }
  1684. blog(LOG_INFO, "Command Line Arguments: %s",
  1685. stor.str().c_str());
  1686. }
  1687. if (!program.OBSInit())
  1688. return 0;
  1689. prof.Stop();
  1690. ret = program.exec();
  1691. } catch (const char *error) {
  1692. blog(LOG_ERROR, "%s", error);
  1693. OBSErrorBox(nullptr, "%s", error);
  1694. }
  1695. if (restart)
  1696. QProcess::startDetached(qApp->arguments()[0],
  1697. qApp->arguments());
  1698. return ret;
  1699. }
  1700. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1701. #ifdef _WIN32
  1702. #define CRASH_MESSAGE \
  1703. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1704. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1705. static void main_crash_handler(const char *format, va_list args, void *param)
  1706. {
  1707. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1708. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1709. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1710. string crashFilePath = "obs-studio/crashes";
  1711. delete_oldest_file(true, crashFilePath.c_str());
  1712. string name = crashFilePath + "/";
  1713. name += "Crash " + GenerateTimeDateFilename("txt");
  1714. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1715. fstream file;
  1716. #ifdef _WIN32
  1717. BPtr<wchar_t> wpath;
  1718. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1719. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1720. ios_base::binary);
  1721. #else
  1722. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1723. ios_base::binary);
  1724. #endif
  1725. file << text;
  1726. file.close();
  1727. string pathString(path.Get());
  1728. #ifdef _WIN32
  1729. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1730. #endif
  1731. string absolutePath =
  1732. canonical(filesystem::path(pathString)).u8string();
  1733. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1734. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1735. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
  1736. absolutePath.c_str());
  1737. string finalMessage =
  1738. string(message_buffer.get(), message_buffer.get() + size);
  1739. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
  1740. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1741. if (ret == IDYES) {
  1742. size_t len = strlen(text);
  1743. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1744. memcpy(GlobalLock(mem), text, len);
  1745. GlobalUnlock(mem);
  1746. OpenClipboard(0);
  1747. EmptyClipboard();
  1748. SetClipboardData(CF_TEXT, mem);
  1749. CloseClipboard();
  1750. }
  1751. exit(-1);
  1752. UNUSED_PARAMETER(param);
  1753. }
  1754. static void load_debug_privilege(void)
  1755. {
  1756. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1757. TOKEN_PRIVILEGES tp;
  1758. HANDLE token;
  1759. LUID val;
  1760. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1761. return;
  1762. }
  1763. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1764. tp.PrivilegeCount = 1;
  1765. tp.Privileges[0].Luid = val;
  1766. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1767. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1768. NULL);
  1769. }
  1770. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1771. tp.PrivilegeCount = 1;
  1772. tp.Privileges[0].Luid = val;
  1773. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1774. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1775. NULL)) {
  1776. blog(LOG_INFO, "Could not set privilege to "
  1777. "increase GPU priority");
  1778. }
  1779. }
  1780. CloseHandle(token);
  1781. }
  1782. #endif
  1783. #ifdef __APPLE__
  1784. #define BASE_PATH ".."
  1785. #else
  1786. #define BASE_PATH "../.."
  1787. #endif
  1788. #define CONFIG_PATH BASE_PATH "/config"
  1789. #ifndef OBS_UNIX_STRUCTURE
  1790. #define OBS_UNIX_STRUCTURE 0
  1791. #endif
  1792. int GetConfigPath(char *path, size_t size, const char *name)
  1793. {
  1794. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1795. if (name && *name) {
  1796. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1797. } else {
  1798. return snprintf(path, size, CONFIG_PATH);
  1799. }
  1800. } else {
  1801. return os_get_config_path(path, size, name);
  1802. }
  1803. }
  1804. char *GetConfigPathPtr(const char *name)
  1805. {
  1806. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1807. char path[512];
  1808. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1809. return bstrdup(path);
  1810. } else {
  1811. return NULL;
  1812. }
  1813. } else {
  1814. return os_get_config_path_ptr(name);
  1815. }
  1816. }
  1817. int GetProgramDataPath(char *path, size_t size, const char *name)
  1818. {
  1819. return os_get_program_data_path(path, size, name);
  1820. }
  1821. char *GetProgramDataPathPtr(const char *name)
  1822. {
  1823. return os_get_program_data_path_ptr(name);
  1824. }
  1825. bool GetFileSafeName(const char *name, std::string &file)
  1826. {
  1827. size_t base_len = strlen(name);
  1828. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1829. std::wstring wfile;
  1830. if (!len)
  1831. return false;
  1832. wfile.resize(len);
  1833. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1834. for (size_t i = wfile.size(); i > 0; i--) {
  1835. size_t im1 = i - 1;
  1836. if (iswspace(wfile[im1])) {
  1837. wfile[im1] = '_';
  1838. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1839. wfile.erase(im1, 1);
  1840. }
  1841. }
  1842. if (wfile.size() == 0)
  1843. wfile = L"characters_only";
  1844. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1845. if (!len)
  1846. return false;
  1847. file.resize(len);
  1848. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1849. return true;
  1850. }
  1851. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1852. {
  1853. size_t len = path.size();
  1854. if (extension) {
  1855. path += ".";
  1856. path += extension;
  1857. }
  1858. if (!os_file_exists(path.c_str()))
  1859. return true;
  1860. int index = 1;
  1861. do {
  1862. path.resize(len);
  1863. path += std::to_string(++index);
  1864. if (extension) {
  1865. path += ".";
  1866. path += extension;
  1867. }
  1868. } while (os_file_exists(path.c_str()));
  1869. return true;
  1870. }
  1871. bool GetUnusedSceneCollectionFile(std::string &name, std::string &file)
  1872. {
  1873. char path[512];
  1874. int ret;
  1875. if (!GetFileSafeName(name.c_str(), file)) {
  1876. blog(LOG_WARNING, "Failed to create safe file name for '%s'",
  1877. name.c_str());
  1878. return false;
  1879. }
  1880. ret = GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes/");
  1881. if (ret <= 0) {
  1882. blog(LOG_WARNING, "Failed to get scene collection config path");
  1883. return false;
  1884. }
  1885. file.insert(0, path);
  1886. if (!GetClosestUnusedFileName(file, "json")) {
  1887. blog(LOG_WARNING, "Failed to get closest file name for %s",
  1888. file.c_str());
  1889. return false;
  1890. }
  1891. file.erase(file.size() - 5, 5);
  1892. file.erase(0, strlen(path));
  1893. return true;
  1894. }
  1895. bool WindowPositionValid(QRect rect)
  1896. {
  1897. for (QScreen *screen : QGuiApplication::screens()) {
  1898. if (screen->availableGeometry().intersects(rect))
  1899. return true;
  1900. }
  1901. return false;
  1902. }
  1903. static inline bool arg_is(const char *arg, const char *long_form,
  1904. const char *short_form)
  1905. {
  1906. return (long_form && strcmp(arg, long_form) == 0) ||
  1907. (short_form && strcmp(arg, short_form) == 0);
  1908. }
  1909. #if !defined(_WIN32) && !defined(__APPLE__)
  1910. #define IS_UNIX 1
  1911. #endif
  1912. /* if using XDG and was previously using an older build of OBS, move config
  1913. * files to XDG directory */
  1914. #if defined(USE_XDG) && defined(IS_UNIX)
  1915. static void move_to_xdg(void)
  1916. {
  1917. char old_path[512];
  1918. char new_path[512];
  1919. char *home = getenv("HOME");
  1920. if (!home)
  1921. return;
  1922. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1923. return;
  1924. /* make base xdg path if it doesn't already exist */
  1925. if (GetConfigPath(new_path, 512, "") <= 0)
  1926. return;
  1927. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1928. return;
  1929. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1930. return;
  1931. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1932. rename(old_path, new_path);
  1933. }
  1934. }
  1935. #endif
  1936. static bool update_ffmpeg_output(ConfigFile &config)
  1937. {
  1938. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1939. return false;
  1940. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1941. if (!url)
  1942. return false;
  1943. bool isActualURL = strstr(url, "://") != nullptr;
  1944. if (isActualURL)
  1945. return false;
  1946. string urlStr = url;
  1947. string extension;
  1948. for (size_t i = urlStr.length(); i > 0; i--) {
  1949. size_t idx = i - 1;
  1950. if (urlStr[idx] == '.') {
  1951. extension = &urlStr[i];
  1952. }
  1953. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1954. urlStr[idx] = 0;
  1955. break;
  1956. }
  1957. }
  1958. if (urlStr.empty() || extension.empty())
  1959. return false;
  1960. config_remove_value(config, "AdvOut", "FFURL");
  1961. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1962. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1963. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1964. return true;
  1965. }
  1966. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1967. {
  1968. bool changed = false;
  1969. if (config_has_user_value(config, sec, "Reconnect")) {
  1970. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1971. config_set_bool(config, "Output", "Reconnect", reconnect);
  1972. changed = true;
  1973. }
  1974. if (config_has_user_value(config, sec, "RetryDelay")) {
  1975. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1976. config_set_uint(config, "Output", "RetryDelay", delay);
  1977. changed = true;
  1978. }
  1979. if (config_has_user_value(config, sec, "MaxRetries")) {
  1980. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1981. config_set_uint(config, "Output", "MaxRetries", retries);
  1982. changed = true;
  1983. }
  1984. return changed;
  1985. }
  1986. static bool update_reconnect(ConfigFile &config)
  1987. {
  1988. if (!config_has_user_value(config, "Output", "Mode"))
  1989. return false;
  1990. const char *mode = config_get_string(config, "Output", "Mode");
  1991. if (!mode)
  1992. return false;
  1993. const char *section = (strcmp(mode, "Advanced") == 0) ? "AdvOut"
  1994. : "SimpleOutput";
  1995. if (move_reconnect_settings(config, section)) {
  1996. config_remove_value(config, "SimpleOutput", "Reconnect");
  1997. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1998. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1999. config_remove_value(config, "AdvOut", "Reconnect");
  2000. config_remove_value(config, "AdvOut", "RetryDelay");
  2001. config_remove_value(config, "AdvOut", "MaxRetries");
  2002. return true;
  2003. }
  2004. return false;
  2005. }
  2006. static void convert_x264_settings(obs_data_t *data)
  2007. {
  2008. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  2009. if (use_bufsize) {
  2010. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  2011. if (buffer_size == 0)
  2012. obs_data_set_string(data, "rate_control", "CRF");
  2013. }
  2014. }
  2015. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  2016. {
  2017. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  2018. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  2019. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  2020. bool modified = false;
  2021. bool cbr = true;
  2022. if (cbr_item) {
  2023. cbr = obs_data_item_get_bool(cbr_item);
  2024. obs_data_item_unset_user_value(cbr_item);
  2025. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  2026. modified = true;
  2027. }
  2028. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  2029. if (!cbr_item)
  2030. obs_data_set_string(data, "rate_control", "CBR");
  2031. else if (!cbr)
  2032. convert_x264_settings(data);
  2033. modified = true;
  2034. }
  2035. if (modified)
  2036. obs_data_save_json_safe(data, file, "tmp", "bak");
  2037. obs_data_item_release(&rc_item);
  2038. obs_data_item_release(&cbr_item);
  2039. obs_data_release(data);
  2040. }
  2041. static void upgrade_settings(void)
  2042. {
  2043. char path[512];
  2044. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  2045. if (pathlen <= 0)
  2046. return;
  2047. if (!os_file_exists(path))
  2048. return;
  2049. os_dir_t *dir = os_opendir(path);
  2050. if (!dir)
  2051. return;
  2052. struct os_dirent *ent = os_readdir(dir);
  2053. while (ent) {
  2054. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  2055. strcmp(ent->d_name, "..") != 0) {
  2056. strcat(path, "/");
  2057. strcat(path, ent->d_name);
  2058. strcat(path, "/basic.ini");
  2059. ConfigFile config;
  2060. int ret;
  2061. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  2062. if (ret == CONFIG_SUCCESS) {
  2063. if (update_ffmpeg_output(config) ||
  2064. update_reconnect(config)) {
  2065. config_save_safe(config, "tmp",
  2066. nullptr);
  2067. }
  2068. }
  2069. if (config) {
  2070. const char *sEnc = config_get_string(
  2071. config, "AdvOut", "Encoder");
  2072. const char *rEnc = config_get_string(
  2073. config, "AdvOut", "RecEncoder");
  2074. /* replace "cbr" option with "rate_control" for
  2075. * each profile's encoder data */
  2076. path[pathlen] = 0;
  2077. strcat(path, "/");
  2078. strcat(path, ent->d_name);
  2079. strcat(path, "/recordEncoder.json");
  2080. convert_14_2_encoder_setting(rEnc, path);
  2081. path[pathlen] = 0;
  2082. strcat(path, "/");
  2083. strcat(path, ent->d_name);
  2084. strcat(path, "/streamEncoder.json");
  2085. convert_14_2_encoder_setting(sEnc, path);
  2086. }
  2087. path[pathlen] = 0;
  2088. }
  2089. ent = os_readdir(dir);
  2090. }
  2091. os_closedir(dir);
  2092. }
  2093. void ctrlc_handler(int s)
  2094. {
  2095. UNUSED_PARAMETER(s);
  2096. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  2097. main->close();
  2098. }
  2099. int main(int argc, char *argv[])
  2100. {
  2101. #ifndef _WIN32
  2102. signal(SIGPIPE, SIG_IGN);
  2103. struct sigaction sig_handler;
  2104. sig_handler.sa_handler = ctrlc_handler;
  2105. sigemptyset(&sig_handler.sa_mask);
  2106. sig_handler.sa_flags = 0;
  2107. sigaction(SIGINT, &sig_handler, NULL);
  2108. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  2109. a closed pipe. */
  2110. sigset_t sigpipe_mask;
  2111. sigemptyset(&sigpipe_mask);
  2112. sigaddset(&sigpipe_mask, SIGPIPE);
  2113. sigset_t saved_mask;
  2114. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  2115. perror("pthread_sigmask");
  2116. exit(1);
  2117. }
  2118. #endif
  2119. #ifdef _WIN32
  2120. obs_init_win32_crash_handler();
  2121. SetErrorMode(SEM_FAILCRITICALERRORS);
  2122. load_debug_privilege();
  2123. base_set_crash_handler(main_crash_handler, nullptr);
  2124. #endif
  2125. base_get_log_handler(&def_log_handler, nullptr);
  2126. #if defined(USE_XDG) && defined(IS_UNIX)
  2127. move_to_xdg();
  2128. #endif
  2129. obs_set_cmdline_args(argc, argv);
  2130. for (int i = 1; i < argc; i++) {
  2131. if (arg_is(argv[i], "--portable", "-p")) {
  2132. portable_mode = true;
  2133. } else if (arg_is(argv[i], "--multi", "-m")) {
  2134. multi = true;
  2135. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2136. log_verbose = true;
  2137. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2138. opt_always_on_top = true;
  2139. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2140. unfiltered_log = true;
  2141. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2142. opt_start_streaming = true;
  2143. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2144. opt_start_recording = true;
  2145. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2146. opt_start_replaybuffer = true;
  2147. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2148. opt_start_virtualcam = true;
  2149. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2150. if (++i < argc)
  2151. opt_starting_collection = argv[i];
  2152. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2153. if (++i < argc)
  2154. opt_starting_profile = argv[i];
  2155. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2156. if (++i < argc)
  2157. opt_starting_scene = argv[i];
  2158. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2159. opt_minimize_tray = true;
  2160. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2161. opt_studio_mode = true;
  2162. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2163. opt_allow_opengl = true;
  2164. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2165. opt_disable_updater = true;
  2166. } else if (arg_is(argv[i], "--disable-high-dpi-scaling",
  2167. nullptr)) {
  2168. opt_disable_high_dpi_scaling = true;
  2169. } else if (arg_is(argv[i], "--help", "-h")) {
  2170. std::string help =
  2171. "--help, -h: Get list of available commands.\n\n"
  2172. "--startstreaming: Automatically start streaming.\n"
  2173. "--startrecording: Automatically start recording.\n"
  2174. "--startreplaybuffer: Start replay buffer.\n"
  2175. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2176. "--collection <string>: Use specific scene collection."
  2177. "\n"
  2178. "--profile <string>: Use specific profile.\n"
  2179. "--scene <string>: Start with specific scene.\n\n"
  2180. "--studio-mode: Enable studio mode.\n"
  2181. "--minimize-to-tray: Minimize to system tray.\n"
  2182. "--portable, -p: Use portable mode.\n"
  2183. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2184. "--verbose: Make log more verbose.\n"
  2185. "--always-on-top: Start in 'always on top' mode.\n\n"
  2186. "--unfiltered_log: Make log unfiltered.\n\n"
  2187. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2188. "--disable-high-dpi-scaling: Disable automatic high-DPI scaling\n\n";
  2189. #ifdef _WIN32
  2190. MessageBoxA(NULL, help.c_str(), "Help",
  2191. MB_OK | MB_ICONASTERISK);
  2192. #else
  2193. std::cout << help
  2194. << "--version, -V: Get current version.\n";
  2195. #endif
  2196. exit(0);
  2197. } else if (arg_is(argv[i], "--version", "-V")) {
  2198. std::cout << "OBS Studio - "
  2199. << App()->GetVersionString() << "\n";
  2200. exit(0);
  2201. }
  2202. }
  2203. #if !OBS_UNIX_STRUCTURE
  2204. if (!portable_mode) {
  2205. portable_mode =
  2206. os_file_exists(BASE_PATH "/portable_mode") ||
  2207. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2208. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2209. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2210. }
  2211. if (!opt_disable_updater) {
  2212. opt_disable_updater =
  2213. os_file_exists(BASE_PATH "/disable_updater") ||
  2214. os_file_exists(BASE_PATH "/disable_updater.txt");
  2215. }
  2216. #endif
  2217. upgrade_settings();
  2218. fstream logFile;
  2219. curl_global_init(CURL_GLOBAL_ALL);
  2220. int ret = run_program(logFile, argc, argv);
  2221. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2222. base_set_log_handler(nullptr, nullptr);
  2223. return ret;
  2224. }