obs-app.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <time.h>
  15. #include <stdio.h>
  16. #include <wchar.h>
  17. #include <chrono>
  18. #include <ratio>
  19. #include <string>
  20. #include <sstream>
  21. #include <mutex>
  22. #include <util/bmem.h>
  23. #include <util/dstr.hpp>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <util/cf-parser.h>
  27. #include <obs-config.h>
  28. #include <obs.hpp>
  29. #include <QFile>
  30. #include <QGuiApplication>
  31. #include <QProxyStyle>
  32. #include <QScreen>
  33. #include <QProcess>
  34. #include <QAccessible>
  35. #include "qt-wrappers.hpp"
  36. #include "obs-app.hpp"
  37. #include "log-viewer.hpp"
  38. #include "slider-ignorewheel.hpp"
  39. #include "window-basic-main.hpp"
  40. #include "window-basic-settings.hpp"
  41. #include "crash-report.hpp"
  42. #include "platform.hpp"
  43. #include <fstream>
  44. #include <curl/curl.h>
  45. #ifdef _WIN32
  46. #include <windows.h>
  47. #include <filesystem>
  48. #else
  49. #include <signal.h>
  50. #include <pthread.h>
  51. #endif
  52. #if !defined(_WIN32) && !defined(__APPLE__)
  53. #include <obs-nix-platform.h>
  54. #include <qpa/qplatformnativeinterface.h>
  55. #endif
  56. #include <iostream>
  57. #include "ui-config.h"
  58. using namespace std;
  59. static log_handler_t def_log_handler;
  60. static string currentLogFile;
  61. static string lastLogFile;
  62. static string lastCrashLogFile;
  63. bool portable_mode = false;
  64. static bool multi = false;
  65. static bool log_verbose = false;
  66. static bool unfiltered_log = false;
  67. bool opt_start_streaming = false;
  68. bool opt_start_recording = false;
  69. bool opt_studio_mode = false;
  70. bool opt_start_replaybuffer = false;
  71. bool opt_start_virtualcam = false;
  72. bool opt_minimize_tray = false;
  73. bool opt_allow_opengl = false;
  74. bool opt_always_on_top = false;
  75. bool opt_disable_high_dpi_scaling = false;
  76. bool opt_disable_updater = false;
  77. bool opt_disable_missing_files_check = false;
  78. string opt_starting_collection;
  79. string opt_starting_profile;
  80. string opt_starting_scene;
  81. bool restart = false;
  82. QPointer<OBSLogViewer> obsLogViewer;
  83. // GPU hint exports for AMD/NVIDIA laptops
  84. #ifdef _MSC_VER
  85. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  86. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  87. #endif
  88. QObject *CreateShortcutFilter()
  89. {
  90. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  91. auto mouse_event = [](QMouseEvent &event) {
  92. if (!App()->HotkeysEnabledInFocus() &&
  93. event.button() != Qt::LeftButton)
  94. return true;
  95. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  96. bool pressed = event.type() == QEvent::MouseButtonPress;
  97. switch (event.button()) {
  98. case Qt::NoButton:
  99. case Qt::LeftButton:
  100. case Qt::RightButton:
  101. case Qt::AllButtons:
  102. case Qt::MouseButtonMask:
  103. return false;
  104. case Qt::MiddleButton:
  105. hotkey.key = OBS_KEY_MOUSE3;
  106. break;
  107. #define MAP_BUTTON(i, j) \
  108. case Qt::ExtraButton##i: \
  109. hotkey.key = OBS_KEY_MOUSE##j; \
  110. break;
  111. MAP_BUTTON(1, 4);
  112. MAP_BUTTON(2, 5);
  113. MAP_BUTTON(3, 6);
  114. MAP_BUTTON(4, 7);
  115. MAP_BUTTON(5, 8);
  116. MAP_BUTTON(6, 9);
  117. MAP_BUTTON(7, 10);
  118. MAP_BUTTON(8, 11);
  119. MAP_BUTTON(9, 12);
  120. MAP_BUTTON(10, 13);
  121. MAP_BUTTON(11, 14);
  122. MAP_BUTTON(12, 15);
  123. MAP_BUTTON(13, 16);
  124. MAP_BUTTON(14, 17);
  125. MAP_BUTTON(15, 18);
  126. MAP_BUTTON(16, 19);
  127. MAP_BUTTON(17, 20);
  128. MAP_BUTTON(18, 21);
  129. MAP_BUTTON(19, 22);
  130. MAP_BUTTON(20, 23);
  131. MAP_BUTTON(21, 24);
  132. MAP_BUTTON(22, 25);
  133. MAP_BUTTON(23, 26);
  134. MAP_BUTTON(24, 27);
  135. #undef MAP_BUTTON
  136. }
  137. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  138. event.modifiers());
  139. obs_hotkey_inject_event(hotkey, pressed);
  140. return true;
  141. };
  142. auto key_event = [&](QKeyEvent *event) {
  143. int key = event->key();
  144. bool enabledInFocus = App()->HotkeysEnabledInFocus();
  145. if (key != Qt::Key_Enter && key != Qt::Key_Escape &&
  146. key != Qt::Key_Return && !enabledInFocus)
  147. return true;
  148. QDialog *dialog = qobject_cast<QDialog *>(obj);
  149. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  150. bool pressed = event->type() == QEvent::KeyPress;
  151. switch (key) {
  152. case Qt::Key_Shift:
  153. case Qt::Key_Control:
  154. case Qt::Key_Alt:
  155. case Qt::Key_Meta:
  156. break;
  157. #ifdef __APPLE__
  158. case Qt::Key_CapsLock:
  159. // kVK_CapsLock == 57
  160. hotkey.key = obs_key_from_virtual_key(57);
  161. pressed = true;
  162. break;
  163. #endif
  164. case Qt::Key_Enter:
  165. case Qt::Key_Escape:
  166. case Qt::Key_Return:
  167. if (dialog && pressed)
  168. return false;
  169. if (!enabledInFocus)
  170. return true;
  171. /* Falls through. */
  172. default:
  173. hotkey.key = obs_key_from_virtual_key(
  174. event->nativeVirtualKey());
  175. }
  176. if (event->isAutoRepeat())
  177. return true;
  178. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  179. event->modifiers());
  180. obs_hotkey_inject_event(hotkey, pressed);
  181. return true;
  182. };
  183. switch (event->type()) {
  184. case QEvent::MouseButtonPress:
  185. case QEvent::MouseButtonRelease:
  186. return mouse_event(*static_cast<QMouseEvent *>(event));
  187. /*case QEvent::MouseButtonDblClick:
  188. case QEvent::Wheel:*/
  189. case QEvent::KeyPress:
  190. case QEvent::KeyRelease:
  191. return key_event(static_cast<QKeyEvent *>(event));
  192. default:
  193. return false;
  194. }
  195. });
  196. }
  197. string CurrentTimeString()
  198. {
  199. using namespace std::chrono;
  200. struct tm tstruct;
  201. char buf[80];
  202. auto tp = system_clock::now();
  203. auto now = system_clock::to_time_t(tp);
  204. tstruct = *localtime(&now);
  205. size_t written = strftime(buf, sizeof(buf), "%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. setStyleSheet(mpath);
  917. QColor color = palette().text().color();
  918. themeDarkMode = !(color.redF() < 0.5);
  919. emit StyleChanged();
  920. return true;
  921. }
  922. bool OBSApp::InitTheme()
  923. {
  924. defaultPalette = palette();
  925. const char *themeName =
  926. config_get_string(globalConfig, "General", "CurrentTheme2");
  927. if (!themeName)
  928. /* Use deprecated "CurrentTheme" value if available */
  929. themeName = config_get_string(globalConfig, "General",
  930. "CurrentTheme");
  931. if (!themeName)
  932. /* Use deprecated "Theme" value if available */
  933. themeName = config_get_string(globalConfig, "General", "Theme");
  934. if (!themeName)
  935. themeName = DEFAULT_THEME;
  936. if (!themeName)
  937. themeName = "Dark";
  938. if (strcmp(themeName, "Default") == 0)
  939. themeName = "System";
  940. if (strcmp(themeName, "System") != 0 && SetTheme(themeName))
  941. return true;
  942. return SetTheme("System");
  943. }
  944. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  945. : QApplication(argc, argv), profilerNameStore(store)
  946. {
  947. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  948. #ifdef __APPLE__
  949. setWindowIcon(
  950. QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png")));
  951. #else
  952. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  953. #endif
  954. setDesktopFileName("com.obsproject.Studio");
  955. }
  956. OBSApp::~OBSApp()
  957. {
  958. #ifdef _WIN32
  959. bool disableAudioDucking =
  960. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  961. if (disableAudioDucking)
  962. DisableAudioDucking(false);
  963. #endif
  964. #ifdef __APPLE__
  965. bool vsyncDisabled =
  966. config_get_bool(globalConfig, "Video", "DisableOSXVSync");
  967. bool resetVSync =
  968. config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
  969. if (vsyncDisabled && resetVSync)
  970. EnableOSXVSync(true);
  971. #endif
  972. os_inhibit_sleep_set_active(sleepInhibitor, false);
  973. os_inhibit_sleep_destroy(sleepInhibitor);
  974. if (libobs_initialized)
  975. obs_shutdown();
  976. }
  977. static void move_basic_to_profiles(void)
  978. {
  979. char path[512];
  980. char new_path[512];
  981. os_glob_t *glob;
  982. /* if not first time use */
  983. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  984. return;
  985. if (!os_file_exists(path))
  986. return;
  987. /* if the profiles directory doesn't already exist */
  988. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  989. return;
  990. if (os_file_exists(new_path))
  991. return;
  992. if (os_mkdir(new_path) == MKDIR_ERROR)
  993. return;
  994. strcat(new_path, "/");
  995. strcat(new_path, Str("Untitled"));
  996. if (os_mkdir(new_path) == MKDIR_ERROR)
  997. return;
  998. strcat(path, "/*.*");
  999. if (os_glob(path, 0, &glob) != 0)
  1000. return;
  1001. strcpy(path, new_path);
  1002. for (size_t i = 0; i < glob->gl_pathc; i++) {
  1003. struct os_globent ent = glob->gl_pathv[i];
  1004. char *file;
  1005. if (ent.directory)
  1006. continue;
  1007. file = strrchr(ent.path, '/');
  1008. if (!file++)
  1009. continue;
  1010. if (astrcmpi(file, "scenes.json") == 0)
  1011. continue;
  1012. strcpy(new_path, path);
  1013. strcat(new_path, "/");
  1014. strcat(new_path, file);
  1015. os_rename(ent.path, new_path);
  1016. }
  1017. os_globfree(glob);
  1018. }
  1019. static void move_basic_to_scene_collections(void)
  1020. {
  1021. char path[512];
  1022. char new_path[512];
  1023. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  1024. return;
  1025. if (!os_file_exists(path))
  1026. return;
  1027. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  1028. return;
  1029. if (os_file_exists(new_path))
  1030. return;
  1031. if (os_mkdir(new_path) == MKDIR_ERROR)
  1032. return;
  1033. strcat(path, "/scenes.json");
  1034. strcat(new_path, "/");
  1035. strcat(new_path, Str("Untitled"));
  1036. strcat(new_path, ".json");
  1037. os_rename(path, new_path);
  1038. }
  1039. void OBSApp::AppInit()
  1040. {
  1041. ProfileScope("OBSApp::AppInit");
  1042. if (!InitApplicationBundle())
  1043. throw "Failed to initialize application bundle";
  1044. if (!MakeUserDirs())
  1045. throw "Failed to create required user directories";
  1046. if (!InitGlobalConfig())
  1047. throw "Failed to initialize global config";
  1048. if (!InitLocale())
  1049. throw "Failed to load locale";
  1050. if (!InitTheme())
  1051. throw "Failed to load theme";
  1052. config_set_default_string(globalConfig, "Basic", "Profile",
  1053. Str("Untitled"));
  1054. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  1055. Str("Untitled"));
  1056. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  1057. Str("Untitled"));
  1058. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  1059. Str("Untitled"));
  1060. config_set_default_bool(globalConfig, "Basic", "ConfigOnNewProfile",
  1061. true);
  1062. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  1063. config_set_string(globalConfig, "Basic", "Profile",
  1064. Str("Untitled"));
  1065. config_set_string(globalConfig, "Basic", "ProfileDir",
  1066. Str("Untitled"));
  1067. }
  1068. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  1069. config_set_string(globalConfig, "Basic", "SceneCollection",
  1070. Str("Untitled"));
  1071. config_set_string(globalConfig, "Basic", "SceneCollectionFile",
  1072. Str("Untitled"));
  1073. }
  1074. #ifdef _WIN32
  1075. bool disableAudioDucking =
  1076. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  1077. if (disableAudioDucking)
  1078. DisableAudioDucking(true);
  1079. #endif
  1080. #ifdef __APPLE__
  1081. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  1082. EnableOSXVSync(false);
  1083. #endif
  1084. UpdateHotkeyFocusSetting(false);
  1085. move_basic_to_profiles();
  1086. move_basic_to_scene_collections();
  1087. if (!MakeUserProfileDirs())
  1088. throw "Failed to create profile directories";
  1089. }
  1090. const char *OBSApp::GetRenderModule() const
  1091. {
  1092. const char *renderer =
  1093. config_get_string(globalConfig, "Video", "Renderer");
  1094. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1095. }
  1096. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1097. {
  1098. char path[512];
  1099. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1100. return false;
  1101. return obs_startup(locale, path, store);
  1102. }
  1103. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1104. {
  1105. obs_hotkey_enable_background_press(
  1106. (inFocus && enableHotkeysInFocus) ||
  1107. (!inFocus && enableHotkeysOutOfFocus));
  1108. }
  1109. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1110. {
  1111. enableHotkeysInFocus = true;
  1112. enableHotkeysOutOfFocus = true;
  1113. const char *hotkeyFocusType =
  1114. config_get_string(globalConfig, "General", "HotkeyFocusType");
  1115. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1116. enableHotkeysInFocus = false;
  1117. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1118. enableHotkeysOutOfFocus = false;
  1119. }
  1120. if (resetState)
  1121. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1122. }
  1123. void OBSApp::DisableHotkeys()
  1124. {
  1125. enableHotkeysInFocus = false;
  1126. enableHotkeysOutOfFocus = false;
  1127. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1128. }
  1129. Q_DECLARE_METATYPE(VoidFunc)
  1130. void OBSApp::Exec(VoidFunc func)
  1131. {
  1132. func();
  1133. }
  1134. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  1135. {
  1136. auto doTask = [=]() {
  1137. /* to get clang-format to behave */
  1138. task(param);
  1139. };
  1140. QMetaObject::invokeMethod(App(), "Exec",
  1141. wait ? WaitConnection() : Qt::AutoConnection,
  1142. Q_ARG(VoidFunc, doTask));
  1143. }
  1144. bool OBSApp::OBSInit()
  1145. {
  1146. ProfileScope("OBSApp::OBSInit");
  1147. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  1148. setAttribute(Qt::AA_UseHighDpiPixmaps);
  1149. #endif
  1150. qRegisterMetaType<VoidFunc>();
  1151. #if !defined(_WIN32) && !defined(__APPLE__)
  1152. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_GLX);
  1153. if (QApplication::platformName() == "xcb" && getenv("OBS_USE_EGL")) {
  1154. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  1155. blog(LOG_INFO, "Using EGL/X11");
  1156. }
  1157. #ifdef ENABLE_WAYLAND
  1158. if (QApplication::platformName().contains("wayland")) {
  1159. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  1160. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1161. blog(LOG_INFO, "Platform: Wayland");
  1162. }
  1163. #endif
  1164. QPlatformNativeInterface *native =
  1165. QGuiApplication::platformNativeInterface();
  1166. obs_set_nix_platform_display(
  1167. native->nativeResourceForIntegration("display"));
  1168. #endif
  1169. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1170. return false;
  1171. libobs_initialized = true;
  1172. obs_set_ui_task_handler(ui_task_handler);
  1173. #if defined(_WIN32) || defined(__APPLE__)
  1174. bool browserHWAccel =
  1175. config_get_bool(globalConfig, "General", "BrowserHWAccel");
  1176. OBSDataAutoRelease settings = obs_data_create();
  1177. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1178. obs_apply_private_data(settings);
  1179. blog(LOG_INFO, "Current Date/Time: %s",
  1180. CurrentDateTimeString().c_str());
  1181. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1182. browserHWAccel ? "true" : "false");
  1183. #endif
  1184. #ifdef _WIN32
  1185. bool hideFromCapture = config_get_bool(globalConfig, "BasicWindow",
  1186. "HideOBSWindowsFromCapture");
  1187. blog(LOG_INFO, "Hide OBS windows from screen capture: %s",
  1188. hideFromCapture ? "true" : "false");
  1189. #endif
  1190. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(),
  1191. QT_VERSION_STR);
  1192. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1193. setQuitOnLastWindowClosed(false);
  1194. mainWindow = new OBSBasic();
  1195. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1196. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1197. mainWindow->OBSInit();
  1198. connect(this, &QGuiApplication::applicationStateChanged,
  1199. [this](Qt::ApplicationState state) {
  1200. ResetHotkeyState(state == Qt::ApplicationActive);
  1201. });
  1202. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1203. return true;
  1204. }
  1205. string OBSApp::GetVersionString() const
  1206. {
  1207. stringstream ver;
  1208. #ifdef HAVE_OBSCONFIG_H
  1209. ver << OBS_VERSION;
  1210. #else
  1211. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1212. << LIBOBS_API_PATCH_VER;
  1213. #endif
  1214. ver << " (";
  1215. #ifdef _WIN32
  1216. if (sizeof(void *) == 8)
  1217. ver << "64-bit, ";
  1218. else
  1219. ver << "32-bit, ";
  1220. ver << "windows)";
  1221. #elif __APPLE__
  1222. ver << "mac)";
  1223. #elif __OpenBSD__
  1224. ver << "openbsd)";
  1225. #elif __FreeBSD__
  1226. ver << "freebsd)";
  1227. #else /* assume linux for the time being */
  1228. ver << "linux)";
  1229. #endif
  1230. return ver.str();
  1231. }
  1232. bool OBSApp::IsPortableMode()
  1233. {
  1234. return portable_mode;
  1235. }
  1236. bool OBSApp::IsUpdaterDisabled()
  1237. {
  1238. return opt_disable_updater;
  1239. }
  1240. bool OBSApp::IsMissingFilesCheckDisabled()
  1241. {
  1242. return opt_disable_missing_files_check;
  1243. }
  1244. #ifdef __APPLE__
  1245. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1246. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1247. #elif _WIN32
  1248. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1249. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1250. #else
  1251. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1252. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1253. #endif
  1254. const char *OBSApp::InputAudioSource() const
  1255. {
  1256. return INPUT_AUDIO_SOURCE;
  1257. }
  1258. const char *OBSApp::OutputAudioSource() const
  1259. {
  1260. return OUTPUT_AUDIO_SOURCE;
  1261. }
  1262. const char *OBSApp::GetLastLog() const
  1263. {
  1264. return lastLogFile.c_str();
  1265. }
  1266. const char *OBSApp::GetCurrentLog() const
  1267. {
  1268. return currentLogFile.c_str();
  1269. }
  1270. const char *OBSApp::GetLastCrashLog() const
  1271. {
  1272. return lastCrashLogFile.c_str();
  1273. }
  1274. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1275. {
  1276. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1277. if (cb(lookupVal, out))
  1278. return true;
  1279. }
  1280. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1281. }
  1282. // Global handler to receive all QEvent::Show events so we can apply
  1283. // display affinity on any newly created windows and dialogs without
  1284. // caring where they are coming from (e.g. plugins).
  1285. bool OBSApp::notify(QObject *receiver, QEvent *e)
  1286. {
  1287. QWidget *w;
  1288. QWindow *window;
  1289. int windowType;
  1290. if (!receiver->isWidgetType())
  1291. goto skip;
  1292. if (e->type() != QEvent::Show)
  1293. goto skip;
  1294. w = qobject_cast<QWidget *>(receiver);
  1295. if (!w->isWindow())
  1296. goto skip;
  1297. window = w->windowHandle();
  1298. if (!window)
  1299. goto skip;
  1300. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  1301. if (windowType == Qt::WindowType::Dialog ||
  1302. windowType == Qt::WindowType::Window ||
  1303. windowType == Qt::WindowType::Tool) {
  1304. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1305. if (main)
  1306. main->SetDisplayAffinity(window);
  1307. }
  1308. skip:
  1309. return QApplication::notify(receiver, e);
  1310. }
  1311. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1312. const char *disambiguation, int n) const
  1313. {
  1314. const char *out = nullptr;
  1315. if (!App()->TranslateString(sourceText, &out))
  1316. return QString(sourceText);
  1317. UNUSED_PARAMETER(context);
  1318. UNUSED_PARAMETER(disambiguation);
  1319. UNUSED_PARAMETER(n);
  1320. return QT_UTF8(out);
  1321. }
  1322. static bool get_token(lexer *lex, string &str, base_token_type type)
  1323. {
  1324. base_token token;
  1325. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1326. return false;
  1327. if (token.type != type)
  1328. return false;
  1329. str.assign(token.text.array, token.text.len);
  1330. return true;
  1331. }
  1332. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1333. {
  1334. base_token token;
  1335. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1336. return false;
  1337. if (token.type != type)
  1338. return false;
  1339. return strref_cmp(&token.text, str) == 0;
  1340. }
  1341. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1342. {
  1343. BaseLexer lex;
  1344. string year, month, day, hour, minute, second;
  1345. lexer_start(lex, name);
  1346. if (has_prefix) {
  1347. string temp;
  1348. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1349. return 0;
  1350. }
  1351. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1352. return 0;
  1353. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1354. return 0;
  1355. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1356. return 0;
  1357. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1358. return 0;
  1359. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1360. return 0;
  1361. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1362. return 0;
  1363. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1364. return 0;
  1365. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1366. return 0;
  1367. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1368. return 0;
  1369. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1370. return 0;
  1371. stringstream timestring;
  1372. timestring << year << month << day << hour << minute << second;
  1373. return std::stoull(timestring.str());
  1374. }
  1375. static void delete_oldest_file(bool has_prefix, const char *location)
  1376. {
  1377. BPtr<char> logDir(GetConfigPathPtr(location));
  1378. string oldestLog;
  1379. uint64_t oldest_ts = (uint64_t)-1;
  1380. struct os_dirent *entry;
  1381. unsigned int maxLogs = (unsigned int)config_get_uint(
  1382. App()->GlobalConfig(), "General", "MaxLogs");
  1383. os_dir_t *dir = os_opendir(logDir);
  1384. if (dir) {
  1385. unsigned int count = 0;
  1386. while ((entry = os_readdir(dir)) != NULL) {
  1387. if (entry->directory || *entry->d_name == '.')
  1388. continue;
  1389. uint64_t ts =
  1390. convert_log_name(has_prefix, entry->d_name);
  1391. if (ts) {
  1392. if (ts < oldest_ts) {
  1393. oldestLog = entry->d_name;
  1394. oldest_ts = ts;
  1395. }
  1396. count++;
  1397. }
  1398. }
  1399. os_closedir(dir);
  1400. if (count > maxLogs) {
  1401. stringstream delPath;
  1402. delPath << logDir << "/" << oldestLog;
  1403. os_unlink(delPath.str().c_str());
  1404. }
  1405. }
  1406. }
  1407. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1408. std::string &last)
  1409. {
  1410. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1411. struct os_dirent *entry;
  1412. os_dir_t *dir = os_opendir(logDir);
  1413. uint64_t highest_ts = 0;
  1414. if (dir) {
  1415. while ((entry = os_readdir(dir)) != NULL) {
  1416. if (entry->directory || *entry->d_name == '.')
  1417. continue;
  1418. uint64_t ts =
  1419. convert_log_name(has_prefix, entry->d_name);
  1420. if (ts > highest_ts) {
  1421. last = entry->d_name;
  1422. highest_ts = ts;
  1423. }
  1424. }
  1425. os_closedir(dir);
  1426. }
  1427. }
  1428. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1429. {
  1430. time_t now = time(0);
  1431. char file[256] = {};
  1432. struct tm *cur_time;
  1433. cur_time = localtime(&now);
  1434. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1435. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1436. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1437. cur_time->tm_min, cur_time->tm_sec, extension);
  1438. return string(file);
  1439. }
  1440. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1441. const char *format)
  1442. {
  1443. BPtr<char> filename =
  1444. os_generate_formatted_filename(extension, !noSpace, format);
  1445. return string(filename);
  1446. }
  1447. static void FindBestFilename(string &strPath, bool noSpace)
  1448. {
  1449. int num = 2;
  1450. if (!os_file_exists(strPath.c_str()))
  1451. return;
  1452. const char *ext = strrchr(strPath.c_str(), '.');
  1453. if (!ext)
  1454. return;
  1455. int extStart = int(ext - strPath.c_str());
  1456. for (;;) {
  1457. string testPath = strPath;
  1458. string numStr;
  1459. numStr = noSpace ? "_" : " (";
  1460. numStr += to_string(num++);
  1461. if (!noSpace)
  1462. numStr += ")";
  1463. testPath.insert(extStart, numStr);
  1464. if (!os_file_exists(testPath.c_str())) {
  1465. strPath = testPath;
  1466. break;
  1467. }
  1468. }
  1469. }
  1470. static void ensure_directory_exists(string &path)
  1471. {
  1472. replace(path.begin(), path.end(), '\\', '/');
  1473. size_t last = path.rfind('/');
  1474. if (last == string::npos)
  1475. return;
  1476. string directory = path.substr(0, last);
  1477. os_mkdirs(directory.c_str());
  1478. }
  1479. static void remove_reserved_file_characters(string &s)
  1480. {
  1481. replace(s.begin(), s.end(), '\\', '/');
  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. }
  1490. string GetFormatString(const char *format, const char *prefix,
  1491. const char *suffix)
  1492. {
  1493. string f;
  1494. f = format;
  1495. if (prefix && *prefix) {
  1496. string str_prefix = prefix;
  1497. if (str_prefix.back() != ' ')
  1498. str_prefix += " ";
  1499. size_t insert_pos = 0;
  1500. size_t tmp;
  1501. tmp = f.find_last_of('/');
  1502. if (tmp != string::npos && tmp > insert_pos)
  1503. insert_pos = tmp + 1;
  1504. tmp = f.find_last_of('\\');
  1505. if (tmp != string::npos && tmp > insert_pos)
  1506. insert_pos = tmp + 1;
  1507. f.insert(insert_pos, str_prefix);
  1508. }
  1509. if (suffix && *suffix) {
  1510. if (*suffix != ' ')
  1511. f += " ";
  1512. f += suffix;
  1513. }
  1514. remove_reserved_file_characters(f);
  1515. return f;
  1516. }
  1517. string GetOutputFilename(const char *path, const char *ext, bool noSpace,
  1518. bool overwrite, const char *format)
  1519. {
  1520. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1521. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1522. if (!dir) {
  1523. if (main->isVisible())
  1524. OBSMessageBox::warning(main,
  1525. QTStr("Output.BadPath.Title"),
  1526. QTStr("Output.BadPath.Text"));
  1527. else
  1528. main->SysTrayNotify(QTStr("Output.BadPath.Text"),
  1529. QSystemTrayIcon::Warning);
  1530. return "";
  1531. }
  1532. os_closedir(dir);
  1533. string strPath;
  1534. strPath += path;
  1535. char lastChar = strPath.back();
  1536. if (lastChar != '/' && lastChar != '\\')
  1537. strPath += "/";
  1538. strPath += GenerateSpecifiedFilename(ext, noSpace, format);
  1539. ensure_directory_exists(strPath);
  1540. if (!overwrite)
  1541. FindBestFilename(strPath, noSpace);
  1542. return strPath;
  1543. }
  1544. vector<pair<string, string>> GetLocaleNames()
  1545. {
  1546. string path;
  1547. if (!GetDataFilePath("locale.ini", path))
  1548. throw "Could not find locale.ini path";
  1549. ConfigFile ini;
  1550. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1551. throw "Could not open locale.ini";
  1552. size_t sections = config_num_sections(ini);
  1553. vector<pair<string, string>> names;
  1554. names.reserve(sections);
  1555. for (size_t i = 0; i < sections; i++) {
  1556. const char *tag = config_get_section(ini, i);
  1557. const char *name = config_get_string(ini, tag, "Name");
  1558. names.emplace_back(tag, name);
  1559. }
  1560. return names;
  1561. }
  1562. static void create_log_file(fstream &logFile)
  1563. {
  1564. stringstream dst;
  1565. get_last_log(false, "obs-studio/logs", lastLogFile);
  1566. #ifdef _WIN32
  1567. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1568. #endif
  1569. currentLogFile = GenerateTimeDateFilename("txt");
  1570. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1571. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1572. #ifdef _WIN32
  1573. BPtr<wchar_t> wpath;
  1574. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1575. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1576. #else
  1577. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1578. #endif
  1579. if (logFile.is_open()) {
  1580. delete_oldest_file(false, "obs-studio/logs");
  1581. base_set_log_handler(do_log, &logFile);
  1582. } else {
  1583. blog(LOG_ERROR, "Failed to open log file");
  1584. }
  1585. }
  1586. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1587. profiler_name_store_free(store);
  1588. };
  1589. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1590. decltype(ProfilerNameStoreRelease)>;
  1591. ProfilerNameStore CreateNameStore()
  1592. {
  1593. return ProfilerNameStore{profiler_name_store_create(),
  1594. ProfilerNameStoreRelease};
  1595. }
  1596. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1597. profile_snapshot_free(snap);
  1598. };
  1599. using ProfilerSnapshot =
  1600. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1601. ProfilerSnapshot GetSnapshot()
  1602. {
  1603. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1604. }
  1605. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1606. {
  1607. if (currentLogFile.empty())
  1608. return;
  1609. auto pos = currentLogFile.rfind('.');
  1610. if (pos == currentLogFile.npos)
  1611. return;
  1612. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1613. ostringstream dst;
  1614. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1615. dst.write(currentLogFile.c_str(), pos);
  1616. dst.write(LITERAL_SIZE(".csv.gz"));
  1617. #undef LITERAL_SIZE
  1618. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1619. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1620. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1621. static_cast<const char *>(path));
  1622. }
  1623. static auto ProfilerFree = [](void *) {
  1624. profiler_stop();
  1625. auto snap = GetSnapshot();
  1626. profiler_print(snap.get());
  1627. profiler_print_time_between_calls(snap.get());
  1628. SaveProfilerData(snap);
  1629. profiler_free();
  1630. };
  1631. QAccessibleInterface *accessibleFactory(const QString &classname,
  1632. QObject *object)
  1633. {
  1634. if (classname == QLatin1String("VolumeSlider") && object &&
  1635. object->isWidgetType())
  1636. return new VolumeAccessibleInterface(
  1637. static_cast<QWidget *>(object));
  1638. return nullptr;
  1639. }
  1640. static const char *run_program_init = "run_program_init";
  1641. static int run_program(fstream &logFile, int argc, char *argv[])
  1642. {
  1643. int ret = -1;
  1644. auto profilerNameStore = CreateNameStore();
  1645. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1646. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1647. profiler_start();
  1648. profile_register_root(run_program_init, 0);
  1649. ScopeProfiler prof{run_program_init};
  1650. #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  1651. QGuiApplication::setAttribute(opt_disable_high_dpi_scaling
  1652. ? Qt::AA_DisableHighDpiScaling
  1653. : Qt::AA_EnableHighDpiScaling);
  1654. #endif
  1655. #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) && defined(_WIN32)
  1656. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
  1657. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1658. #endif
  1659. QCoreApplication::addLibraryPath(".");
  1660. #if __APPLE__
  1661. InstallNSApplicationSubclass();
  1662. #endif
  1663. #if !defined(_WIN32) && !defined(__APPLE__) && defined(USE_XDG) && \
  1664. defined(ENABLE_WAYLAND)
  1665. /* NOTE: Qt doesn't use the Wayland platform on GNOME, so we have to
  1666. * force it using the QT_QPA_PLATFORM env var. It's still possible to
  1667. * use other QPA platforms using this env var, or the -platform command
  1668. * line option. */
  1669. const char *session_type = getenv("XDG_SESSION_TYPE");
  1670. if (session_type && strcmp(session_type, "wayland") == 0)
  1671. setenv("QT_QPA_PLATFORM", "wayland", false);
  1672. #endif
  1673. OBSApp program(argc, argv, profilerNameStore.get());
  1674. try {
  1675. QAccessible::installFactory(accessibleFactory);
  1676. bool created_log = false;
  1677. program.AppInit();
  1678. delete_oldest_file(false, "obs-studio/profiler_data");
  1679. OBSTranslator translator;
  1680. program.installTranslator(&translator);
  1681. /* --------------------------------------- */
  1682. /* check and warn if already running */
  1683. bool cancel_launch = false;
  1684. bool already_running = false;
  1685. #if defined(_WIN32)
  1686. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1687. #elif defined(__APPLE__)
  1688. CheckAppWithSameBundleID(already_running);
  1689. #elif defined(__linux__)
  1690. RunningInstanceCheck(already_running);
  1691. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  1692. PIDFileCheck(already_running);
  1693. #endif
  1694. if (!already_running) {
  1695. goto run;
  1696. }
  1697. if (!multi) {
  1698. QMessageBox::StandardButtons buttons(
  1699. QMessageBox::Yes | QMessageBox::Cancel);
  1700. QMessageBox mb(QMessageBox::Question,
  1701. QTStr("AlreadyRunning.Title"),
  1702. QTStr("AlreadyRunning.Text"), buttons,
  1703. nullptr);
  1704. mb.setButtonText(QMessageBox::Yes,
  1705. QTStr("AlreadyRunning.LaunchAnyway"));
  1706. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1707. mb.setDefaultButton(QMessageBox::Cancel);
  1708. QMessageBox::StandardButton button;
  1709. button = (QMessageBox::StandardButton)mb.exec();
  1710. cancel_launch = button == QMessageBox::Cancel;
  1711. }
  1712. if (cancel_launch)
  1713. return 0;
  1714. if (!created_log) {
  1715. create_log_file(logFile);
  1716. created_log = true;
  1717. }
  1718. if (multi) {
  1719. blog(LOG_INFO, "User enabled --multi flag and is now "
  1720. "running multiple instances of OBS.");
  1721. } else {
  1722. blog(LOG_WARNING, "================================");
  1723. blog(LOG_WARNING, "Warning: OBS is already running!");
  1724. blog(LOG_WARNING, "================================");
  1725. blog(LOG_WARNING, "User is now running multiple "
  1726. "instances of OBS!");
  1727. }
  1728. /* --------------------------------------- */
  1729. run:
  1730. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1731. // Mounted by termina during chromeOS linux container startup
  1732. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1733. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1734. if (crosDir) {
  1735. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1736. QMessageBox mb(QMessageBox::Critical,
  1737. QTStr("ChromeOS.Title"),
  1738. QTStr("ChromeOS.Text"), buttons,
  1739. nullptr);
  1740. mb.exec();
  1741. return 0;
  1742. }
  1743. #endif
  1744. if (!created_log) {
  1745. create_log_file(logFile);
  1746. created_log = true;
  1747. }
  1748. #ifdef __APPLE__
  1749. bool rosettaTranslated = ProcessIsRosettaTranslated();
  1750. blog(LOG_INFO, "Rosetta translation used: %s",
  1751. rosettaTranslated ? "true" : "false");
  1752. #endif
  1753. #ifdef _WIN32
  1754. if (IsRunningOnWine()) {
  1755. QMessageBox mb(QMessageBox::Question,
  1756. QTStr("Wine.Title"), QTStr("Wine.Text"));
  1757. mb.setTextFormat(Qt::RichText);
  1758. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"),
  1759. QMessageBox::AcceptRole);
  1760. QPushButton *closeButton =
  1761. mb.addButton(QMessageBox::Close);
  1762. mb.setDefaultButton(closeButton);
  1763. mb.exec();
  1764. if (mb.clickedButton() == closeButton)
  1765. return 0;
  1766. }
  1767. #endif
  1768. if (argc > 1) {
  1769. stringstream stor;
  1770. stor << argv[1];
  1771. for (int i = 2; i < argc; ++i) {
  1772. stor << " " << argv[i];
  1773. }
  1774. blog(LOG_INFO, "Command Line Arguments: %s",
  1775. stor.str().c_str());
  1776. }
  1777. if (!program.OBSInit())
  1778. return 0;
  1779. prof.Stop();
  1780. ret = program.exec();
  1781. } catch (const char *error) {
  1782. blog(LOG_ERROR, "%s", error);
  1783. OBSErrorBox(nullptr, "%s", error);
  1784. }
  1785. if (restart)
  1786. QProcess::startDetached(qApp->arguments()[0],
  1787. qApp->arguments());
  1788. return ret;
  1789. }
  1790. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1791. #ifdef _WIN32
  1792. #define CRASH_MESSAGE \
  1793. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1794. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1795. static void main_crash_handler(const char *format, va_list args, void *param)
  1796. {
  1797. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1798. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1799. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1800. string crashFilePath = "obs-studio/crashes";
  1801. delete_oldest_file(true, crashFilePath.c_str());
  1802. string name = crashFilePath + "/";
  1803. name += "Crash " + GenerateTimeDateFilename("txt");
  1804. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1805. fstream file;
  1806. #ifdef _WIN32
  1807. BPtr<wchar_t> wpath;
  1808. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1809. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1810. ios_base::binary);
  1811. #else
  1812. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1813. ios_base::binary);
  1814. #endif
  1815. file << text;
  1816. file.close();
  1817. string pathString(path.Get());
  1818. #ifdef _WIN32
  1819. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1820. #endif
  1821. string absolutePath =
  1822. canonical(filesystem::path(pathString)).u8string();
  1823. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1824. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1825. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
  1826. absolutePath.c_str());
  1827. string finalMessage =
  1828. string(message_buffer.get(), message_buffer.get() + size);
  1829. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
  1830. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1831. if (ret == IDYES) {
  1832. size_t len = strlen(text);
  1833. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1834. memcpy(GlobalLock(mem), text, len);
  1835. GlobalUnlock(mem);
  1836. OpenClipboard(0);
  1837. EmptyClipboard();
  1838. SetClipboardData(CF_TEXT, mem);
  1839. CloseClipboard();
  1840. }
  1841. exit(-1);
  1842. UNUSED_PARAMETER(param);
  1843. }
  1844. static void load_debug_privilege(void)
  1845. {
  1846. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1847. TOKEN_PRIVILEGES tp;
  1848. HANDLE token;
  1849. LUID val;
  1850. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1851. return;
  1852. }
  1853. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1854. tp.PrivilegeCount = 1;
  1855. tp.Privileges[0].Luid = val;
  1856. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1857. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1858. NULL);
  1859. }
  1860. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1861. tp.PrivilegeCount = 1;
  1862. tp.Privileges[0].Luid = val;
  1863. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1864. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1865. NULL)) {
  1866. blog(LOG_INFO, "Could not set privilege to "
  1867. "increase GPU priority");
  1868. }
  1869. }
  1870. CloseHandle(token);
  1871. }
  1872. #endif
  1873. #ifdef __APPLE__
  1874. #define BASE_PATH ".."
  1875. #else
  1876. #define BASE_PATH "../.."
  1877. #endif
  1878. #define CONFIG_PATH BASE_PATH "/config"
  1879. #ifndef OBS_UNIX_STRUCTURE
  1880. #define OBS_UNIX_STRUCTURE 0
  1881. #endif
  1882. int GetConfigPath(char *path, size_t size, const char *name)
  1883. {
  1884. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1885. if (name && *name) {
  1886. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1887. } else {
  1888. return snprintf(path, size, CONFIG_PATH);
  1889. }
  1890. } else {
  1891. return os_get_config_path(path, size, name);
  1892. }
  1893. }
  1894. char *GetConfigPathPtr(const char *name)
  1895. {
  1896. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1897. char path[512];
  1898. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1899. return bstrdup(path);
  1900. } else {
  1901. return NULL;
  1902. }
  1903. } else {
  1904. return os_get_config_path_ptr(name);
  1905. }
  1906. }
  1907. int GetProgramDataPath(char *path, size_t size, const char *name)
  1908. {
  1909. return os_get_program_data_path(path, size, name);
  1910. }
  1911. char *GetProgramDataPathPtr(const char *name)
  1912. {
  1913. return os_get_program_data_path_ptr(name);
  1914. }
  1915. bool GetFileSafeName(const char *name, std::string &file)
  1916. {
  1917. size_t base_len = strlen(name);
  1918. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1919. std::wstring wfile;
  1920. if (!len)
  1921. return false;
  1922. wfile.resize(len);
  1923. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1924. for (size_t i = wfile.size(); i > 0; i--) {
  1925. size_t im1 = i - 1;
  1926. if (iswspace(wfile[im1])) {
  1927. wfile[im1] = '_';
  1928. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1929. wfile.erase(im1, 1);
  1930. }
  1931. }
  1932. if (wfile.size() == 0)
  1933. wfile = L"characters_only";
  1934. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1935. if (!len)
  1936. return false;
  1937. file.resize(len);
  1938. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1939. return true;
  1940. }
  1941. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1942. {
  1943. size_t len = path.size();
  1944. if (extension) {
  1945. path += ".";
  1946. path += extension;
  1947. }
  1948. if (!os_file_exists(path.c_str()))
  1949. return true;
  1950. int index = 1;
  1951. do {
  1952. path.resize(len);
  1953. path += std::to_string(++index);
  1954. if (extension) {
  1955. path += ".";
  1956. path += extension;
  1957. }
  1958. } while (os_file_exists(path.c_str()));
  1959. return true;
  1960. }
  1961. bool GetUnusedSceneCollectionFile(std::string &name, std::string &file)
  1962. {
  1963. char path[512];
  1964. int ret;
  1965. if (!GetFileSafeName(name.c_str(), file)) {
  1966. blog(LOG_WARNING, "Failed to create safe file name for '%s'",
  1967. name.c_str());
  1968. return false;
  1969. }
  1970. ret = GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes/");
  1971. if (ret <= 0) {
  1972. blog(LOG_WARNING, "Failed to get scene collection config path");
  1973. return false;
  1974. }
  1975. file.insert(0, path);
  1976. if (!GetClosestUnusedFileName(file, "json")) {
  1977. blog(LOG_WARNING, "Failed to get closest file name for %s",
  1978. file.c_str());
  1979. return false;
  1980. }
  1981. file.erase(file.size() - 5, 5);
  1982. file.erase(0, strlen(path));
  1983. return true;
  1984. }
  1985. bool WindowPositionValid(QRect rect)
  1986. {
  1987. for (QScreen *screen : QGuiApplication::screens()) {
  1988. if (screen->availableGeometry().intersects(rect))
  1989. return true;
  1990. }
  1991. return false;
  1992. }
  1993. static inline bool arg_is(const char *arg, const char *long_form,
  1994. const char *short_form)
  1995. {
  1996. return (long_form && strcmp(arg, long_form) == 0) ||
  1997. (short_form && strcmp(arg, short_form) == 0);
  1998. }
  1999. #if !defined(_WIN32) && !defined(__APPLE__)
  2000. #define IS_UNIX 1
  2001. #endif
  2002. /* if using XDG and was previously using an older build of OBS, move config
  2003. * files to XDG directory */
  2004. #if defined(USE_XDG) && defined(IS_UNIX)
  2005. static void move_to_xdg(void)
  2006. {
  2007. char old_path[512];
  2008. char new_path[512];
  2009. char *home = getenv("HOME");
  2010. if (!home)
  2011. return;
  2012. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  2013. return;
  2014. /* make base xdg path if it doesn't already exist */
  2015. if (GetConfigPath(new_path, 512, "") <= 0)
  2016. return;
  2017. if (os_mkdirs(new_path) == MKDIR_ERROR)
  2018. return;
  2019. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  2020. return;
  2021. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  2022. rename(old_path, new_path);
  2023. }
  2024. }
  2025. #endif
  2026. static bool update_ffmpeg_output(ConfigFile &config)
  2027. {
  2028. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  2029. return false;
  2030. const char *url = config_get_string(config, "AdvOut", "FFURL");
  2031. if (!url)
  2032. return false;
  2033. bool isActualURL = strstr(url, "://") != nullptr;
  2034. if (isActualURL)
  2035. return false;
  2036. string urlStr = url;
  2037. string extension;
  2038. for (size_t i = urlStr.length(); i > 0; i--) {
  2039. size_t idx = i - 1;
  2040. if (urlStr[idx] == '.') {
  2041. extension = &urlStr[i];
  2042. }
  2043. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  2044. urlStr[idx] = 0;
  2045. break;
  2046. }
  2047. }
  2048. if (urlStr.empty() || extension.empty())
  2049. return false;
  2050. config_remove_value(config, "AdvOut", "FFURL");
  2051. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  2052. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  2053. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  2054. return true;
  2055. }
  2056. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  2057. {
  2058. bool changed = false;
  2059. if (config_has_user_value(config, sec, "Reconnect")) {
  2060. bool reconnect = config_get_bool(config, sec, "Reconnect");
  2061. config_set_bool(config, "Output", "Reconnect", reconnect);
  2062. changed = true;
  2063. }
  2064. if (config_has_user_value(config, sec, "RetryDelay")) {
  2065. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  2066. config_set_uint(config, "Output", "RetryDelay", delay);
  2067. changed = true;
  2068. }
  2069. if (config_has_user_value(config, sec, "MaxRetries")) {
  2070. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  2071. config_set_uint(config, "Output", "MaxRetries", retries);
  2072. changed = true;
  2073. }
  2074. return changed;
  2075. }
  2076. static bool update_reconnect(ConfigFile &config)
  2077. {
  2078. if (!config_has_user_value(config, "Output", "Mode"))
  2079. return false;
  2080. const char *mode = config_get_string(config, "Output", "Mode");
  2081. if (!mode)
  2082. return false;
  2083. const char *section = (strcmp(mode, "Advanced") == 0) ? "AdvOut"
  2084. : "SimpleOutput";
  2085. if (move_reconnect_settings(config, section)) {
  2086. config_remove_value(config, "SimpleOutput", "Reconnect");
  2087. config_remove_value(config, "SimpleOutput", "RetryDelay");
  2088. config_remove_value(config, "SimpleOutput", "MaxRetries");
  2089. config_remove_value(config, "AdvOut", "Reconnect");
  2090. config_remove_value(config, "AdvOut", "RetryDelay");
  2091. config_remove_value(config, "AdvOut", "MaxRetries");
  2092. return true;
  2093. }
  2094. return false;
  2095. }
  2096. static void convert_x264_settings(obs_data_t *data)
  2097. {
  2098. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  2099. if (use_bufsize) {
  2100. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  2101. if (buffer_size == 0)
  2102. obs_data_set_string(data, "rate_control", "CRF");
  2103. }
  2104. }
  2105. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  2106. {
  2107. OBSDataAutoRelease data =
  2108. obs_data_create_from_json_file_safe(file, "bak");
  2109. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  2110. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  2111. bool modified = false;
  2112. bool cbr = true;
  2113. if (cbr_item) {
  2114. cbr = obs_data_item_get_bool(cbr_item);
  2115. obs_data_item_unset_user_value(cbr_item);
  2116. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  2117. modified = true;
  2118. }
  2119. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  2120. if (!cbr_item)
  2121. obs_data_set_string(data, "rate_control", "CBR");
  2122. else if (!cbr)
  2123. convert_x264_settings(data);
  2124. modified = true;
  2125. }
  2126. if (modified)
  2127. obs_data_save_json_safe(data, file, "tmp", "bak");
  2128. obs_data_item_release(&rc_item);
  2129. obs_data_item_release(&cbr_item);
  2130. }
  2131. static void upgrade_settings(void)
  2132. {
  2133. char path[512];
  2134. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  2135. if (pathlen <= 0)
  2136. return;
  2137. if (!os_file_exists(path))
  2138. return;
  2139. os_dir_t *dir = os_opendir(path);
  2140. if (!dir)
  2141. return;
  2142. struct os_dirent *ent = os_readdir(dir);
  2143. while (ent) {
  2144. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  2145. strcmp(ent->d_name, "..") != 0) {
  2146. strcat(path, "/");
  2147. strcat(path, ent->d_name);
  2148. strcat(path, "/basic.ini");
  2149. ConfigFile config;
  2150. int ret;
  2151. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  2152. if (ret == CONFIG_SUCCESS) {
  2153. if (update_ffmpeg_output(config) ||
  2154. update_reconnect(config)) {
  2155. config_save_safe(config, "tmp",
  2156. nullptr);
  2157. }
  2158. }
  2159. if (config) {
  2160. const char *sEnc = config_get_string(
  2161. config, "AdvOut", "Encoder");
  2162. const char *rEnc = config_get_string(
  2163. config, "AdvOut", "RecEncoder");
  2164. /* replace "cbr" option with "rate_control" for
  2165. * each profile's encoder data */
  2166. path[pathlen] = 0;
  2167. strcat(path, "/");
  2168. strcat(path, ent->d_name);
  2169. strcat(path, "/recordEncoder.json");
  2170. convert_14_2_encoder_setting(rEnc, path);
  2171. path[pathlen] = 0;
  2172. strcat(path, "/");
  2173. strcat(path, ent->d_name);
  2174. strcat(path, "/streamEncoder.json");
  2175. convert_14_2_encoder_setting(sEnc, path);
  2176. }
  2177. path[pathlen] = 0;
  2178. }
  2179. ent = os_readdir(dir);
  2180. }
  2181. os_closedir(dir);
  2182. }
  2183. void ctrlc_handler(int s)
  2184. {
  2185. UNUSED_PARAMETER(s);
  2186. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  2187. main->close();
  2188. }
  2189. int main(int argc, char *argv[])
  2190. {
  2191. #ifndef _WIN32
  2192. signal(SIGPIPE, SIG_IGN);
  2193. struct sigaction sig_handler;
  2194. sig_handler.sa_handler = ctrlc_handler;
  2195. sigemptyset(&sig_handler.sa_mask);
  2196. sig_handler.sa_flags = 0;
  2197. sigaction(SIGINT, &sig_handler, NULL);
  2198. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  2199. a closed pipe. */
  2200. sigset_t sigpipe_mask;
  2201. sigemptyset(&sigpipe_mask);
  2202. sigaddset(&sigpipe_mask, SIGPIPE);
  2203. sigset_t saved_mask;
  2204. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  2205. perror("pthread_sigmask");
  2206. exit(1);
  2207. }
  2208. #endif
  2209. #ifdef _WIN32
  2210. obs_init_win32_crash_handler();
  2211. SetErrorMode(SEM_FAILCRITICALERRORS);
  2212. load_debug_privilege();
  2213. base_set_crash_handler(main_crash_handler, nullptr);
  2214. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  2215. if (hRtwq) {
  2216. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  2217. PFN_RtwqStartup func =
  2218. (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  2219. func();
  2220. }
  2221. #endif
  2222. base_get_log_handler(&def_log_handler, nullptr);
  2223. #if defined(USE_XDG) && defined(IS_UNIX)
  2224. move_to_xdg();
  2225. #endif
  2226. obs_set_cmdline_args(argc, argv);
  2227. for (int i = 1; i < argc; i++) {
  2228. if (arg_is(argv[i], "--portable", "-p")) {
  2229. portable_mode = true;
  2230. } else if (arg_is(argv[i], "--multi", "-m")) {
  2231. multi = true;
  2232. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2233. log_verbose = true;
  2234. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2235. opt_always_on_top = true;
  2236. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2237. unfiltered_log = true;
  2238. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2239. opt_start_streaming = true;
  2240. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2241. opt_start_recording = true;
  2242. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2243. opt_start_replaybuffer = true;
  2244. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2245. opt_start_virtualcam = true;
  2246. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2247. if (++i < argc)
  2248. opt_starting_collection = argv[i];
  2249. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2250. if (++i < argc)
  2251. opt_starting_profile = argv[i];
  2252. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2253. if (++i < argc)
  2254. opt_starting_scene = argv[i];
  2255. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2256. opt_minimize_tray = true;
  2257. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2258. opt_studio_mode = true;
  2259. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2260. opt_allow_opengl = true;
  2261. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2262. opt_disable_updater = true;
  2263. } else if (arg_is(argv[i], "--disable-missing-files-check",
  2264. nullptr)) {
  2265. opt_disable_missing_files_check = true;
  2266. } else if (arg_is(argv[i], "--disable-high-dpi-scaling",
  2267. nullptr)) {
  2268. opt_disable_high_dpi_scaling = true;
  2269. } else if (arg_is(argv[i], "--help", "-h")) {
  2270. std::string help =
  2271. "--help, -h: Get list of available commands.\n\n"
  2272. "--startstreaming: Automatically start streaming.\n"
  2273. "--startrecording: Automatically start recording.\n"
  2274. "--startreplaybuffer: Start replay buffer.\n"
  2275. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2276. "--collection <string>: Use specific scene collection."
  2277. "\n"
  2278. "--profile <string>: Use specific profile.\n"
  2279. "--scene <string>: Start with specific scene.\n\n"
  2280. "--studio-mode: Enable studio mode.\n"
  2281. "--minimize-to-tray: Minimize to system tray.\n"
  2282. "--portable, -p: Use portable mode.\n"
  2283. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2284. "--verbose: Make log more verbose.\n"
  2285. "--always-on-top: Start in 'always on top' mode.\n\n"
  2286. "--unfiltered_log: Make log unfiltered.\n\n"
  2287. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2288. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n"
  2289. "--disable-high-dpi-scaling: Disable automatic high-DPI scaling\n\n";
  2290. #ifdef _WIN32
  2291. MessageBoxA(NULL, help.c_str(), "Help",
  2292. MB_OK | MB_ICONASTERISK);
  2293. #else
  2294. std::cout << help
  2295. << "--version, -V: Get current version.\n";
  2296. #endif
  2297. exit(0);
  2298. } else if (arg_is(argv[i], "--version", "-V")) {
  2299. std::cout << "OBS Studio - "
  2300. << App()->GetVersionString() << "\n";
  2301. exit(0);
  2302. }
  2303. }
  2304. #if !OBS_UNIX_STRUCTURE
  2305. if (!portable_mode) {
  2306. portable_mode =
  2307. os_file_exists(BASE_PATH "/portable_mode") ||
  2308. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2309. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2310. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2311. }
  2312. if (!opt_disable_updater) {
  2313. opt_disable_updater =
  2314. os_file_exists(BASE_PATH "/disable_updater") ||
  2315. os_file_exists(BASE_PATH "/disable_updater.txt");
  2316. }
  2317. if (!opt_disable_missing_files_check) {
  2318. opt_disable_missing_files_check =
  2319. os_file_exists(BASE_PATH
  2320. "/disable_missing_files_check") ||
  2321. os_file_exists(BASE_PATH
  2322. "/disable_missing_files_check.txt");
  2323. }
  2324. #endif
  2325. upgrade_settings();
  2326. fstream logFile;
  2327. curl_global_init(CURL_GLOBAL_ALL);
  2328. int ret = run_program(logFile, argc, argv);
  2329. #ifdef _WIN32
  2330. if (hRtwq) {
  2331. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  2332. PFN_RtwqShutdown func =
  2333. (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  2334. func();
  2335. FreeLibrary(hRtwq);
  2336. }
  2337. #endif
  2338. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2339. base_set_log_handler(nullptr, nullptr);
  2340. return ret;
  2341. }