obs-app.cpp 65 KB

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