obs-app.cpp 70 KB

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