obs-app.cpp 55 KB

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