obs-app.cpp 71 KB

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