obs-app.cpp 59 KB

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