obs-app.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295
  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, "BasicWindow",
  587. "MultiviewLayout")) {
  588. const char *layout = config_get_string(globalConfig,
  589. "BasicWindow", "MultiviewLayout");
  590. changed |= UpdatePre22MultiviewLayout(layout);
  591. }
  592. if (changed)
  593. config_save_safe(globalConfig, "tmp", nullptr);
  594. return InitGlobalConfigDefaults();
  595. }
  596. bool OBSApp::InitLocale()
  597. {
  598. ProfileScope("OBSApp::InitLocale");
  599. const char *lang = config_get_string(globalConfig, "General",
  600. "Language");
  601. locale = lang;
  602. string englishPath;
  603. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  604. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  605. return false;
  606. }
  607. textLookup = text_lookup_create(englishPath.c_str());
  608. if (!textLookup) {
  609. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  610. englishPath.c_str());
  611. return false;
  612. }
  613. bool userLocale = config_has_user_value(globalConfig, "General",
  614. "Language");
  615. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  616. if (userLocale && defaultLang)
  617. return true;
  618. if (!userLocale && defaultLang) {
  619. for (auto &locale_ : GetPreferredLocales()) {
  620. if (locale_ == lang)
  621. return true;
  622. stringstream file;
  623. file << "locale/" << locale_ << ".ini";
  624. string path;
  625. if (!GetDataFilePath(file.str().c_str(), path))
  626. continue;
  627. if (!text_lookup_add(textLookup, path.c_str()))
  628. continue;
  629. blog(LOG_INFO, "Using preferred locale '%s'",
  630. locale_.c_str());
  631. locale = locale_;
  632. return true;
  633. }
  634. return true;
  635. }
  636. stringstream file;
  637. file << "locale/" << lang << ".ini";
  638. string path;
  639. if (GetDataFilePath(file.str().c_str(), path)) {
  640. if (!text_lookup_add(textLookup, path.c_str()))
  641. blog(LOG_ERROR, "Failed to add locale file '%s'",
  642. path.c_str());
  643. } else {
  644. blog(LOG_ERROR, "Could not find locale file '%s'",
  645. file.str().c_str());
  646. }
  647. return true;
  648. }
  649. void OBSApp::AddExtraThemeColor(QPalette &pal, int group,
  650. const char *name, uint32_t color)
  651. {
  652. std::function<void(QPalette::ColorGroup)> func;
  653. #define DEF_PALETTE_ASSIGN(name) \
  654. do { \
  655. func = [&] (QPalette::ColorGroup group) \
  656. { \
  657. pal.setColor(group, QPalette::name, \
  658. QColor::fromRgb(color)); \
  659. }; \
  660. } while (false)
  661. if (astrcmpi(name, "alternateBase") == 0) {
  662. DEF_PALETTE_ASSIGN(AlternateBase);
  663. } else if (astrcmpi(name, "base") == 0) {
  664. DEF_PALETTE_ASSIGN(Base);
  665. } else if (astrcmpi(name, "brightText") == 0) {
  666. DEF_PALETTE_ASSIGN(BrightText);
  667. } else if (astrcmpi(name, "button") == 0) {
  668. DEF_PALETTE_ASSIGN(Button);
  669. } else if (astrcmpi(name, "buttonText") == 0) {
  670. DEF_PALETTE_ASSIGN(ButtonText);
  671. } else if (astrcmpi(name, "brightText") == 0) {
  672. DEF_PALETTE_ASSIGN(BrightText);
  673. } else if (astrcmpi(name, "dark") == 0) {
  674. DEF_PALETTE_ASSIGN(Dark);
  675. } else if (astrcmpi(name, "highlight") == 0) {
  676. DEF_PALETTE_ASSIGN(Highlight);
  677. } else if (astrcmpi(name, "highlightedText") == 0) {
  678. DEF_PALETTE_ASSIGN(HighlightedText);
  679. } else if (astrcmpi(name, "light") == 0) {
  680. DEF_PALETTE_ASSIGN(Light);
  681. } else if (astrcmpi(name, "link") == 0) {
  682. DEF_PALETTE_ASSIGN(Link);
  683. } else if (astrcmpi(name, "linkVisited") == 0) {
  684. DEF_PALETTE_ASSIGN(LinkVisited);
  685. } else if (astrcmpi(name, "mid") == 0) {
  686. DEF_PALETTE_ASSIGN(Mid);
  687. } else if (astrcmpi(name, "midlight") == 0) {
  688. DEF_PALETTE_ASSIGN(Midlight);
  689. } else if (astrcmpi(name, "shadow") == 0) {
  690. DEF_PALETTE_ASSIGN(Shadow);
  691. } else if (astrcmpi(name, "text") == 0 ||
  692. astrcmpi(name, "foreground") == 0) {
  693. DEF_PALETTE_ASSIGN(Text);
  694. } else if (astrcmpi(name, "toolTipBase") == 0) {
  695. DEF_PALETTE_ASSIGN(ToolTipBase);
  696. } else if (astrcmpi(name, "toolTipText") == 0) {
  697. DEF_PALETTE_ASSIGN(ToolTipText);
  698. } else if (astrcmpi(name, "windowText") == 0) {
  699. DEF_PALETTE_ASSIGN(WindowText);
  700. } else if (astrcmpi(name, "window") == 0 ||
  701. astrcmpi(name, "background") == 0) {
  702. DEF_PALETTE_ASSIGN(Window);
  703. } else {
  704. return;
  705. }
  706. #undef DEF_PALETTE_ASSIGN
  707. switch (group) {
  708. case QPalette::Disabled:
  709. case QPalette::Active:
  710. case QPalette::Inactive:
  711. func((QPalette::ColorGroup)group);
  712. break;
  713. default:
  714. func((QPalette::ColorGroup)QPalette::Disabled);
  715. func((QPalette::ColorGroup)QPalette::Active);
  716. func((QPalette::ColorGroup)QPalette::Inactive);
  717. }
  718. }
  719. struct CFParser {
  720. cf_parser cfp = {};
  721. inline ~CFParser() {cf_parser_free(&cfp);}
  722. inline operator cf_parser*() {return &cfp;}
  723. inline cf_parser *operator->() {return &cfp;}
  724. };
  725. void OBSApp::ParseExtraThemeData(const char *path)
  726. {
  727. BPtr<char> data = os_quick_read_utf8_file(path);
  728. QPalette pal = palette();
  729. CFParser cfp;
  730. int ret;
  731. cf_parser_parse(cfp, data, path);
  732. while (cf_go_to_token(cfp, "OBSTheme", nullptr)) {
  733. if (!cf_next_token(cfp)) return;
  734. int group = -1;
  735. if (cf_token_is(cfp, ":")) {
  736. ret = cf_next_token_should_be(cfp, ":", nullptr,
  737. nullptr);
  738. if (ret != PARSE_SUCCESS) continue;
  739. if (!cf_next_token(cfp)) return;
  740. if (cf_token_is(cfp, "disabled")) {
  741. group = QPalette::Disabled;
  742. } else if (cf_token_is(cfp, "active")) {
  743. group = QPalette::Active;
  744. } else if (cf_token_is(cfp, "inactive")) {
  745. group = QPalette::Inactive;
  746. } else {
  747. continue;
  748. }
  749. if (!cf_next_token(cfp)) return;
  750. }
  751. if (!cf_token_is(cfp, "{")) continue;
  752. for (;;) {
  753. if (!cf_next_token(cfp)) return;
  754. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name",
  755. nullptr);
  756. if (ret != PARSE_SUCCESS)
  757. break;
  758. DStr name;
  759. dstr_copy_strref(name, &cfp->cur_token->str);
  760. ret = cf_next_token_should_be(cfp, ":", ";",
  761. nullptr);
  762. if (ret != PARSE_SUCCESS) continue;
  763. if (!cf_next_token(cfp)) return;
  764. const char *array;
  765. uint32_t color = 0;
  766. if (cf_token_is(cfp, "#")) {
  767. array = cfp->cur_token->str.array;
  768. color = strtol(array + 1, nullptr, 16);
  769. } else if (cf_token_is(cfp, "rgb")) {
  770. ret = cf_next_token_should_be(cfp, "(", ";",
  771. nullptr);
  772. if (ret != PARSE_SUCCESS) continue;
  773. if (!cf_next_token(cfp)) return;
  774. array = cfp->cur_token->str.array;
  775. color |= strtol(array, nullptr, 10) << 16;
  776. ret = cf_next_token_should_be(cfp, ",", ";",
  777. nullptr);
  778. if (ret != PARSE_SUCCESS) continue;
  779. if (!cf_next_token(cfp)) return;
  780. array = cfp->cur_token->str.array;
  781. color |= strtol(array, nullptr, 10) << 8;
  782. ret = cf_next_token_should_be(cfp, ",", ";",
  783. nullptr);
  784. if (ret != PARSE_SUCCESS) continue;
  785. if (!cf_next_token(cfp)) return;
  786. array = cfp->cur_token->str.array;
  787. color |= strtol(array, nullptr, 10);
  788. } else if (cf_token_is(cfp, "white")) {
  789. color = 0xFFFFFF;
  790. } else if (cf_token_is(cfp, "black")) {
  791. color = 0;
  792. }
  793. if (!cf_go_to_token(cfp, ";", nullptr)) return;
  794. AddExtraThemeColor(pal, group, name->array, color);
  795. }
  796. ret = cf_token_should_be(cfp, "}", "}", nullptr);
  797. if (ret != PARSE_SUCCESS) continue;
  798. }
  799. setPalette(pal);
  800. }
  801. bool OBSApp::SetTheme(std::string name, std::string path)
  802. {
  803. theme = name;
  804. /* Check user dir first, then preinstalled themes. */
  805. if (path == "") {
  806. char userDir[512];
  807. name = "themes/" + name + ".qss";
  808. string temp = "obs-studio/" + name;
  809. int ret = GetConfigPath(userDir, sizeof(userDir),
  810. temp.c_str());
  811. if (ret > 0 && QFile::exists(userDir)) {
  812. path = string(userDir);
  813. } else if (!GetDataFilePath(name.c_str(), path)) {
  814. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  815. return false;
  816. }
  817. }
  818. QString mpath = QString("file:///") + path.c_str();
  819. setPalette(defaultPalette);
  820. setStyleSheet(mpath);
  821. ParseExtraThemeData(path.c_str());
  822. emit StyleChanged();
  823. return true;
  824. }
  825. bool OBSApp::InitTheme()
  826. {
  827. defaultPalette = palette();
  828. const char *themeName = config_get_string(globalConfig, "General",
  829. "CurrentTheme");
  830. if (!themeName) {
  831. /* Use deprecated "Theme" value if available */
  832. themeName = config_get_string(globalConfig,
  833. "General", "Theme");
  834. if (!themeName)
  835. themeName = "Default";
  836. }
  837. if (strcmp(themeName, "Default") != 0 && SetTheme(themeName))
  838. return true;
  839. return SetTheme("Default");
  840. }
  841. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  842. : QApplication(argc, argv),
  843. profilerNameStore(store)
  844. {
  845. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  846. }
  847. OBSApp::~OBSApp()
  848. {
  849. #ifdef _WIN32
  850. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  851. "DisableAudioDucking");
  852. if (disableAudioDucking)
  853. DisableAudioDucking(false);
  854. #endif
  855. #ifdef __APPLE__
  856. bool vsyncDiabled = config_get_bool(globalConfig, "Video",
  857. "DisableOSXVSync");
  858. bool resetVSync = config_get_bool(globalConfig, "Video",
  859. "ResetOSXVSyncOnExit");
  860. if (vsyncDiabled && resetVSync)
  861. EnableOSXVSync(true);
  862. #endif
  863. os_inhibit_sleep_set_active(sleepInhibitor, false);
  864. os_inhibit_sleep_destroy(sleepInhibitor);
  865. }
  866. static void move_basic_to_profiles(void)
  867. {
  868. char path[512];
  869. char new_path[512];
  870. os_glob_t *glob;
  871. /* if not first time use */
  872. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  873. return;
  874. if (!os_file_exists(path))
  875. return;
  876. /* if the profiles directory doesn't already exist */
  877. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  878. return;
  879. if (os_file_exists(new_path))
  880. return;
  881. if (os_mkdir(new_path) == MKDIR_ERROR)
  882. return;
  883. strcat(new_path, "/");
  884. strcat(new_path, Str("Untitled"));
  885. if (os_mkdir(new_path) == MKDIR_ERROR)
  886. return;
  887. strcat(path, "/*.*");
  888. if (os_glob(path, 0, &glob) != 0)
  889. return;
  890. strcpy(path, new_path);
  891. for (size_t i = 0; i < glob->gl_pathc; i++) {
  892. struct os_globent ent = glob->gl_pathv[i];
  893. char *file;
  894. if (ent.directory)
  895. continue;
  896. file = strrchr(ent.path, '/');
  897. if (!file++)
  898. continue;
  899. if (astrcmpi(file, "scenes.json") == 0)
  900. continue;
  901. strcpy(new_path, path);
  902. strcat(new_path, "/");
  903. strcat(new_path, file);
  904. os_rename(ent.path, new_path);
  905. }
  906. os_globfree(glob);
  907. }
  908. static void move_basic_to_scene_collections(void)
  909. {
  910. char path[512];
  911. char new_path[512];
  912. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  913. return;
  914. if (!os_file_exists(path))
  915. return;
  916. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  917. return;
  918. if (os_file_exists(new_path))
  919. return;
  920. if (os_mkdir(new_path) == MKDIR_ERROR)
  921. return;
  922. strcat(path, "/scenes.json");
  923. strcat(new_path, "/");
  924. strcat(new_path, Str("Untitled"));
  925. strcat(new_path, ".json");
  926. os_rename(path, new_path);
  927. }
  928. void OBSApp::AppInit()
  929. {
  930. ProfileScope("OBSApp::AppInit");
  931. if (!InitApplicationBundle())
  932. throw "Failed to initialize application bundle";
  933. if (!MakeUserDirs())
  934. throw "Failed to create required user directories";
  935. if (!InitGlobalConfig())
  936. throw "Failed to initialize global config";
  937. if (!InitLocale())
  938. throw "Failed to load locale";
  939. if (!InitTheme())
  940. throw "Failed to load theme";
  941. config_set_default_string(globalConfig, "Basic", "Profile",
  942. Str("Untitled"));
  943. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  944. Str("Untitled"));
  945. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  946. Str("Untitled"));
  947. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  948. Str("Untitled"));
  949. #ifdef _WIN32
  950. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  951. "DisableAudioDucking");
  952. if (disableAudioDucking)
  953. DisableAudioDucking(true);
  954. #endif
  955. #ifdef __APPLE__
  956. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  957. EnableOSXVSync(false);
  958. #endif
  959. enableHotkeysInFocus = !config_get_bool(globalConfig, "General",
  960. "DisableHotkeysInFocus");
  961. move_basic_to_profiles();
  962. move_basic_to_scene_collections();
  963. if (!MakeUserProfileDirs())
  964. throw "Failed to create profile directories";
  965. }
  966. const char *OBSApp::GetRenderModule() const
  967. {
  968. const char *renderer = config_get_string(globalConfig, "Video",
  969. "Renderer");
  970. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  971. DL_D3D11 : DL_OPENGL;
  972. }
  973. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  974. {
  975. char path[512];
  976. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  977. return false;
  978. return obs_startup(locale, path, store);
  979. }
  980. inline void OBSApp::ResetHotkeyState(bool inFocus)
  981. {
  982. obs_hotkey_enable_background_press(
  983. inFocus || enableHotkeysInFocus);
  984. }
  985. void OBSApp::EnableInFocusHotkeys(bool enable)
  986. {
  987. enableHotkeysInFocus = enable;
  988. ResetHotkeyState(applicationState() != Qt::ApplicationActive);
  989. }
  990. bool OBSApp::OBSInit()
  991. {
  992. ProfileScope("OBSApp::OBSInit");
  993. setAttribute(Qt::AA_UseHighDpiPixmaps);
  994. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  995. return false;
  996. #ifdef _WIN32
  997. bool browserHWAccel = config_get_bool(globalConfig, "General",
  998. "BrowserHWAccel");
  999. obs_data_t *settings = obs_data_create();
  1000. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1001. obs_apply_private_data(settings);
  1002. obs_data_release(settings);
  1003. blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str());
  1004. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1005. browserHWAccel ? "true" : "false");
  1006. #endif
  1007. blog(LOG_INFO, "Portable mode: %s",
  1008. portable_mode ? "true" : "false");
  1009. setQuitOnLastWindowClosed(false);
  1010. mainWindow = new OBSBasic();
  1011. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1012. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1013. mainWindow->OBSInit();
  1014. connect(this, &QGuiApplication::applicationStateChanged,
  1015. [this](Qt::ApplicationState state)
  1016. {
  1017. ResetHotkeyState(
  1018. state != Qt::ApplicationActive);
  1019. });
  1020. ResetHotkeyState(applicationState() != Qt::ApplicationActive);
  1021. return true;
  1022. }
  1023. string OBSApp::GetVersionString() const
  1024. {
  1025. stringstream ver;
  1026. #ifdef HAVE_OBSCONFIG_H
  1027. ver << OBS_VERSION;
  1028. #else
  1029. ver << LIBOBS_API_MAJOR_VER << "." <<
  1030. LIBOBS_API_MINOR_VER << "." <<
  1031. LIBOBS_API_PATCH_VER;
  1032. #endif
  1033. ver << " (";
  1034. #ifdef _WIN32
  1035. if (sizeof(void*) == 8)
  1036. ver << "64-bit, ";
  1037. else
  1038. ver << "32-bit, ";
  1039. ver << "windows)";
  1040. #elif __APPLE__
  1041. ver << "mac)";
  1042. #elif __FreeBSD__
  1043. ver << "freebsd)";
  1044. #else /* assume linux for the time being */
  1045. ver << "linux)";
  1046. #endif
  1047. return ver.str();
  1048. }
  1049. bool OBSApp::IsPortableMode()
  1050. {
  1051. return portable_mode;
  1052. }
  1053. #ifdef __APPLE__
  1054. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1055. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1056. #elif _WIN32
  1057. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1058. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1059. #else
  1060. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1061. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1062. #endif
  1063. const char *OBSApp::InputAudioSource() const
  1064. {
  1065. return INPUT_AUDIO_SOURCE;
  1066. }
  1067. const char *OBSApp::OutputAudioSource() const
  1068. {
  1069. return OUTPUT_AUDIO_SOURCE;
  1070. }
  1071. const char *OBSApp::GetLastLog() const
  1072. {
  1073. return lastLogFile.c_str();
  1074. }
  1075. const char *OBSApp::GetCurrentLog() const
  1076. {
  1077. return currentLogFile.c_str();
  1078. }
  1079. const char *OBSApp::GetLastCrashLog() const
  1080. {
  1081. return lastCrashLogFile.c_str();
  1082. }
  1083. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1084. {
  1085. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1086. if (cb(lookupVal, out))
  1087. return true;
  1088. }
  1089. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1090. }
  1091. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1092. const char *disambiguation, int n) const
  1093. {
  1094. const char *out = nullptr;
  1095. if (!App()->TranslateString(sourceText, &out))
  1096. return QString(sourceText);
  1097. UNUSED_PARAMETER(context);
  1098. UNUSED_PARAMETER(disambiguation);
  1099. UNUSED_PARAMETER(n);
  1100. return QT_UTF8(out);
  1101. }
  1102. static bool get_token(lexer *lex, string &str, base_token_type type)
  1103. {
  1104. base_token token;
  1105. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1106. return false;
  1107. if (token.type != type)
  1108. return false;
  1109. str.assign(token.text.array, token.text.len);
  1110. return true;
  1111. }
  1112. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1113. {
  1114. base_token token;
  1115. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1116. return false;
  1117. if (token.type != type)
  1118. return false;
  1119. return strref_cmp(&token.text, str) == 0;
  1120. }
  1121. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1122. {
  1123. BaseLexer lex;
  1124. string year, month, day, hour, minute, second;
  1125. lexer_start(lex, name);
  1126. if (has_prefix) {
  1127. string temp;
  1128. if (!get_token(lex, temp, BASETOKEN_ALPHA)) return 0;
  1129. }
  1130. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  1131. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1132. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  1133. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1134. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  1135. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  1136. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1137. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  1138. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1139. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  1140. stringstream timestring;
  1141. timestring << year << month << day << hour << minute << second;
  1142. return std::stoull(timestring.str());
  1143. }
  1144. static void delete_oldest_file(bool has_prefix, const char *location)
  1145. {
  1146. BPtr<char> logDir(GetConfigPathPtr(location));
  1147. string oldestLog;
  1148. uint64_t oldest_ts = (uint64_t)-1;
  1149. struct os_dirent *entry;
  1150. unsigned int maxLogs = (unsigned int)config_get_uint(
  1151. App()->GlobalConfig(), "General", "MaxLogs");
  1152. os_dir_t *dir = os_opendir(logDir);
  1153. if (dir) {
  1154. unsigned int count = 0;
  1155. while ((entry = os_readdir(dir)) != NULL) {
  1156. if (entry->directory || *entry->d_name == '.')
  1157. continue;
  1158. uint64_t ts = convert_log_name(has_prefix,
  1159. entry->d_name);
  1160. if (ts) {
  1161. if (ts < oldest_ts) {
  1162. oldestLog = entry->d_name;
  1163. oldest_ts = ts;
  1164. }
  1165. count++;
  1166. }
  1167. }
  1168. os_closedir(dir);
  1169. if (count > maxLogs) {
  1170. stringstream delPath;
  1171. delPath << logDir << "/" << oldestLog;
  1172. os_unlink(delPath.str().c_str());
  1173. }
  1174. }
  1175. }
  1176. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1177. std::string &last)
  1178. {
  1179. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1180. struct os_dirent *entry;
  1181. os_dir_t *dir = os_opendir(logDir);
  1182. uint64_t highest_ts = 0;
  1183. if (dir) {
  1184. while ((entry = os_readdir(dir)) != NULL) {
  1185. if (entry->directory || *entry->d_name == '.')
  1186. continue;
  1187. uint64_t ts = convert_log_name(has_prefix,
  1188. entry->d_name);
  1189. if (ts > highest_ts) {
  1190. last = entry->d_name;
  1191. highest_ts = ts;
  1192. }
  1193. }
  1194. os_closedir(dir);
  1195. }
  1196. }
  1197. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1198. {
  1199. time_t now = time(0);
  1200. char file[256] = {};
  1201. struct tm *cur_time;
  1202. cur_time = localtime(&now);
  1203. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1204. cur_time->tm_year+1900,
  1205. cur_time->tm_mon+1,
  1206. cur_time->tm_mday,
  1207. noSpace ? '_' : ' ',
  1208. cur_time->tm_hour,
  1209. cur_time->tm_min,
  1210. cur_time->tm_sec,
  1211. extension);
  1212. return string(file);
  1213. }
  1214. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1215. const char *format)
  1216. {
  1217. OBSBasic *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1218. bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux");
  1219. if ((strcmp(extension, "mp4") == 0) && autoRemux)
  1220. extension = "mkv";
  1221. BPtr<char> filename = os_generate_formatted_filename(extension,
  1222. !noSpace, format);
  1223. remuxFilename = string(filename);
  1224. remuxAfterRecord = autoRemux;
  1225. return string(filename);
  1226. }
  1227. vector<pair<string, string>> GetLocaleNames()
  1228. {
  1229. string path;
  1230. if (!GetDataFilePath("locale.ini", path))
  1231. throw "Could not find locale.ini path";
  1232. ConfigFile ini;
  1233. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1234. throw "Could not open locale.ini";
  1235. size_t sections = config_num_sections(ini);
  1236. vector<pair<string, string>> names;
  1237. names.reserve(sections);
  1238. for (size_t i = 0; i < sections; i++) {
  1239. const char *tag = config_get_section(ini, i);
  1240. const char *name = config_get_string(ini, tag, "Name");
  1241. names.emplace_back(tag, name);
  1242. }
  1243. return names;
  1244. }
  1245. static void create_log_file(fstream &logFile)
  1246. {
  1247. stringstream dst;
  1248. get_last_log(false, "obs-studio/logs", lastLogFile);
  1249. #ifdef _WIN32
  1250. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1251. #endif
  1252. currentLogFile = GenerateTimeDateFilename("txt");
  1253. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1254. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1255. #ifdef _WIN32
  1256. BPtr<wchar_t> wpath;
  1257. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1258. logFile.open(wpath,
  1259. ios_base::in | ios_base::out | ios_base::trunc);
  1260. #else
  1261. logFile.open(path,
  1262. ios_base::in | ios_base::out | ios_base::trunc);
  1263. #endif
  1264. if (logFile.is_open()) {
  1265. delete_oldest_file(false, "obs-studio/logs");
  1266. base_set_log_handler(do_log, &logFile);
  1267. } else {
  1268. blog(LOG_ERROR, "Failed to open log file");
  1269. }
  1270. }
  1271. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  1272. {
  1273. profiler_name_store_free(store);
  1274. };
  1275. using ProfilerNameStore =
  1276. std::unique_ptr<profiler_name_store_t,
  1277. decltype(ProfilerNameStoreRelease)>;
  1278. ProfilerNameStore CreateNameStore()
  1279. {
  1280. return ProfilerNameStore{profiler_name_store_create(),
  1281. ProfilerNameStoreRelease};
  1282. }
  1283. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  1284. {
  1285. profile_snapshot_free(snap);
  1286. };
  1287. using ProfilerSnapshot =
  1288. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1289. ProfilerSnapshot GetSnapshot()
  1290. {
  1291. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1292. }
  1293. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1294. {
  1295. if (currentLogFile.empty())
  1296. return;
  1297. auto pos = currentLogFile.rfind('.');
  1298. if (pos == currentLogFile.npos)
  1299. return;
  1300. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1301. ostringstream dst;
  1302. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1303. dst.write(currentLogFile.c_str(), pos);
  1304. dst.write(LITERAL_SIZE(".csv.gz"));
  1305. #undef LITERAL_SIZE
  1306. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1307. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1308. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1309. static_cast<const char*>(path));
  1310. }
  1311. static auto ProfilerFree = [](void *)
  1312. {
  1313. profiler_stop();
  1314. auto snap = GetSnapshot();
  1315. profiler_print(snap.get());
  1316. profiler_print_time_between_calls(snap.get());
  1317. SaveProfilerData(snap);
  1318. profiler_free();
  1319. };
  1320. static const char *run_program_init = "run_program_init";
  1321. static int run_program(fstream &logFile, int argc, char *argv[])
  1322. {
  1323. int ret = -1;
  1324. auto profilerNameStore = CreateNameStore();
  1325. std::unique_ptr<void, decltype(ProfilerFree)>
  1326. prof_release(static_cast<void*>(&ProfilerFree),
  1327. ProfilerFree);
  1328. profiler_start();
  1329. profile_register_root(run_program_init, 0);
  1330. ScopeProfiler prof{run_program_init};
  1331. QCoreApplication::addLibraryPath(".");
  1332. OBSApp program(argc, argv, profilerNameStore.get());
  1333. try {
  1334. bool created_log = false;
  1335. program.AppInit();
  1336. delete_oldest_file(false, "obs-studio/profiler_data");
  1337. OBSTranslator translator;
  1338. program.installTranslator(&translator);
  1339. #ifdef _WIN32
  1340. /* --------------------------------------- */
  1341. /* check and warn if already running */
  1342. bool cancel_launch = false;
  1343. bool already_running = false;
  1344. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1345. if (!already_running) {
  1346. goto run;
  1347. }
  1348. if (!multi) {
  1349. QMessageBox::StandardButtons buttons(
  1350. QMessageBox::Yes | QMessageBox::Cancel);
  1351. QMessageBox mb(QMessageBox::Question,
  1352. QTStr("AlreadyRunning.Title"),
  1353. QTStr("AlreadyRunning.Text"), buttons,
  1354. nullptr);
  1355. mb.setButtonText(QMessageBox::Yes,
  1356. QTStr("AlreadyRunning.LaunchAnyway"));
  1357. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1358. mb.setDefaultButton(QMessageBox::Cancel);
  1359. QMessageBox::StandardButton button;
  1360. button = (QMessageBox::StandardButton)mb.exec();
  1361. cancel_launch = button == QMessageBox::Cancel;
  1362. }
  1363. if (cancel_launch)
  1364. return 0;
  1365. if (!created_log) {
  1366. create_log_file(logFile);
  1367. created_log = true;
  1368. }
  1369. if (multi) {
  1370. blog(LOG_INFO, "User enabled --multi flag and is now "
  1371. "running multiple instances of OBS.");
  1372. } else {
  1373. blog(LOG_WARNING, "================================");
  1374. blog(LOG_WARNING, "Warning: OBS is already running!");
  1375. blog(LOG_WARNING, "================================");
  1376. blog(LOG_WARNING, "User is now running multiple "
  1377. "instances of OBS!");
  1378. }
  1379. /* --------------------------------------- */
  1380. run:
  1381. #endif
  1382. if (!created_log) {
  1383. create_log_file(logFile);
  1384. created_log = true;
  1385. }
  1386. if (argc > 1) {
  1387. stringstream stor;
  1388. stor << argv[1];
  1389. for (int i = 2; i < argc; ++i) {
  1390. stor << " " << argv[i];
  1391. }
  1392. blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str());
  1393. }
  1394. if (!program.OBSInit())
  1395. return 0;
  1396. prof.Stop();
  1397. return program.exec();
  1398. } catch (const char *error) {
  1399. blog(LOG_ERROR, "%s", error);
  1400. OBSErrorBox(nullptr, "%s", error);
  1401. }
  1402. return ret;
  1403. }
  1404. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1405. #ifdef _WIN32
  1406. #define CRASH_MESSAGE \
  1407. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1408. "to the clipboard? (Crash logs will still be saved to the " \
  1409. "%appdata%\\obs-studio\\crashes directory)"
  1410. static void main_crash_handler(const char *format, va_list args, void *param)
  1411. {
  1412. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1413. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1414. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1415. delete_oldest_file(true, "obs-studio/crashes");
  1416. string name = "obs-studio/crashes/Crash ";
  1417. name += GenerateTimeDateFilename("txt");
  1418. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1419. fstream file;
  1420. #ifdef _WIN32
  1421. BPtr<wchar_t> wpath;
  1422. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1423. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1424. ios_base::binary);
  1425. #else
  1426. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1427. ios_base::binary);
  1428. #endif
  1429. file << text;
  1430. file.close();
  1431. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1432. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1433. if (ret == IDYES) {
  1434. size_t len = strlen(text);
  1435. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1436. memcpy(GlobalLock(mem), text, len);
  1437. GlobalUnlock(mem);
  1438. OpenClipboard(0);
  1439. EmptyClipboard();
  1440. SetClipboardData(CF_TEXT, mem);
  1441. CloseClipboard();
  1442. }
  1443. exit(-1);
  1444. UNUSED_PARAMETER(param);
  1445. }
  1446. static void load_debug_privilege(void)
  1447. {
  1448. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1449. TOKEN_PRIVILEGES tp;
  1450. HANDLE token;
  1451. LUID val;
  1452. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1453. return;
  1454. }
  1455. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1456. tp.PrivilegeCount = 1;
  1457. tp.Privileges[0].Luid = val;
  1458. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1459. AdjustTokenPrivileges(token, false, &tp,
  1460. sizeof(tp), NULL, NULL);
  1461. }
  1462. CloseHandle(token);
  1463. }
  1464. #endif
  1465. #ifdef __APPLE__
  1466. #define BASE_PATH ".."
  1467. #else
  1468. #define BASE_PATH "../.."
  1469. #endif
  1470. #define CONFIG_PATH BASE_PATH "/config"
  1471. #ifndef OBS_UNIX_STRUCTURE
  1472. #define OBS_UNIX_STRUCTURE 0
  1473. #endif
  1474. int GetConfigPath(char *path, size_t size, const char *name)
  1475. {
  1476. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1477. if (name && *name) {
  1478. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1479. } else {
  1480. return snprintf(path, size, CONFIG_PATH);
  1481. }
  1482. } else {
  1483. return os_get_config_path(path, size, name);
  1484. }
  1485. }
  1486. char *GetConfigPathPtr(const char *name)
  1487. {
  1488. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1489. char path[512];
  1490. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1491. return bstrdup(path);
  1492. } else {
  1493. return NULL;
  1494. }
  1495. } else {
  1496. return os_get_config_path_ptr(name);
  1497. }
  1498. }
  1499. int GetProgramDataPath(char *path, size_t size, const char *name)
  1500. {
  1501. return os_get_program_data_path(path, size, name);
  1502. }
  1503. char *GetProgramDataPathPtr(const char *name)
  1504. {
  1505. return os_get_program_data_path_ptr(name);
  1506. }
  1507. bool GetFileSafeName(const char *name, std::string &file)
  1508. {
  1509. size_t base_len = strlen(name);
  1510. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1511. std::wstring wfile;
  1512. if (!len)
  1513. return false;
  1514. wfile.resize(len);
  1515. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1516. for (size_t i = wfile.size(); i > 0; i--) {
  1517. size_t im1 = i - 1;
  1518. if (iswspace(wfile[im1])) {
  1519. wfile[im1] = '_';
  1520. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1521. wfile.erase(im1, 1);
  1522. }
  1523. }
  1524. if (wfile.size() == 0)
  1525. wfile = L"characters_only";
  1526. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1527. if (!len)
  1528. return false;
  1529. file.resize(len);
  1530. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1531. return true;
  1532. }
  1533. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1534. {
  1535. size_t len = path.size();
  1536. if (extension) {
  1537. path += ".";
  1538. path += extension;
  1539. }
  1540. if (!os_file_exists(path.c_str()))
  1541. return true;
  1542. int index = 1;
  1543. do {
  1544. path.resize(len);
  1545. path += std::to_string(++index);
  1546. if (extension) {
  1547. path += ".";
  1548. path += extension;
  1549. }
  1550. } while (os_file_exists(path.c_str()));
  1551. return true;
  1552. }
  1553. bool WindowPositionValid(QRect rect)
  1554. {
  1555. for (QScreen* screen: QGuiApplication::screens()) {
  1556. if (screen->availableGeometry().intersects(rect))
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. static inline bool arg_is(const char *arg,
  1562. const char *long_form, const char *short_form)
  1563. {
  1564. return (long_form && strcmp(arg, long_form) == 0) ||
  1565. (short_form && strcmp(arg, short_form) == 0);
  1566. }
  1567. #if !defined(_WIN32) && !defined(__APPLE__)
  1568. #define IS_UNIX 1
  1569. #endif
  1570. /* if using XDG and was previously using an older build of OBS, move config
  1571. * files to XDG directory */
  1572. #if defined(USE_XDG) && defined(IS_UNIX)
  1573. static void move_to_xdg(void)
  1574. {
  1575. char old_path[512];
  1576. char new_path[512];
  1577. char *home = getenv("HOME");
  1578. if (!home)
  1579. return;
  1580. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1581. return;
  1582. /* make base xdg path if it doesn't already exist */
  1583. if (GetConfigPath(new_path, 512, "") <= 0)
  1584. return;
  1585. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1586. return;
  1587. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1588. return;
  1589. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1590. rename(old_path, new_path);
  1591. }
  1592. }
  1593. #endif
  1594. static bool update_ffmpeg_output(ConfigFile &config)
  1595. {
  1596. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1597. return false;
  1598. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1599. if (!url)
  1600. return false;
  1601. bool isActualURL = strstr(url, "://") != nullptr;
  1602. if (isActualURL)
  1603. return false;
  1604. string urlStr = url;
  1605. string extension;
  1606. for (size_t i = urlStr.length(); i > 0; i--) {
  1607. size_t idx = i - 1;
  1608. if (urlStr[idx] == '.') {
  1609. extension = &urlStr[i];
  1610. }
  1611. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1612. urlStr[idx] = 0;
  1613. break;
  1614. }
  1615. }
  1616. if (urlStr.empty() || extension.empty())
  1617. return false;
  1618. config_remove_value(config, "AdvOut", "FFURL");
  1619. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1620. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1621. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1622. return true;
  1623. }
  1624. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1625. {
  1626. bool changed = false;
  1627. if (config_has_user_value(config, sec, "Reconnect")) {
  1628. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1629. config_set_bool(config, "Output", "Reconnect", reconnect);
  1630. changed = true;
  1631. }
  1632. if (config_has_user_value(config, sec, "RetryDelay")) {
  1633. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1634. config_set_uint(config, "Output", "RetryDelay", delay);
  1635. changed = true;
  1636. }
  1637. if (config_has_user_value(config, sec, "MaxRetries")) {
  1638. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1639. config_set_uint(config, "Output", "MaxRetries", retries);
  1640. changed = true;
  1641. }
  1642. return changed;
  1643. }
  1644. static bool update_reconnect(ConfigFile &config)
  1645. {
  1646. if (!config_has_user_value(config, "Output", "Mode"))
  1647. return false;
  1648. const char *mode = config_get_string(config, "Output", "Mode");
  1649. if (!mode)
  1650. return false;
  1651. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1652. "AdvOut" : "SimpleOutput";
  1653. if (move_reconnect_settings(config, section)) {
  1654. config_remove_value(config, "SimpleOutput", "Reconnect");
  1655. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1656. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1657. config_remove_value(config, "AdvOut", "Reconnect");
  1658. config_remove_value(config, "AdvOut", "RetryDelay");
  1659. config_remove_value(config, "AdvOut", "MaxRetries");
  1660. return true;
  1661. }
  1662. return false;
  1663. }
  1664. static void convert_x264_settings(obs_data_t *data)
  1665. {
  1666. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1667. if (use_bufsize) {
  1668. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1669. if (buffer_size == 0)
  1670. obs_data_set_string(data, "rate_control", "CRF");
  1671. }
  1672. }
  1673. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1674. {
  1675. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1676. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1677. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1678. bool modified = false;
  1679. bool cbr = true;
  1680. if (cbr_item) {
  1681. cbr = obs_data_item_get_bool(cbr_item);
  1682. obs_data_item_unset_user_value(cbr_item);
  1683. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1684. modified = true;
  1685. }
  1686. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1687. if (!cbr_item)
  1688. obs_data_set_string(data, "rate_control", "CBR");
  1689. else if (!cbr)
  1690. convert_x264_settings(data);
  1691. modified = true;
  1692. }
  1693. if (modified)
  1694. obs_data_save_json_safe(data, file, "tmp", "bak");
  1695. obs_data_item_release(&rc_item);
  1696. obs_data_item_release(&cbr_item);
  1697. obs_data_release(data);
  1698. }
  1699. static void upgrade_settings(void)
  1700. {
  1701. char path[512];
  1702. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1703. if (pathlen <= 0)
  1704. return;
  1705. if (!os_file_exists(path))
  1706. return;
  1707. os_dir_t *dir = os_opendir(path);
  1708. if (!dir)
  1709. return;
  1710. struct os_dirent *ent = os_readdir(dir);
  1711. while (ent) {
  1712. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1713. strcmp(ent->d_name, "..") != 0) {
  1714. strcat(path, "/");
  1715. strcat(path, ent->d_name);
  1716. strcat(path, "/basic.ini");
  1717. ConfigFile config;
  1718. int ret;
  1719. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1720. if (ret == CONFIG_SUCCESS) {
  1721. if (update_ffmpeg_output(config) ||
  1722. update_reconnect(config)) {
  1723. config_save_safe(config, "tmp",
  1724. nullptr);
  1725. }
  1726. }
  1727. if (config) {
  1728. const char *sEnc = config_get_string(config,
  1729. "AdvOut", "Encoder");
  1730. const char *rEnc = config_get_string(config,
  1731. "AdvOut", "RecEncoder");
  1732. /* replace "cbr" option with "rate_control" for
  1733. * each profile's encoder data */
  1734. path[pathlen] = 0;
  1735. strcat(path, "/");
  1736. strcat(path, ent->d_name);
  1737. strcat(path, "/recordEncoder.json");
  1738. convert_14_2_encoder_setting(rEnc, path);
  1739. path[pathlen] = 0;
  1740. strcat(path, "/");
  1741. strcat(path, ent->d_name);
  1742. strcat(path, "/streamEncoder.json");
  1743. convert_14_2_encoder_setting(sEnc, path);
  1744. }
  1745. path[pathlen] = 0;
  1746. }
  1747. ent = os_readdir(dir);
  1748. }
  1749. os_closedir(dir);
  1750. }
  1751. int main(int argc, char *argv[])
  1752. {
  1753. #ifndef _WIN32
  1754. signal(SIGPIPE, SIG_IGN);
  1755. #endif
  1756. #ifdef _WIN32
  1757. obs_init_win32_crash_handler();
  1758. SetErrorMode(SEM_FAILCRITICALERRORS);
  1759. load_debug_privilege();
  1760. base_set_crash_handler(main_crash_handler, nullptr);
  1761. #endif
  1762. base_get_log_handler(&def_log_handler, nullptr);
  1763. #if defined(USE_XDG) && defined(IS_UNIX)
  1764. move_to_xdg();
  1765. #endif
  1766. obs_set_cmdline_args(argc, argv);
  1767. for (int i = 1; i < argc; i++) {
  1768. if (arg_is(argv[i], "--portable", "-p")) {
  1769. portable_mode = true;
  1770. } else if (arg_is(argv[i], "--multi", "-m")) {
  1771. multi = true;
  1772. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1773. log_verbose = true;
  1774. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  1775. opt_always_on_top = true;
  1776. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1777. unfiltered_log = true;
  1778. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1779. opt_start_streaming = true;
  1780. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1781. opt_start_recording = true;
  1782. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1783. opt_start_replaybuffer = true;
  1784. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1785. if (++i < argc) opt_starting_collection = argv[i];
  1786. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1787. if (++i < argc) opt_starting_profile = argv[i];
  1788. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1789. if (++i < argc) opt_starting_scene = argv[i];
  1790. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1791. opt_minimize_tray = true;
  1792. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1793. opt_studio_mode = true;
  1794. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  1795. opt_allow_opengl = true;
  1796. } else if (arg_is(argv[i], "--help", "-h")) {
  1797. std::cout <<
  1798. "--help, -h: Get list of available commands.\n\n" <<
  1799. "--startstreaming: Automatically start streaming.\n" <<
  1800. "--startrecording: Automatically start recording.\n" <<
  1801. "--startreplaybuffer: Start replay buffer.\n\n" <<
  1802. "--collection <string>: Use specific scene collection."
  1803. << "\n" <<
  1804. "--profile <string>: Use specific profile.\n" <<
  1805. "--scene <string>: Start with specific scene.\n\n" <<
  1806. "--studio-mode: Enable studio mode.\n" <<
  1807. "--minimize-to-tray: Minimize to system tray.\n" <<
  1808. "--portable, -p: Use portable mode.\n" <<
  1809. "--multi, -m: Don't warn when launching multiple instances.\n\n" <<
  1810. "--verbose: Make log more verbose.\n" <<
  1811. "--always-on-top: Start in 'always on top' mode.\n\n" <<
  1812. "--unfiltered_log: Make log unfiltered.\n\n" <<
  1813. "--allow-opengl: Allow OpenGL on Windows.\n\n" <<
  1814. "--version, -V: Get current version.\n";
  1815. exit(0);
  1816. } else if (arg_is(argv[i], "--version", "-V")) {
  1817. std::cout << "OBS Studio - " <<
  1818. App()->GetVersionString() << "\n";
  1819. exit(0);
  1820. }
  1821. }
  1822. #if !OBS_UNIX_STRUCTURE
  1823. if (!portable_mode) {
  1824. portable_mode =
  1825. os_file_exists(BASE_PATH "/portable_mode") ||
  1826. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1827. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1828. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1829. }
  1830. #endif
  1831. upgrade_settings();
  1832. fstream logFile;
  1833. curl_global_init(CURL_GLOBAL_ALL);
  1834. int ret = run_program(logFile, argc, argv);
  1835. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1836. base_set_log_handler(nullptr, nullptr);
  1837. return ret;
  1838. }