obs-app.cpp 41 KB

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