obs-app.cpp 60 KB

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