obs-app.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  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.h>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <obs-config.h>
  27. #include <obs.hpp>
  28. #include <QGuiApplication>
  29. #include <QProxyStyle>
  30. #include <QScreen>
  31. #include "qt-wrappers.hpp"
  32. #include "obs-app.hpp"
  33. #include "window-basic-main.hpp"
  34. #include "window-basic-settings.hpp"
  35. #include "window-license-agreement.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 bool portable_mode = false;
  51. static bool log_verbose = false;
  52. static bool unfiltered_log = false;
  53. bool opt_start_streaming = false;
  54. bool opt_start_recording = false;
  55. bool opt_studio_mode = false;
  56. bool opt_start_replaybuffer = false;
  57. bool opt_minimize_tray = false;
  58. string opt_starting_collection;
  59. string opt_starting_profile;
  60. string opt_starting_scene;
  61. // AMD PowerXpress High Performance Flags
  62. #ifdef _MSC_VER
  63. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  64. #endif
  65. QObject *CreateShortcutFilter()
  66. {
  67. return new OBSEventFilter([](QObject *obj, QEvent *event)
  68. {
  69. auto mouse_event = [](QMouseEvent &event)
  70. {
  71. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  72. bool pressed = event.type() == QEvent::MouseButtonPress;
  73. switch (event.button()) {
  74. case Qt::NoButton:
  75. case Qt::LeftButton:
  76. case Qt::RightButton:
  77. case Qt::AllButtons:
  78. case Qt::MouseButtonMask:
  79. return false;
  80. case Qt::MidButton:
  81. hotkey.key = OBS_KEY_MOUSE3;
  82. break;
  83. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  84. hotkey.key = OBS_KEY_MOUSE ## j; break;
  85. MAP_BUTTON( 1, 4);
  86. MAP_BUTTON( 2, 5);
  87. MAP_BUTTON( 3, 6);
  88. MAP_BUTTON( 4, 7);
  89. MAP_BUTTON( 5, 8);
  90. MAP_BUTTON( 6, 9);
  91. MAP_BUTTON( 7, 10);
  92. MAP_BUTTON( 8, 11);
  93. MAP_BUTTON( 9, 12);
  94. MAP_BUTTON(10, 13);
  95. MAP_BUTTON(11, 14);
  96. MAP_BUTTON(12, 15);
  97. MAP_BUTTON(13, 16);
  98. MAP_BUTTON(14, 17);
  99. MAP_BUTTON(15, 18);
  100. MAP_BUTTON(16, 19);
  101. MAP_BUTTON(17, 20);
  102. MAP_BUTTON(18, 21);
  103. MAP_BUTTON(19, 22);
  104. MAP_BUTTON(20, 23);
  105. MAP_BUTTON(21, 24);
  106. MAP_BUTTON(22, 25);
  107. MAP_BUTTON(23, 26);
  108. MAP_BUTTON(24, 27);
  109. #undef MAP_BUTTON
  110. }
  111. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  112. event.modifiers());
  113. obs_hotkey_inject_event(hotkey, pressed);
  114. return true;
  115. };
  116. auto key_event = [&](QKeyEvent *event)
  117. {
  118. QDialog *dialog = qobject_cast<QDialog*>(obj);
  119. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  120. bool pressed = event->type() == QEvent::KeyPress;
  121. switch (event->key()) {
  122. case Qt::Key_Shift:
  123. case Qt::Key_Control:
  124. case Qt::Key_Alt:
  125. case Qt::Key_Meta:
  126. break;
  127. #ifdef __APPLE__
  128. case Qt::Key_CapsLock:
  129. // kVK_CapsLock == 57
  130. hotkey.key = obs_key_from_virtual_key(57);
  131. pressed = true;
  132. break;
  133. #endif
  134. case Qt::Key_Enter:
  135. case Qt::Key_Escape:
  136. case Qt::Key_Return:
  137. if (dialog && pressed)
  138. return false;
  139. default:
  140. hotkey.key = obs_key_from_virtual_key(
  141. event->nativeVirtualKey());
  142. }
  143. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  144. event->modifiers());
  145. obs_hotkey_inject_event(hotkey, pressed);
  146. return true;
  147. };
  148. switch (event->type()) {
  149. case QEvent::MouseButtonPress:
  150. case QEvent::MouseButtonRelease:
  151. return mouse_event(*static_cast<QMouseEvent*>(event));
  152. /*case QEvent::MouseButtonDblClick:
  153. case QEvent::Wheel:*/
  154. case QEvent::KeyPress:
  155. case QEvent::KeyRelease:
  156. return key_event(static_cast<QKeyEvent*>(event));
  157. default:
  158. return false;
  159. }
  160. });
  161. }
  162. string CurrentTimeString()
  163. {
  164. using namespace std::chrono;
  165. struct tm tstruct;
  166. char buf[80];
  167. auto tp = system_clock::now();
  168. auto now = system_clock::to_time_t(tp);
  169. tstruct = *localtime(&now);
  170. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  171. if (ratio_less<system_clock::period, seconds::period>::value &&
  172. written && (sizeof(buf) - written) > 5) {
  173. auto tp_secs =
  174. time_point_cast<seconds>(tp);
  175. auto millis =
  176. duration_cast<milliseconds>(tp - tp_secs).count();
  177. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  178. static_cast<unsigned>(millis));
  179. }
  180. return buf;
  181. }
  182. string CurrentDateTimeString()
  183. {
  184. time_t now = time(0);
  185. struct tm tstruct;
  186. char buf[80];
  187. tstruct = *localtime(&now);
  188. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  189. return buf;
  190. }
  191. static inline void LogString(fstream &logFile, const char *timeString,
  192. char *str)
  193. {
  194. logFile << timeString << str << endl;
  195. }
  196. static inline void LogStringChunk(fstream &logFile, char *str)
  197. {
  198. char *nextLine = str;
  199. string timeString = CurrentTimeString();
  200. timeString += ": ";
  201. while (*nextLine) {
  202. char *nextLine = strchr(str, '\n');
  203. if (!nextLine)
  204. break;
  205. if (nextLine != str && nextLine[-1] == '\r') {
  206. nextLine[-1] = 0;
  207. } else {
  208. nextLine[0] = 0;
  209. }
  210. LogString(logFile, timeString.c_str(), str);
  211. nextLine++;
  212. str = nextLine;
  213. }
  214. LogString(logFile, timeString.c_str(), str);
  215. }
  216. #define MAX_REPEATED_LINES 30
  217. #define MAX_CHAR_VARIATION (255 * 3)
  218. static inline int sum_chars(const char *str)
  219. {
  220. int val = 0;
  221. for (; *str != 0; str++)
  222. val += *str;
  223. return val;
  224. }
  225. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  226. const char *output_str)
  227. {
  228. static mutex log_mutex;
  229. static const char *last_msg_ptr = nullptr;
  230. static int last_char_sum = 0;
  231. static char cmp_str[4096];
  232. static int rep_count = 0;
  233. int new_sum = sum_chars(output_str);
  234. lock_guard<mutex> guard(log_mutex);
  235. if (unfiltered_log) {
  236. return false;
  237. }
  238. if (last_msg_ptr == msg) {
  239. int diff = std::abs(new_sum - last_char_sum);
  240. if (diff < MAX_CHAR_VARIATION) {
  241. return (rep_count++ >= MAX_REPEATED_LINES);
  242. }
  243. }
  244. if (rep_count > MAX_REPEATED_LINES) {
  245. logFile << CurrentTimeString() <<
  246. ": Last log entry repeated for " <<
  247. to_string(rep_count - MAX_REPEATED_LINES) <<
  248. " more lines" << endl;
  249. }
  250. last_msg_ptr = msg;
  251. strcpy(cmp_str, output_str);
  252. last_char_sum = new_sum;
  253. rep_count = 0;
  254. return false;
  255. }
  256. static void do_log(int log_level, const char *msg, va_list args, void *param)
  257. {
  258. fstream &logFile = *static_cast<fstream*>(param);
  259. char str[4096];
  260. #ifndef _WIN32
  261. va_list args2;
  262. va_copy(args2, args);
  263. #endif
  264. vsnprintf(str, 4095, msg, args);
  265. #ifdef _WIN32
  266. if (IsDebuggerPresent()) {
  267. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  268. if (wNum > 1) {
  269. static wstring wide_buf;
  270. static mutex wide_mutex;
  271. lock_guard<mutex> lock(wide_mutex);
  272. wide_buf.reserve(wNum + 1);
  273. wide_buf.resize(wNum - 1);
  274. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  275. wNum);
  276. wide_buf.push_back('\n');
  277. OutputDebugStringW(wide_buf.c_str());
  278. }
  279. }
  280. #else
  281. def_log_handler(log_level, msg, args2, nullptr);
  282. #endif
  283. if (too_many_repeated_entries(logFile, msg, str))
  284. return;
  285. if (log_level <= LOG_INFO || log_verbose)
  286. LogStringChunk(logFile, str);
  287. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  288. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  289. __debugbreak();
  290. #endif
  291. }
  292. #define DEFAULT_LANG "en-US"
  293. bool OBSApp::InitGlobalConfigDefaults()
  294. {
  295. config_set_default_string(globalConfig, "General", "Language",
  296. DEFAULT_LANG);
  297. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  298. config_set_default_string(globalConfig, "General", "ProcessPriority",
  299. "Normal");
  300. #if _WIN32
  301. config_set_default_string(globalConfig, "Video", "Renderer",
  302. "Direct3D 11");
  303. #else
  304. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  305. #endif
  306. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  307. true);
  308. config_set_default_bool(globalConfig, "BasicWindow",
  309. "PreviewProgramMode", false);
  310. config_set_default_bool(globalConfig, "BasicWindow",
  311. "SceneDuplicationMode", true);
  312. config_set_default_bool(globalConfig, "BasicWindow",
  313. "SwapScenesMode", true);
  314. config_set_default_bool(globalConfig, "BasicWindow",
  315. "SnappingEnabled", true);
  316. config_set_default_bool(globalConfig, "BasicWindow",
  317. "ScreenSnapping", true);
  318. config_set_default_bool(globalConfig, "BasicWindow",
  319. "SourceSnapping", true);
  320. config_set_default_bool(globalConfig, "BasicWindow",
  321. "CenterSnapping", false);
  322. config_set_default_double(globalConfig, "BasicWindow",
  323. "SnapDistance", 10.0);
  324. config_set_default_bool(globalConfig, "BasicWindow",
  325. "RecordWhenStreaming", false);
  326. config_set_default_bool(globalConfig, "BasicWindow",
  327. "KeepRecordingWhenStreamStops", false);
  328. config_set_default_bool(globalConfig, "BasicWindow",
  329. "SysTrayEnabled", true);
  330. config_set_default_bool(globalConfig, "BasicWindow",
  331. "SysTrayWhenStarted", false);
  332. config_set_default_bool(globalConfig, "BasicWindow",
  333. "SaveProjectors", false);
  334. config_set_default_bool(globalConfig, "BasicWindow",
  335. "ShowTransitions", true);
  336. config_set_default_bool(globalConfig, "BasicWindow",
  337. "ShowListboxToolbars", true);
  338. config_set_default_bool(globalConfig, "BasicWindow",
  339. "ShowStatusBar", true);
  340. #ifdef __APPLE__
  341. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  342. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  343. true);
  344. #endif
  345. return true;
  346. }
  347. static bool do_mkdir(const char *path)
  348. {
  349. if (os_mkdirs(path) == MKDIR_ERROR) {
  350. OBSErrorBox(NULL, "Failed to create directory %s", path);
  351. return false;
  352. }
  353. return true;
  354. }
  355. static bool MakeUserDirs()
  356. {
  357. char path[512];
  358. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  359. return false;
  360. if (!do_mkdir(path))
  361. return false;
  362. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  363. return false;
  364. if (!do_mkdir(path))
  365. return false;
  366. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  367. return false;
  368. if (!do_mkdir(path))
  369. return false;
  370. #ifdef _WIN32
  371. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  372. return false;
  373. if (!do_mkdir(path))
  374. return false;
  375. #endif
  376. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  377. return false;
  378. if (!do_mkdir(path))
  379. return false;
  380. return true;
  381. }
  382. static bool MakeUserProfileDirs()
  383. {
  384. char path[512];
  385. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  386. return false;
  387. if (!do_mkdir(path))
  388. return false;
  389. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  390. return false;
  391. if (!do_mkdir(path))
  392. return false;
  393. return true;
  394. }
  395. static string GetProfileDirFromName(const char *name)
  396. {
  397. string outputPath;
  398. os_glob_t *glob;
  399. char path[512];
  400. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  401. return outputPath;
  402. strcat(path, "/*");
  403. if (os_glob(path, 0, &glob) != 0)
  404. return outputPath;
  405. for (size_t i = 0; i < glob->gl_pathc; i++) {
  406. struct os_globent ent = glob->gl_pathv[i];
  407. if (!ent.directory)
  408. continue;
  409. strcpy(path, ent.path);
  410. strcat(path, "/basic.ini");
  411. ConfigFile config;
  412. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  413. continue;
  414. const char *curName = config_get_string(config, "General",
  415. "Name");
  416. if (astrcmpi(curName, name) == 0) {
  417. outputPath = ent.path;
  418. break;
  419. }
  420. }
  421. os_globfree(glob);
  422. if (!outputPath.empty()) {
  423. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  424. const char *start = strrchr(outputPath.c_str(), '/');
  425. if (start)
  426. outputPath.erase(0, start - outputPath.c_str() + 1);
  427. }
  428. return outputPath;
  429. }
  430. static string GetSceneCollectionFileFromName(const char *name)
  431. {
  432. string outputPath;
  433. os_glob_t *glob;
  434. char path[512];
  435. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  436. return outputPath;
  437. strcat(path, "/*.json");
  438. if (os_glob(path, 0, &glob) != 0)
  439. return outputPath;
  440. for (size_t i = 0; i < glob->gl_pathc; i++) {
  441. struct os_globent ent = glob->gl_pathv[i];
  442. if (ent.directory)
  443. continue;
  444. obs_data_t *data =
  445. obs_data_create_from_json_file_safe(ent.path, "bak");
  446. const char *curName = obs_data_get_string(data, "name");
  447. if (astrcmpi(name, curName) == 0) {
  448. outputPath = ent.path;
  449. obs_data_release(data);
  450. break;
  451. }
  452. obs_data_release(data);
  453. }
  454. os_globfree(glob);
  455. if (!outputPath.empty()) {
  456. outputPath.resize(outputPath.size() - 5);
  457. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  458. const char *start = strrchr(outputPath.c_str(), '/');
  459. if (start)
  460. outputPath.erase(0, start - outputPath.c_str() + 1);
  461. }
  462. return outputPath;
  463. }
  464. bool OBSApp::InitGlobalConfig()
  465. {
  466. char path[512];
  467. int len = GetConfigPath(path, sizeof(path),
  468. "obs-studio/global.ini");
  469. if (len <= 0) {
  470. return false;
  471. }
  472. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  473. if (errorcode != CONFIG_SUCCESS) {
  474. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  475. return false;
  476. }
  477. if (!opt_starting_collection.empty()) {
  478. string path = GetSceneCollectionFileFromName(
  479. opt_starting_collection.c_str());
  480. if (!path.empty()) {
  481. config_set_string(globalConfig,
  482. "Basic", "SceneCollection",
  483. opt_starting_collection.c_str());
  484. config_set_string(globalConfig,
  485. "Basic", "SceneCollectionFile",
  486. path.c_str());
  487. }
  488. }
  489. if (!opt_starting_profile.empty()) {
  490. string path = GetProfileDirFromName(
  491. opt_starting_profile.c_str());
  492. if (!path.empty()) {
  493. config_set_string(globalConfig, "Basic", "Profile",
  494. opt_starting_profile.c_str());
  495. config_set_string(globalConfig, "Basic", "ProfileDir",
  496. path.c_str());
  497. }
  498. }
  499. return InitGlobalConfigDefaults();
  500. }
  501. bool OBSApp::InitLocale()
  502. {
  503. ProfileScope("OBSApp::InitLocale");
  504. const char *lang = config_get_string(globalConfig, "General",
  505. "Language");
  506. locale = lang;
  507. string englishPath;
  508. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  509. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  510. return false;
  511. }
  512. textLookup = text_lookup_create(englishPath.c_str());
  513. if (!textLookup) {
  514. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  515. englishPath.c_str());
  516. return false;
  517. }
  518. bool userLocale = config_has_user_value(globalConfig, "General",
  519. "Language");
  520. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  521. if (userLocale && defaultLang)
  522. return true;
  523. if (!userLocale && defaultLang) {
  524. for (auto &locale_ : GetPreferredLocales()) {
  525. if (locale_ == lang)
  526. return true;
  527. stringstream file;
  528. file << "locale/" << locale_ << ".ini";
  529. string path;
  530. if (!GetDataFilePath(file.str().c_str(), path))
  531. continue;
  532. if (!text_lookup_add(textLookup, path.c_str()))
  533. continue;
  534. blog(LOG_INFO, "Using preferred locale '%s'",
  535. locale_.c_str());
  536. locale = locale_;
  537. return true;
  538. }
  539. return true;
  540. }
  541. stringstream file;
  542. file << "locale/" << lang << ".ini";
  543. string path;
  544. if (GetDataFilePath(file.str().c_str(), path)) {
  545. if (!text_lookup_add(textLookup, path.c_str()))
  546. blog(LOG_ERROR, "Failed to add locale file '%s'",
  547. path.c_str());
  548. } else {
  549. blog(LOG_ERROR, "Could not find locale file '%s'",
  550. file.str().c_str());
  551. }
  552. return true;
  553. }
  554. bool OBSApp::SetTheme(std::string name, std::string path)
  555. {
  556. theme = name;
  557. /* Check user dir first, then preinstalled themes. */
  558. if (path == "") {
  559. char userDir[512];
  560. name = "themes/" + name + ".qss";
  561. string temp = "obs-studio/" + name;
  562. int ret = GetConfigPath(userDir, sizeof(userDir),
  563. temp.c_str());
  564. if (ret > 0 && QFile::exists(userDir)) {
  565. path = string(userDir);
  566. } else if (!GetDataFilePath(name.c_str(), path)) {
  567. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  568. return false;
  569. }
  570. }
  571. QString mpath = QString("file:///") + path.c_str();
  572. setStyleSheet(mpath);
  573. return true;
  574. }
  575. bool OBSApp::InitTheme()
  576. {
  577. const char *themeName = config_get_string(globalConfig, "General",
  578. "Theme");
  579. if (!themeName)
  580. themeName = "Default";
  581. stringstream t;
  582. t << themeName;
  583. return SetTheme(t.str());
  584. }
  585. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  586. : QApplication(argc, argv),
  587. profilerNameStore(store)
  588. {
  589. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  590. }
  591. OBSApp::~OBSApp()
  592. {
  593. #ifdef __APPLE__
  594. bool vsyncDiabled = config_get_bool(globalConfig, "Video",
  595. "DisableOSXVSync");
  596. bool resetVSync = config_get_bool(globalConfig, "Video",
  597. "ResetOSXVSyncOnExit");
  598. if (vsyncDiabled && resetVSync)
  599. EnableOSXVSync(true);
  600. #endif
  601. os_inhibit_sleep_set_active(sleepInhibitor, false);
  602. os_inhibit_sleep_destroy(sleepInhibitor);
  603. }
  604. static void move_basic_to_profiles(void)
  605. {
  606. char path[512];
  607. char new_path[512];
  608. os_glob_t *glob;
  609. /* if not first time use */
  610. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  611. return;
  612. if (!os_file_exists(path))
  613. return;
  614. /* if the profiles directory doesn't already exist */
  615. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  616. return;
  617. if (os_file_exists(new_path))
  618. return;
  619. if (os_mkdir(new_path) == MKDIR_ERROR)
  620. return;
  621. strcat(new_path, "/");
  622. strcat(new_path, Str("Untitled"));
  623. if (os_mkdir(new_path) == MKDIR_ERROR)
  624. return;
  625. strcat(path, "/*.*");
  626. if (os_glob(path, 0, &glob) != 0)
  627. return;
  628. strcpy(path, new_path);
  629. for (size_t i = 0; i < glob->gl_pathc; i++) {
  630. struct os_globent ent = glob->gl_pathv[i];
  631. char *file;
  632. if (ent.directory)
  633. continue;
  634. file = strrchr(ent.path, '/');
  635. if (!file++)
  636. continue;
  637. if (astrcmpi(file, "scenes.json") == 0)
  638. continue;
  639. strcpy(new_path, path);
  640. strcat(new_path, "/");
  641. strcat(new_path, file);
  642. os_rename(ent.path, new_path);
  643. }
  644. os_globfree(glob);
  645. }
  646. static void move_basic_to_scene_collections(void)
  647. {
  648. char path[512];
  649. char new_path[512];
  650. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  651. return;
  652. if (!os_file_exists(path))
  653. return;
  654. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  655. return;
  656. if (os_file_exists(new_path))
  657. return;
  658. if (os_mkdir(new_path) == MKDIR_ERROR)
  659. return;
  660. strcat(path, "/scenes.json");
  661. strcat(new_path, "/");
  662. strcat(new_path, Str("Untitled"));
  663. strcat(new_path, ".json");
  664. os_rename(path, new_path);
  665. }
  666. void OBSApp::AppInit()
  667. {
  668. ProfileScope("OBSApp::AppInit");
  669. if (!InitApplicationBundle())
  670. throw "Failed to initialize application bundle";
  671. if (!MakeUserDirs())
  672. throw "Failed to create required user directories";
  673. if (!InitGlobalConfig())
  674. throw "Failed to initialize global config";
  675. if (!InitLocale())
  676. throw "Failed to load locale";
  677. if (!InitTheme())
  678. throw "Failed to load theme";
  679. config_set_default_string(globalConfig, "Basic", "Profile",
  680. Str("Untitled"));
  681. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  682. Str("Untitled"));
  683. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  684. Str("Untitled"));
  685. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  686. Str("Untitled"));
  687. #ifdef __APPLE__
  688. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  689. EnableOSXVSync(false);
  690. #endif
  691. move_basic_to_profiles();
  692. move_basic_to_scene_collections();
  693. if (!MakeUserProfileDirs())
  694. throw "Failed to create profile directories";
  695. }
  696. const char *OBSApp::GetRenderModule() const
  697. {
  698. const char *renderer = config_get_string(globalConfig, "Video",
  699. "Renderer");
  700. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  701. DL_D3D11 : DL_OPENGL;
  702. }
  703. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  704. {
  705. char path[512];
  706. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  707. return false;
  708. return obs_startup(locale, path, store);
  709. }
  710. bool OBSApp::OBSInit()
  711. {
  712. ProfileScope("OBSApp::OBSInit");
  713. bool licenseAccepted = config_get_bool(globalConfig, "General",
  714. "LicenseAccepted");
  715. OBSLicenseAgreement agreement(nullptr);
  716. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  717. if (!licenseAccepted) {
  718. config_set_bool(globalConfig, "General",
  719. "LicenseAccepted", true);
  720. config_save(globalConfig);
  721. }
  722. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  723. return false;
  724. blog(LOG_INFO, "Portable mode: %s",
  725. portable_mode ? "true" : "false");
  726. mainWindow = new OBSBasic();
  727. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  728. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  729. mainWindow->OBSInit();
  730. connect(this, &QGuiApplication::applicationStateChanged,
  731. [](Qt::ApplicationState state)
  732. {
  733. obs_hotkey_enable_background_press(
  734. state != Qt::ApplicationActive);
  735. });
  736. obs_hotkey_enable_background_press(
  737. applicationState() != Qt::ApplicationActive);
  738. return true;
  739. } else {
  740. return false;
  741. }
  742. }
  743. string OBSApp::GetVersionString() const
  744. {
  745. stringstream ver;
  746. #ifdef HAVE_OBSCONFIG_H
  747. ver << OBS_VERSION;
  748. #else
  749. ver << LIBOBS_API_MAJOR_VER << "." <<
  750. LIBOBS_API_MINOR_VER << "." <<
  751. LIBOBS_API_PATCH_VER;
  752. #endif
  753. ver << " (";
  754. #ifdef _WIN32
  755. if (sizeof(void*) == 8)
  756. ver << "64bit, ";
  757. ver << "windows)";
  758. #elif __APPLE__
  759. ver << "mac)";
  760. #elif __FreeBSD__
  761. ver << "freebsd)";
  762. #else /* assume linux for the time being */
  763. ver << "linux)";
  764. #endif
  765. return ver.str();
  766. }
  767. bool OBSApp::IsPortableMode()
  768. {
  769. return portable_mode;
  770. }
  771. #ifdef __APPLE__
  772. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  773. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  774. #elif _WIN32
  775. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  776. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  777. #else
  778. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  779. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  780. #endif
  781. const char *OBSApp::InputAudioSource() const
  782. {
  783. return INPUT_AUDIO_SOURCE;
  784. }
  785. const char *OBSApp::OutputAudioSource() const
  786. {
  787. return OUTPUT_AUDIO_SOURCE;
  788. }
  789. const char *OBSApp::GetLastLog() const
  790. {
  791. return lastLogFile.c_str();
  792. }
  793. const char *OBSApp::GetCurrentLog() const
  794. {
  795. return currentLogFile.c_str();
  796. }
  797. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  798. {
  799. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  800. if (cb(lookupVal, out))
  801. return true;
  802. }
  803. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  804. }
  805. QString OBSTranslator::translate(const char *context, const char *sourceText,
  806. const char *disambiguation, int n) const
  807. {
  808. const char *out = nullptr;
  809. if (!App()->TranslateString(sourceText, &out))
  810. return QString(sourceText);
  811. UNUSED_PARAMETER(context);
  812. UNUSED_PARAMETER(disambiguation);
  813. UNUSED_PARAMETER(n);
  814. return QT_UTF8(out);
  815. }
  816. static bool get_token(lexer *lex, string &str, base_token_type type)
  817. {
  818. base_token token;
  819. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  820. return false;
  821. if (token.type != type)
  822. return false;
  823. str.assign(token.text.array, token.text.len);
  824. return true;
  825. }
  826. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  827. {
  828. base_token token;
  829. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  830. return false;
  831. if (token.type != type)
  832. return false;
  833. return strref_cmp(&token.text, str) == 0;
  834. }
  835. static uint64_t convert_log_name(const char *name)
  836. {
  837. BaseLexer lex;
  838. string year, month, day, hour, minute, second;
  839. lexer_start(lex, name);
  840. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  841. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  842. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  843. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  844. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  845. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  846. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  847. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  848. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  849. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  850. stringstream timestring;
  851. timestring << year << month << day << hour << minute << second;
  852. return std::stoull(timestring.str());
  853. }
  854. static void delete_oldest_file(const char *location)
  855. {
  856. BPtr<char> logDir(GetConfigPathPtr(location));
  857. string oldestLog;
  858. uint64_t oldest_ts = (uint64_t)-1;
  859. struct os_dirent *entry;
  860. unsigned int maxLogs = (unsigned int)config_get_uint(
  861. App()->GlobalConfig(), "General", "MaxLogs");
  862. os_dir_t *dir = os_opendir(logDir);
  863. if (dir) {
  864. unsigned int count = 0;
  865. while ((entry = os_readdir(dir)) != NULL) {
  866. if (entry->directory || *entry->d_name == '.')
  867. continue;
  868. uint64_t ts = convert_log_name(entry->d_name);
  869. if (ts) {
  870. if (ts < oldest_ts) {
  871. oldestLog = entry->d_name;
  872. oldest_ts = ts;
  873. }
  874. count++;
  875. }
  876. }
  877. os_closedir(dir);
  878. if (count > maxLogs) {
  879. stringstream delPath;
  880. delPath << logDir << "/" << oldestLog;
  881. os_unlink(delPath.str().c_str());
  882. }
  883. }
  884. }
  885. static void get_last_log(void)
  886. {
  887. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  888. struct os_dirent *entry;
  889. os_dir_t *dir = os_opendir(logDir);
  890. uint64_t highest_ts = 0;
  891. if (dir) {
  892. while ((entry = os_readdir(dir)) != NULL) {
  893. if (entry->directory || *entry->d_name == '.')
  894. continue;
  895. uint64_t ts = convert_log_name(entry->d_name);
  896. if (ts > highest_ts) {
  897. lastLogFile = entry->d_name;
  898. highest_ts = ts;
  899. }
  900. }
  901. os_closedir(dir);
  902. }
  903. }
  904. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  905. {
  906. time_t now = time(0);
  907. char file[256] = {};
  908. struct tm *cur_time;
  909. cur_time = localtime(&now);
  910. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  911. cur_time->tm_year+1900,
  912. cur_time->tm_mon+1,
  913. cur_time->tm_mday,
  914. noSpace ? '_' : ' ',
  915. cur_time->tm_hour,
  916. cur_time->tm_min,
  917. cur_time->tm_sec,
  918. extension);
  919. return string(file);
  920. }
  921. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  922. const char *format)
  923. {
  924. BPtr<char> filename = os_generate_formatted_filename(extension,
  925. !noSpace, format);
  926. return string(filename);
  927. }
  928. vector<pair<string, string>> GetLocaleNames()
  929. {
  930. string path;
  931. if (!GetDataFilePath("locale.ini", path))
  932. throw "Could not find locale.ini path";
  933. ConfigFile ini;
  934. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  935. throw "Could not open locale.ini";
  936. size_t sections = config_num_sections(ini);
  937. vector<pair<string, string>> names;
  938. names.reserve(sections);
  939. for (size_t i = 0; i < sections; i++) {
  940. const char *tag = config_get_section(ini, i);
  941. const char *name = config_get_string(ini, tag, "Name");
  942. names.emplace_back(tag, name);
  943. }
  944. return names;
  945. }
  946. static void create_log_file(fstream &logFile)
  947. {
  948. stringstream dst;
  949. get_last_log();
  950. currentLogFile = GenerateTimeDateFilename("txt");
  951. dst << "obs-studio/logs/" << currentLogFile.c_str();
  952. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  953. logFile.open(path,
  954. ios_base::in | ios_base::out | ios_base::trunc);
  955. if (logFile.is_open()) {
  956. delete_oldest_file("obs-studio/logs");
  957. base_set_log_handler(do_log, &logFile);
  958. } else {
  959. blog(LOG_ERROR, "Failed to open log file");
  960. }
  961. }
  962. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  963. {
  964. profiler_name_store_free(store);
  965. };
  966. using ProfilerNameStore =
  967. std::unique_ptr<profiler_name_store_t,
  968. decltype(ProfilerNameStoreRelease)>;
  969. ProfilerNameStore CreateNameStore()
  970. {
  971. return ProfilerNameStore{profiler_name_store_create(),
  972. ProfilerNameStoreRelease};
  973. }
  974. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  975. {
  976. profile_snapshot_free(snap);
  977. };
  978. using ProfilerSnapshot =
  979. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  980. ProfilerSnapshot GetSnapshot()
  981. {
  982. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  983. }
  984. static void SaveProfilerData(const ProfilerSnapshot &snap)
  985. {
  986. if (currentLogFile.empty())
  987. return;
  988. auto pos = currentLogFile.rfind('.');
  989. if (pos == currentLogFile.npos)
  990. return;
  991. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  992. ostringstream dst;
  993. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  994. dst.write(currentLogFile.c_str(), pos);
  995. dst.write(LITERAL_SIZE(".csv.gz"));
  996. #undef LITERAL_SIZE
  997. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  998. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  999. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1000. static_cast<const char*>(path));
  1001. }
  1002. static auto ProfilerFree = [](void *)
  1003. {
  1004. profiler_stop();
  1005. auto snap = GetSnapshot();
  1006. profiler_print(snap.get());
  1007. profiler_print_time_between_calls(snap.get());
  1008. SaveProfilerData(snap);
  1009. profiler_free();
  1010. };
  1011. static const char *run_program_init = "run_program_init";
  1012. static int run_program(fstream &logFile, int argc, char *argv[])
  1013. {
  1014. int ret = -1;
  1015. auto profilerNameStore = CreateNameStore();
  1016. std::unique_ptr<void, decltype(ProfilerFree)>
  1017. prof_release(static_cast<void*>(&ProfilerFree),
  1018. ProfilerFree);
  1019. profiler_start();
  1020. profile_register_root(run_program_init, 0);
  1021. ScopeProfiler prof{run_program_init};
  1022. QCoreApplication::addLibraryPath(".");
  1023. OBSApp program(argc, argv, profilerNameStore.get());
  1024. try {
  1025. program.AppInit();
  1026. OBSTranslator translator;
  1027. create_log_file(logFile);
  1028. delete_oldest_file("obs-studio/profiler_data");
  1029. program.installTranslator(&translator);
  1030. if (!program.OBSInit())
  1031. return 0;
  1032. prof.Stop();
  1033. return program.exec();
  1034. } catch (const char *error) {
  1035. blog(LOG_ERROR, "%s", error);
  1036. OBSErrorBox(nullptr, "%s", error);
  1037. }
  1038. return ret;
  1039. }
  1040. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  1041. #ifdef _WIN32
  1042. #define CRASH_MESSAGE \
  1043. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1044. "to the clipboard? (Crash logs will still be saved to the " \
  1045. "%appdata%\\obs-studio\\crashes directory)"
  1046. static void main_crash_handler(const char *format, va_list args, void *param)
  1047. {
  1048. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1049. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1050. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1051. delete_oldest_file("obs-studio/crashes");
  1052. string name = "obs-studio/crashes/Crash ";
  1053. name += GenerateTimeDateFilename("txt");
  1054. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1055. fstream file;
  1056. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1057. ios_base::binary);
  1058. file << text;
  1059. file.close();
  1060. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1061. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1062. if (ret == IDYES) {
  1063. size_t len = strlen(text);
  1064. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1065. memcpy(GlobalLock(mem), text, len);
  1066. GlobalUnlock(mem);
  1067. OpenClipboard(0);
  1068. EmptyClipboard();
  1069. SetClipboardData(CF_TEXT, mem);
  1070. CloseClipboard();
  1071. }
  1072. exit(-1);
  1073. UNUSED_PARAMETER(param);
  1074. }
  1075. static void load_debug_privilege(void)
  1076. {
  1077. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1078. TOKEN_PRIVILEGES tp;
  1079. HANDLE token;
  1080. LUID val;
  1081. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1082. return;
  1083. }
  1084. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1085. tp.PrivilegeCount = 1;
  1086. tp.Privileges[0].Luid = val;
  1087. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1088. AdjustTokenPrivileges(token, false, &tp,
  1089. sizeof(tp), NULL, NULL);
  1090. }
  1091. CloseHandle(token);
  1092. }
  1093. #endif
  1094. #ifdef __APPLE__
  1095. #define BASE_PATH ".."
  1096. #else
  1097. #define BASE_PATH "../.."
  1098. #endif
  1099. #define CONFIG_PATH BASE_PATH "/config"
  1100. #ifndef OBS_UNIX_STRUCTURE
  1101. #define OBS_UNIX_STRUCTURE 0
  1102. #endif
  1103. int GetConfigPath(char *path, size_t size, const char *name)
  1104. {
  1105. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1106. if (name && *name) {
  1107. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1108. } else {
  1109. return snprintf(path, size, CONFIG_PATH);
  1110. }
  1111. } else {
  1112. return os_get_config_path(path, size, name);
  1113. }
  1114. }
  1115. char *GetConfigPathPtr(const char *name)
  1116. {
  1117. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1118. char path[512];
  1119. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1120. return bstrdup(path);
  1121. } else {
  1122. return NULL;
  1123. }
  1124. } else {
  1125. return os_get_config_path_ptr(name);
  1126. }
  1127. }
  1128. int GetProgramDataPath(char *path, size_t size, const char *name)
  1129. {
  1130. return os_get_program_data_path(path, size, name);
  1131. }
  1132. char *GetProgramDataPathPtr(const char *name)
  1133. {
  1134. return os_get_program_data_path_ptr(name);
  1135. }
  1136. bool GetFileSafeName(const char *name, std::string &file)
  1137. {
  1138. size_t base_len = strlen(name);
  1139. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1140. std::wstring wfile;
  1141. if (!len)
  1142. return false;
  1143. wfile.resize(len);
  1144. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1145. for (size_t i = wfile.size(); i > 0; i--) {
  1146. size_t im1 = i - 1;
  1147. if (iswspace(wfile[im1])) {
  1148. wfile[im1] = '_';
  1149. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1150. wfile.erase(im1, 1);
  1151. }
  1152. }
  1153. if (wfile.size() == 0)
  1154. wfile = L"characters_only";
  1155. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1156. if (!len)
  1157. return false;
  1158. file.resize(len);
  1159. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1160. return true;
  1161. }
  1162. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1163. {
  1164. size_t len = path.size();
  1165. if (extension) {
  1166. path += ".";
  1167. path += extension;
  1168. }
  1169. if (!os_file_exists(path.c_str()))
  1170. return true;
  1171. int index = 1;
  1172. do {
  1173. path.resize(len);
  1174. path += std::to_string(++index);
  1175. if (extension) {
  1176. path += ".";
  1177. path += extension;
  1178. }
  1179. } while (os_file_exists(path.c_str()));
  1180. return true;
  1181. }
  1182. bool WindowPositionValid(QRect rect)
  1183. {
  1184. for (QScreen* screen: QGuiApplication::screens()) {
  1185. if (screen->availableGeometry().intersects(rect))
  1186. return true;
  1187. }
  1188. return false;
  1189. }
  1190. static inline bool arg_is(const char *arg,
  1191. const char *long_form, const char *short_form)
  1192. {
  1193. return (long_form && strcmp(arg, long_form) == 0) ||
  1194. (short_form && strcmp(arg, short_form) == 0);
  1195. }
  1196. #if !defined(_WIN32) && !defined(__APPLE__)
  1197. #define IS_UNIX 1
  1198. #endif
  1199. /* if using XDG and was previously using an older build of OBS, move config
  1200. * files to XDG directory */
  1201. #if defined(USE_XDG) && defined(IS_UNIX)
  1202. static void move_to_xdg(void)
  1203. {
  1204. char old_path[512];
  1205. char new_path[512];
  1206. char *home = getenv("HOME");
  1207. if (!home)
  1208. return;
  1209. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1210. return;
  1211. /* make base xdg path if it doesn't already exist */
  1212. if (GetConfigPath(new_path, 512, "") <= 0)
  1213. return;
  1214. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1215. return;
  1216. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1217. return;
  1218. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1219. rename(old_path, new_path);
  1220. }
  1221. }
  1222. #endif
  1223. static bool update_ffmpeg_output(ConfigFile &config)
  1224. {
  1225. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1226. return false;
  1227. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1228. if (!url)
  1229. return false;
  1230. bool isActualURL = strstr(url, "://") != nullptr;
  1231. if (isActualURL)
  1232. return false;
  1233. string urlStr = url;
  1234. string extension;
  1235. for (size_t i = urlStr.length(); i > 0; i--) {
  1236. size_t idx = i - 1;
  1237. if (urlStr[idx] == '.') {
  1238. extension = &urlStr[i];
  1239. }
  1240. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1241. urlStr[idx] = 0;
  1242. break;
  1243. }
  1244. }
  1245. if (urlStr.empty() || extension.empty())
  1246. return false;
  1247. config_remove_value(config, "AdvOut", "FFURL");
  1248. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1249. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1250. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1251. return true;
  1252. }
  1253. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1254. {
  1255. bool changed = false;
  1256. if (config_has_user_value(config, sec, "Reconnect")) {
  1257. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1258. config_set_bool(config, "Output", "Reconnect", reconnect);
  1259. changed = true;
  1260. }
  1261. if (config_has_user_value(config, sec, "RetryDelay")) {
  1262. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1263. config_set_uint(config, "Output", "RetryDelay", delay);
  1264. changed = true;
  1265. }
  1266. if (config_has_user_value(config, sec, "MaxRetries")) {
  1267. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1268. config_set_uint(config, "Output", "MaxRetries", retries);
  1269. changed = true;
  1270. }
  1271. return changed;
  1272. }
  1273. static bool update_reconnect(ConfigFile &config)
  1274. {
  1275. if (!config_has_user_value(config, "Output", "Mode"))
  1276. return false;
  1277. const char *mode = config_get_string(config, "Output", "Mode");
  1278. if (!mode)
  1279. return false;
  1280. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1281. "AdvOut" : "SimpleOutput";
  1282. if (move_reconnect_settings(config, section)) {
  1283. config_remove_value(config, "SimpleOutput", "Reconnect");
  1284. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1285. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1286. config_remove_value(config, "AdvOut", "Reconnect");
  1287. config_remove_value(config, "AdvOut", "RetryDelay");
  1288. config_remove_value(config, "AdvOut", "MaxRetries");
  1289. return true;
  1290. }
  1291. return false;
  1292. }
  1293. static void convert_x264_settings(obs_data_t *data)
  1294. {
  1295. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1296. if (use_bufsize) {
  1297. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1298. if (buffer_size == 0)
  1299. obs_data_set_string(data, "rate_control", "CRF");
  1300. }
  1301. }
  1302. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1303. {
  1304. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1305. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1306. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1307. bool modified = false;
  1308. bool cbr = true;
  1309. if (cbr_item) {
  1310. cbr = obs_data_item_get_bool(cbr_item);
  1311. obs_data_item_unset_user_value(cbr_item);
  1312. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1313. modified = true;
  1314. }
  1315. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1316. if (!cbr_item)
  1317. obs_data_set_string(data, "rate_control", "CBR");
  1318. else if (!cbr)
  1319. convert_x264_settings(data);
  1320. modified = true;
  1321. }
  1322. if (modified)
  1323. obs_data_save_json_safe(data, file, "tmp", "bak");
  1324. obs_data_item_release(&rc_item);
  1325. obs_data_item_release(&cbr_item);
  1326. obs_data_release(data);
  1327. }
  1328. static void upgrade_settings(void)
  1329. {
  1330. char path[512];
  1331. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1332. if (pathlen <= 0)
  1333. return;
  1334. if (!os_file_exists(path))
  1335. return;
  1336. os_dir_t *dir = os_opendir(path);
  1337. if (!dir)
  1338. return;
  1339. struct os_dirent *ent = os_readdir(dir);
  1340. while (ent) {
  1341. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1342. strcmp(ent->d_name, "..") != 0) {
  1343. strcat(path, "/");
  1344. strcat(path, ent->d_name);
  1345. strcat(path, "/basic.ini");
  1346. ConfigFile config;
  1347. int ret;
  1348. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1349. if (ret == CONFIG_SUCCESS) {
  1350. if (update_ffmpeg_output(config) ||
  1351. update_reconnect(config)) {
  1352. config_save_safe(config, "tmp",
  1353. nullptr);
  1354. }
  1355. }
  1356. if (config) {
  1357. const char *sEnc = config_get_string(config,
  1358. "AdvOut", "Encoder");
  1359. const char *rEnc = config_get_string(config,
  1360. "AdvOut", "RecEncoder");
  1361. /* replace "cbr" option with "rate_control" for
  1362. * each profile's encoder data */
  1363. path[pathlen] = 0;
  1364. strcat(path, "/");
  1365. strcat(path, ent->d_name);
  1366. strcat(path, "/recordEncoder.json");
  1367. convert_14_2_encoder_setting(rEnc, path);
  1368. path[pathlen] = 0;
  1369. strcat(path, "/");
  1370. strcat(path, ent->d_name);
  1371. strcat(path, "/streamEncoder.json");
  1372. convert_14_2_encoder_setting(sEnc, path);
  1373. }
  1374. path[pathlen] = 0;
  1375. }
  1376. ent = os_readdir(dir);
  1377. }
  1378. os_closedir(dir);
  1379. }
  1380. int main(int argc, char *argv[])
  1381. {
  1382. #ifndef _WIN32
  1383. signal(SIGPIPE, SIG_IGN);
  1384. #endif
  1385. #ifdef _WIN32
  1386. load_debug_privilege();
  1387. base_set_crash_handler(main_crash_handler, nullptr);
  1388. #endif
  1389. base_get_log_handler(&def_log_handler, nullptr);
  1390. #if defined(USE_XDG) && defined(IS_UNIX)
  1391. move_to_xdg();
  1392. #endif
  1393. for (int i = 1; i < argc; i++) {
  1394. if (arg_is(argv[i], "--portable", "-p")) {
  1395. portable_mode = true;
  1396. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1397. log_verbose = true;
  1398. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1399. unfiltered_log = true;
  1400. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1401. opt_start_streaming = true;
  1402. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1403. opt_start_recording = true;
  1404. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1405. opt_start_replaybuffer = true;
  1406. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1407. if (++i < argc) opt_starting_collection = argv[i];
  1408. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1409. if (++i < argc) opt_starting_profile = argv[i];
  1410. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1411. if (++i < argc) opt_starting_scene = argv[i];
  1412. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1413. opt_minimize_tray = true;
  1414. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1415. opt_studio_mode = true;
  1416. } else if (arg_is(argv[i], "--help", "-h")) {
  1417. std::cout <<
  1418. "--help, -h: Get list of available commands.\n\n" <<
  1419. "--startstreaming: Automatically start streaming.\n" <<
  1420. "--startrecording: Automatically start recording.\n" <<
  1421. "--startreplaybuffer: Start replay buffer.\n\n" <<
  1422. "--collection <string>: Use specific scene collection."
  1423. << "\n" <<
  1424. "--profile <string>: Use specific profile.\n" <<
  1425. "--scene <string>: Start with specific scene.\n\n" <<
  1426. "--studio-mode: Enable studio mode.\n" <<
  1427. "--minimize-to-tray: Minimize to system tray.\n" <<
  1428. "--portable, -p: Use portable mode.\n\n" <<
  1429. "--verbose: Make log more verbose.\n" <<
  1430. "--unfiltered_log: Make log unfiltered.\n\n" <<
  1431. "--version, -V: Get current version.\n";
  1432. exit(0);
  1433. } else if (arg_is(argv[i], "--version", "-V")) {
  1434. std::cout << "OBS Studio - " <<
  1435. App()->GetVersionString() << "\n";
  1436. exit(0);
  1437. } else {
  1438. std::cout <<
  1439. "Invalid arguments. Use --help or -h to get " <<
  1440. "a list of available command line arguments.\n";
  1441. exit(0);
  1442. }
  1443. }
  1444. #if !OBS_UNIX_STRUCTURE
  1445. if (!portable_mode) {
  1446. portable_mode =
  1447. os_file_exists(BASE_PATH "/portable_mode") ||
  1448. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1449. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1450. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1451. }
  1452. #endif
  1453. upgrade_settings();
  1454. fstream logFile;
  1455. curl_global_init(CURL_GLOBAL_ALL);
  1456. int ret = run_program(logFile, argc, argv);
  1457. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1458. base_set_log_handler(nullptr, nullptr);
  1459. return ret;
  1460. }