obs-app.cpp 74 KB

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