obs-app.cpp 71 KB

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