obs-app.cpp 66 KB

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