obs-app.cpp 41 KB

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