obs-app.cpp 54 KB

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