obs-app.cpp 69 KB

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