obs-app.cpp 41 KB

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