obs-app.cpp 56 KB

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