obs-main.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 <OBSApp.hpp>
  15. #include <dialogs/OBSLogViewer.hpp>
  16. #ifdef __APPLE__
  17. #include <dialogs/OBSPermissions.hpp>
  18. #endif
  19. #include <utility/BaseLexer.hpp>
  20. #include <utility/OBSTranslator.hpp>
  21. #include <utility/platform.hpp>
  22. #include <widgets/VolumeAccessibleInterface.hpp>
  23. #include <qt-wrappers.hpp>
  24. #include <util/platform.h>
  25. #include <util/profiler.h>
  26. #include <util/util.hpp>
  27. #ifdef _WIN32
  28. #include <util/windows/win-version.h>
  29. #endif
  30. #include <QProcess>
  31. #include <curl/curl.h>
  32. #include <fstream>
  33. #include <iostream>
  34. #include <sstream>
  35. #ifdef _WIN32
  36. #include <shellapi.h>
  37. #define WIN32_LEAN_AND_MEAN
  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. extern string currentLogFile;
  45. extern string lastLogFile;
  46. extern string lastCrashLogFile;
  47. bool portable_mode = false;
  48. bool steam = false;
  49. bool safe_mode = false;
  50. bool disable_3p_plugins = false;
  51. static bool unclean_shutdown = false;
  52. static bool disable_shutdown_check = false;
  53. static bool multi = false;
  54. static bool log_verbose = false;
  55. static bool unfiltered_log = false;
  56. bool opt_start_streaming = false;
  57. bool opt_start_recording = false;
  58. bool opt_studio_mode = false;
  59. bool opt_start_replaybuffer = false;
  60. bool opt_start_virtualcam = false;
  61. bool opt_minimize_tray = false;
  62. bool opt_allow_opengl = false;
  63. bool opt_always_on_top = false;
  64. bool opt_disable_updater = false;
  65. bool opt_disable_missing_files_check = false;
  66. string opt_starting_collection;
  67. string opt_starting_profile;
  68. string opt_starting_scene;
  69. bool restart = false;
  70. bool restart_safe = false;
  71. static QStringList arguments;
  72. QPointer<OBSLogViewer> obsLogViewer;
  73. string CurrentTimeString()
  74. {
  75. using namespace std::chrono;
  76. struct tm tstruct;
  77. char buf[80];
  78. auto tp = system_clock::now();
  79. auto now = system_clock::to_time_t(tp);
  80. tstruct = *localtime(&now);
  81. size_t written = strftime(buf, sizeof(buf), "%T", &tstruct);
  82. if (ratio_less<system_clock::period, seconds::period>::value && written && (sizeof(buf) - written) > 5) {
  83. auto tp_secs = time_point_cast<seconds>(tp);
  84. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  85. snprintf(buf + written, sizeof(buf) - written, ".%03u", static_cast<unsigned>(millis));
  86. }
  87. return buf;
  88. }
  89. static void LogString(fstream &logFile, const char *timeString, char *str, int log_level)
  90. {
  91. static mutex logfile_mutex;
  92. string msg;
  93. msg += timeString;
  94. msg += str;
  95. logfile_mutex.lock();
  96. logFile << msg << endl;
  97. logfile_mutex.unlock();
  98. if (!!obsLogViewer)
  99. QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine", Qt::QueuedConnection, Q_ARG(int, log_level),
  100. Q_ARG(QString, QString(msg.c_str())));
  101. }
  102. static inline void LogStringChunk(fstream &logFile, char *str, int log_level)
  103. {
  104. char *nextLine = str;
  105. string timeString = CurrentTimeString();
  106. timeString += ": ";
  107. while (*nextLine) {
  108. char *nextLine = strchr(str, '\n');
  109. if (!nextLine)
  110. break;
  111. if (nextLine != str && nextLine[-1] == '\r') {
  112. nextLine[-1] = 0;
  113. } else {
  114. nextLine[0] = 0;
  115. }
  116. LogString(logFile, timeString.c_str(), str, log_level);
  117. nextLine++;
  118. str = nextLine;
  119. }
  120. LogString(logFile, timeString.c_str(), str, log_level);
  121. }
  122. #define MAX_REPEATED_LINES 30
  123. #define MAX_CHAR_VARIATION (255 * 3)
  124. static inline int sum_chars(const char *str)
  125. {
  126. int val = 0;
  127. for (; *str != 0; str++)
  128. val += *str;
  129. return val;
  130. }
  131. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg, const char *output_str)
  132. {
  133. static mutex log_mutex;
  134. static const char *last_msg_ptr = nullptr;
  135. static int last_char_sum = 0;
  136. static int rep_count = 0;
  137. int new_sum = sum_chars(output_str);
  138. lock_guard<mutex> guard(log_mutex);
  139. if (unfiltered_log) {
  140. return false;
  141. }
  142. if (last_msg_ptr == msg) {
  143. int diff = std::abs(new_sum - last_char_sum);
  144. if (diff < MAX_CHAR_VARIATION) {
  145. return (rep_count++ >= MAX_REPEATED_LINES);
  146. }
  147. }
  148. if (rep_count > MAX_REPEATED_LINES) {
  149. logFile << CurrentTimeString() << ": Last log entry repeated for "
  150. << to_string(rep_count - MAX_REPEATED_LINES) << " more lines" << endl;
  151. }
  152. last_msg_ptr = msg;
  153. last_char_sum = new_sum;
  154. rep_count = 0;
  155. return false;
  156. }
  157. static void do_log(int log_level, const char *msg, va_list args, void *param)
  158. {
  159. fstream &logFile = *static_cast<fstream *>(param);
  160. char str[8192];
  161. #ifndef _WIN32
  162. va_list args2;
  163. va_copy(args2, args);
  164. #endif
  165. vsnprintf(str, sizeof(str), msg, args);
  166. #ifdef _WIN32
  167. if (IsDebuggerPresent()) {
  168. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  169. if (wNum > 1) {
  170. static wstring wide_buf;
  171. static mutex wide_mutex;
  172. lock_guard<mutex> lock(wide_mutex);
  173. wide_buf.reserve(wNum + 1);
  174. wide_buf.resize(wNum - 1);
  175. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0], wNum);
  176. wide_buf.push_back('\n');
  177. OutputDebugStringW(wide_buf.c_str());
  178. }
  179. }
  180. #endif
  181. #if !defined(_WIN32) && defined(_DEBUG)
  182. def_log_handler(log_level, msg, args2, nullptr);
  183. #endif
  184. if (log_level <= LOG_INFO || log_verbose) {
  185. #if !defined(_WIN32) && !defined(_DEBUG)
  186. def_log_handler(log_level, msg, args2, nullptr);
  187. #endif
  188. if (!too_many_repeated_entries(logFile, msg, str))
  189. LogStringChunk(logFile, str, log_level);
  190. }
  191. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  192. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  193. __debugbreak();
  194. #endif
  195. #ifndef _WIN32
  196. va_end(args2);
  197. #endif
  198. }
  199. static bool get_token(lexer *lex, string &str, base_token_type type)
  200. {
  201. base_token token;
  202. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  203. return false;
  204. if (token.type != type)
  205. return false;
  206. str.assign(token.text.array, token.text.len);
  207. return true;
  208. }
  209. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  210. {
  211. base_token token;
  212. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  213. return false;
  214. if (token.type != type)
  215. return false;
  216. return strref_cmp(&token.text, str) == 0;
  217. }
  218. static uint64_t convert_log_name(bool has_prefix, const char *name)
  219. {
  220. BaseLexer lex;
  221. string year, month, day, hour, minute, second;
  222. lexer_start(lex, name);
  223. if (has_prefix) {
  224. string temp;
  225. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  226. return 0;
  227. }
  228. if (!get_token(lex, year, BASETOKEN_DIGIT))
  229. return 0;
  230. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  231. return 0;
  232. if (!get_token(lex, month, BASETOKEN_DIGIT))
  233. return 0;
  234. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  235. return 0;
  236. if (!get_token(lex, day, BASETOKEN_DIGIT))
  237. return 0;
  238. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  239. return 0;
  240. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  241. return 0;
  242. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  243. return 0;
  244. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  245. return 0;
  246. if (!get_token(lex, second, BASETOKEN_DIGIT))
  247. return 0;
  248. stringstream timestring;
  249. timestring << year << month << day << hour << minute << second;
  250. return std::stoull(timestring.str());
  251. }
  252. /* If upgrading from an older (non-XDG) build of OBS, move config files to XDG directory. */
  253. /* TODO: Remove after version 32.0. */
  254. #if defined(__FreeBSD__)
  255. static void move_to_xdg(void)
  256. {
  257. char old_path[512];
  258. char new_path[512];
  259. char *home = getenv("HOME");
  260. if (!home)
  261. return;
  262. if (snprintf(old_path, sizeof(old_path), "%s/.obs-studio", home) <= 0)
  263. return;
  264. /* make base xdg path if it doesn't already exist */
  265. if (GetAppConfigPath(new_path, sizeof(new_path), "") <= 0)
  266. return;
  267. if (os_mkdirs(new_path) == MKDIR_ERROR)
  268. return;
  269. if (GetAppConfigPath(new_path, sizeof(new_path), "obs-studio") <= 0)
  270. return;
  271. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  272. rename(old_path, new_path);
  273. }
  274. }
  275. #endif
  276. static void delete_oldest_file(bool has_prefix, const char *location)
  277. {
  278. BPtr<char> logDir(GetAppConfigPathPtr(location));
  279. string oldestLog;
  280. uint64_t oldest_ts = (uint64_t)-1;
  281. struct os_dirent *entry;
  282. unsigned int maxLogs = (unsigned int)config_get_uint(App()->GetAppConfig(), "General", "MaxLogs");
  283. os_dir_t *dir = os_opendir(logDir);
  284. if (dir) {
  285. unsigned int count = 0;
  286. while ((entry = os_readdir(dir)) != NULL) {
  287. if (entry->directory || *entry->d_name == '.')
  288. continue;
  289. uint64_t ts = convert_log_name(has_prefix, entry->d_name);
  290. if (ts) {
  291. if (ts < oldest_ts) {
  292. oldestLog = entry->d_name;
  293. oldest_ts = ts;
  294. }
  295. count++;
  296. }
  297. }
  298. os_closedir(dir);
  299. if (count > maxLogs) {
  300. stringstream delPath;
  301. delPath << logDir << "/" << oldestLog;
  302. os_unlink(delPath.str().c_str());
  303. }
  304. }
  305. }
  306. static void get_last_log(bool has_prefix, const char *subdir_to_use, std::string &last)
  307. {
  308. BPtr<char> logDir(GetAppConfigPathPtr(subdir_to_use));
  309. struct os_dirent *entry;
  310. os_dir_t *dir = os_opendir(logDir);
  311. uint64_t highest_ts = 0;
  312. if (dir) {
  313. while ((entry = os_readdir(dir)) != NULL) {
  314. if (entry->directory || *entry->d_name == '.')
  315. continue;
  316. uint64_t ts = convert_log_name(has_prefix, entry->d_name);
  317. if (ts > highest_ts) {
  318. last = entry->d_name;
  319. highest_ts = ts;
  320. }
  321. }
  322. os_closedir(dir);
  323. }
  324. }
  325. static void create_log_file(fstream &logFile)
  326. {
  327. stringstream dst;
  328. get_last_log(false, "obs-studio/logs", lastLogFile);
  329. #ifdef _WIN32
  330. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  331. #endif
  332. currentLogFile = GenerateTimeDateFilename("txt");
  333. dst << "obs-studio/logs/" << currentLogFile.c_str();
  334. BPtr<char> path(GetAppConfigPathPtr(dst.str().c_str()));
  335. #ifdef _WIN32
  336. BPtr<wchar_t> wpath;
  337. os_utf8_to_wcs_ptr(path, 0, &wpath);
  338. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  339. #else
  340. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  341. #endif
  342. if (logFile.is_open()) {
  343. delete_oldest_file(false, "obs-studio/logs");
  344. base_set_log_handler(do_log, &logFile);
  345. } else {
  346. blog(LOG_ERROR, "Failed to open log file");
  347. }
  348. }
  349. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  350. profiler_name_store_free(store);
  351. };
  352. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t, decltype(ProfilerNameStoreRelease)>;
  353. ProfilerNameStore CreateNameStore()
  354. {
  355. return ProfilerNameStore{profiler_name_store_create(), ProfilerNameStoreRelease};
  356. }
  357. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  358. profile_snapshot_free(snap);
  359. };
  360. using ProfilerSnapshot = std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  361. ProfilerSnapshot GetSnapshot()
  362. {
  363. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  364. }
  365. static void SaveProfilerData(const ProfilerSnapshot &snap)
  366. {
  367. if (currentLogFile.empty())
  368. return;
  369. auto pos = currentLogFile.rfind('.');
  370. if (pos == currentLogFile.npos)
  371. return;
  372. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  373. ostringstream dst;
  374. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  375. dst.write(currentLogFile.c_str(), pos);
  376. dst.write(LITERAL_SIZE(".csv.gz"));
  377. #undef LITERAL_SIZE
  378. BPtr<char> path = GetAppConfigPathPtr(dst.str().c_str());
  379. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  380. blog(LOG_WARNING, "Could not save profiler data to '%s'", static_cast<const char *>(path));
  381. }
  382. static auto ProfilerFree = [](void *) {
  383. profiler_stop();
  384. auto snap = GetSnapshot();
  385. profiler_print(snap.get());
  386. profiler_print_time_between_calls(snap.get());
  387. SaveProfilerData(snap);
  388. profiler_free();
  389. };
  390. QAccessibleInterface *accessibleFactory(const QString &classname, QObject *object)
  391. {
  392. if (classname == QLatin1String("VolumeSlider") && object && object->isWidgetType())
  393. return new VolumeAccessibleInterface(static_cast<QWidget *>(object));
  394. return nullptr;
  395. }
  396. static const char *run_program_init = "run_program_init";
  397. static int run_program(fstream &logFile, int argc, char *argv[])
  398. {
  399. int ret = -1;
  400. auto profilerNameStore = CreateNameStore();
  401. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(static_cast<void *>(&ProfilerFree), ProfilerFree);
  402. profiler_start();
  403. profile_register_root(run_program_init, 0);
  404. ScopeProfiler prof{run_program_init};
  405. #ifdef _WIN32
  406. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  407. #endif
  408. QCoreApplication::addLibraryPath(".");
  409. #if __APPLE__
  410. InstallNSApplicationSubclass();
  411. InstallNSThreadLocks();
  412. if (!isInBundle()) {
  413. blog(LOG_ERROR,
  414. "OBS cannot be run as a standalone binary on macOS. Run the Application bundle instead.");
  415. return ret;
  416. }
  417. #endif
  418. #if !defined(_WIN32) && !defined(__APPLE__)
  419. /* NOTE: Users blindly set this, but this theme is incompatble with Qt6 and
  420. * crashes loading saved geometry. Just turn off this theme and let users complain OBS
  421. * looks ugly instead of crashing. */
  422. const char *platform_theme = getenv("QT_QPA_PLATFORMTHEME");
  423. if (platform_theme && strcmp(platform_theme, "qt5ct") == 0)
  424. unsetenv("QT_QPA_PLATFORMTHEME");
  425. #endif
  426. /* NOTE: This disables an optimisation in Qt that attempts to determine if
  427. * any "siblings" intersect with a widget when determining the approximate
  428. * visible/unobscured area. However, by Qt's own admission this is slow
  429. * and in the case of OBS it significantly slows down lists with many
  430. * elements (e.g. Hotkeys) and it is actually faster to disable it. */
  431. qputenv("QT_NO_SUBTRACTOPAQUESIBLINGS", "1");
  432. OBSApp program(argc, argv, profilerNameStore.get());
  433. try {
  434. QAccessible::installFactory(accessibleFactory);
  435. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Regular.ttf");
  436. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Bold.ttf");
  437. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Italic.ttf");
  438. bool created_log = false;
  439. program.AppInit();
  440. delete_oldest_file(false, "obs-studio/profiler_data");
  441. OBSTranslator translator;
  442. program.installTranslator(&translator);
  443. /* --------------------------------------- */
  444. /* check and warn if already running */
  445. bool cancel_launch = false;
  446. bool already_running = false;
  447. #ifdef _WIN32
  448. RunOnceMutex rom =
  449. #endif
  450. CheckIfAlreadyRunning(already_running);
  451. if (!already_running) {
  452. goto run;
  453. }
  454. if (!multi) {
  455. QMessageBox mb(QMessageBox::Question, QTStr("AlreadyRunning.Title"),
  456. QTStr("AlreadyRunning.Text"));
  457. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::YesRole);
  458. QPushButton *cancelButton = mb.addButton(QTStr("Cancel"), QMessageBox::NoRole);
  459. mb.setDefaultButton(cancelButton);
  460. mb.exec();
  461. cancel_launch = mb.clickedButton() == cancelButton;
  462. }
  463. if (cancel_launch)
  464. return 0;
  465. if (!created_log) {
  466. create_log_file(logFile);
  467. created_log = true;
  468. }
  469. if (multi) {
  470. blog(LOG_INFO, "User enabled --multi flag and is now "
  471. "running multiple instances of OBS.");
  472. } else {
  473. blog(LOG_WARNING, "================================");
  474. blog(LOG_WARNING, "Warning: OBS is already running!");
  475. blog(LOG_WARNING, "================================");
  476. blog(LOG_WARNING, "User is now running multiple "
  477. "instances of OBS!");
  478. /* Clear unclean_shutdown flag as multiple instances
  479. * running from the same config will lead to a
  480. * false-positive detection.*/
  481. unclean_shutdown = false;
  482. }
  483. /* --------------------------------------- */
  484. run:
  485. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  486. // Mounted by termina during chromeOS linux container startup
  487. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  488. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  489. if (crosDir) {
  490. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  491. QMessageBox mb(QMessageBox::Critical, QTStr("ChromeOS.Title"), QTStr("ChromeOS.Text"), buttons,
  492. nullptr);
  493. mb.exec();
  494. return 0;
  495. }
  496. #endif
  497. if (!created_log)
  498. create_log_file(logFile);
  499. if (unclean_shutdown) {
  500. blog(LOG_WARNING, "[Safe Mode] Unclean shutdown detected!");
  501. }
  502. if (unclean_shutdown && !safe_mode) {
  503. QMessageBox mb(QMessageBox::Warning, QTStr("AutoSafeMode.Title"), QTStr("AutoSafeMode.Text"));
  504. QPushButton *launchSafeButton =
  505. mb.addButton(QTStr("AutoSafeMode.LaunchSafe"), QMessageBox::AcceptRole);
  506. QPushButton *launchNormalButton =
  507. mb.addButton(QTStr("AutoSafeMode.LaunchNormal"), QMessageBox::RejectRole);
  508. mb.setDefaultButton(launchNormalButton);
  509. mb.exec();
  510. safe_mode = mb.clickedButton() == launchSafeButton;
  511. if (safe_mode) {
  512. blog(LOG_INFO, "[Safe Mode] User has launched in Safe Mode.");
  513. } else {
  514. blog(LOG_WARNING, "[Safe Mode] User elected to launch normally.");
  515. }
  516. }
  517. qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &, const QString &message) {
  518. switch (type) {
  519. #ifdef _DEBUG
  520. case QtDebugMsg:
  521. blog(LOG_DEBUG, "%s", QT_TO_UTF8(message));
  522. break;
  523. case QtInfoMsg:
  524. blog(LOG_INFO, "%s", QT_TO_UTF8(message));
  525. break;
  526. #else
  527. case QtDebugMsg:
  528. case QtInfoMsg:
  529. break;
  530. #endif
  531. case QtWarningMsg:
  532. blog(LOG_WARNING, "%s", QT_TO_UTF8(message));
  533. break;
  534. case QtCriticalMsg:
  535. case QtFatalMsg:
  536. blog(LOG_ERROR, "%s", QT_TO_UTF8(message));
  537. break;
  538. }
  539. });
  540. #ifdef __APPLE__
  541. MacPermissionStatus audio_permission = CheckPermission(kAudioDeviceAccess);
  542. MacPermissionStatus video_permission = CheckPermission(kVideoDeviceAccess);
  543. MacPermissionStatus input_monitoring_permission = CheckPermission(kInputMonitoring);
  544. MacPermissionStatus screen_permission = CheckPermission(kScreenCapture);
  545. int permissionsDialogLastShown =
  546. config_get_int(App()->GetAppConfig(), "General", "MacOSPermissionsDialogLastShown");
  547. if (permissionsDialogLastShown < MACOS_PERMISSIONS_DIALOG_VERSION) {
  548. OBSPermissions check(nullptr, screen_permission, video_permission, audio_permission,
  549. input_monitoring_permission);
  550. check.exec();
  551. }
  552. #endif
  553. #ifdef _WIN32
  554. if (IsRunningOnWine()) {
  555. QMessageBox mb(QMessageBox::Question, QTStr("Wine.Title"), QTStr("Wine.Text"));
  556. mb.setTextFormat(Qt::RichText);
  557. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::AcceptRole);
  558. QPushButton *closeButton = mb.addButton(QMessageBox::Close);
  559. mb.setDefaultButton(closeButton);
  560. mb.exec();
  561. if (mb.clickedButton() == closeButton)
  562. return 0;
  563. }
  564. #endif
  565. if (argc > 1) {
  566. stringstream stor;
  567. stor << argv[1];
  568. for (int i = 2; i < argc; ++i) {
  569. stor << " " << argv[i];
  570. }
  571. blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str());
  572. }
  573. if (!program.OBSInit())
  574. return 0;
  575. prof.Stop();
  576. ret = program.exec();
  577. } catch (const char *error) {
  578. blog(LOG_ERROR, "%s", error);
  579. OBSErrorBox(nullptr, "%s", error);
  580. }
  581. if (restart || restart_safe) {
  582. arguments = qApp->arguments();
  583. if (restart_safe) {
  584. arguments.append("--safe-mode");
  585. } else {
  586. arguments.removeAll("--safe-mode");
  587. }
  588. }
  589. return ret;
  590. }
  591. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  592. #ifdef _WIN32
  593. #define CRASH_MESSAGE \
  594. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  595. "to the clipboard? The crash log will still be saved to:\n\n%s"
  596. static void main_crash_handler(const char *format, va_list args, void * /* param */)
  597. {
  598. char *text = new char[MAX_CRASH_REPORT_SIZE];
  599. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  600. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  601. string crashFilePath = "obs-studio/crashes";
  602. delete_oldest_file(true, crashFilePath.c_str());
  603. string name = crashFilePath + "/";
  604. name += "Crash " + GenerateTimeDateFilename("txt");
  605. BPtr<char> path(GetAppConfigPathPtr(name.c_str()));
  606. fstream file;
  607. #ifdef _WIN32
  608. BPtr<wchar_t> wpath;
  609. os_utf8_to_wcs_ptr(path, 0, &wpath);
  610. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
  611. #else
  612. file.open(path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
  613. #endif
  614. file << text;
  615. file.close();
  616. string pathString(path.Get());
  617. #ifdef _WIN32
  618. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  619. #endif
  620. string absolutePath = canonical(filesystem::path(pathString)).u8string();
  621. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  622. unique_ptr<char[]> message_buffer(new char[size + 1]);
  623. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE, absolutePath.c_str());
  624. string finalMessage = string(message_buffer.get(), message_buffer.get() + size);
  625. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!", MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  626. if (ret == IDYES) {
  627. size_t len = strlen(text);
  628. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  629. memcpy(GlobalLock(mem), text, len);
  630. GlobalUnlock(mem);
  631. OpenClipboard(0);
  632. EmptyClipboard();
  633. SetClipboardData(CF_TEXT, mem);
  634. CloseClipboard();
  635. }
  636. exit(-1);
  637. }
  638. static void load_debug_privilege(void)
  639. {
  640. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  641. TOKEN_PRIVILEGES tp;
  642. HANDLE token;
  643. LUID val;
  644. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  645. return;
  646. }
  647. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  648. tp.PrivilegeCount = 1;
  649. tp.Privileges[0].Luid = val;
  650. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  651. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL);
  652. }
  653. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  654. tp.PrivilegeCount = 1;
  655. tp.Privileges[0].Luid = val;
  656. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  657. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL)) {
  658. blog(LOG_INFO, "Could not set privilege to "
  659. "increase GPU priority");
  660. }
  661. }
  662. CloseHandle(token);
  663. }
  664. #endif
  665. static inline bool arg_is(const char *arg, const char *long_form, const char *short_form)
  666. {
  667. return (long_form && strcmp(arg, long_form) == 0) || (short_form && strcmp(arg, short_form) == 0);
  668. }
  669. static void check_safe_mode_sentinel(void)
  670. {
  671. #ifndef NDEBUG
  672. /* Safe Mode detection is disabled in Debug builds to keep developers
  673. * somewhat sane. */
  674. return;
  675. #else
  676. if (disable_shutdown_check)
  677. return;
  678. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  679. if (os_file_exists(sentinelPath)) {
  680. unclean_shutdown = true;
  681. return;
  682. }
  683. os_quick_write_utf8_file(sentinelPath, nullptr, 0, false);
  684. #endif
  685. }
  686. static void delete_safe_mode_sentinel(void)
  687. {
  688. #ifndef NDEBUG
  689. return;
  690. #else
  691. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  692. os_unlink(sentinelPath);
  693. #endif
  694. }
  695. #ifdef _WIN32
  696. static constexpr char vcRunErrorTitle[] = "Outdated Visual C++ Runtime";
  697. static constexpr char vcRunErrorMsg[] = "OBS Studio requires a newer version of the Microsoft Visual C++ "
  698. "Redistributables.\n\nYou will now be directed to the download page.";
  699. static constexpr char vcRunInstallerUrl[] = "https://obsproject.com/visual-studio-2022-runtimes";
  700. static bool vc_runtime_outdated()
  701. {
  702. win_version_info ver;
  703. if (!get_dll_ver(L"msvcp140.dll", &ver))
  704. return true;
  705. /* Major is always 14 (hence 140.dll), so we only care about minor. */
  706. if (ver.minor >= 40)
  707. return false;
  708. int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle, MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL);
  709. if (choice == IDOK) {
  710. /* Open the URL in the default browser. */
  711. ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL, SW_SHOWNORMAL);
  712. }
  713. return true;
  714. }
  715. #endif
  716. #if defined(__APPLE__) || defined(__linux__)
  717. #define BASE_PATH ".."
  718. #else
  719. #define BASE_PATH "../.."
  720. #endif
  721. #if defined(ENABLE_PORTABLE_CONFIG) || defined(_WIN32)
  722. #define ALLOW_PORTABLE_MODE 1
  723. #else
  724. #define ALLOW_PORTABLE_MODE 0
  725. #endif
  726. int main(int argc, char *argv[])
  727. {
  728. #ifndef _WIN32
  729. signal(SIGPIPE, SIG_IGN);
  730. struct sigaction sig_handler;
  731. sig_handler.sa_handler = OBSApp::SigIntSignalHandler;
  732. sigemptyset(&sig_handler.sa_mask);
  733. sig_handler.sa_flags = 0;
  734. sigaction(SIGINT, &sig_handler, NULL);
  735. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  736. a closed pipe. */
  737. sigset_t sigpipe_mask;
  738. sigemptyset(&sigpipe_mask);
  739. sigaddset(&sigpipe_mask, SIGPIPE);
  740. sigset_t saved_mask;
  741. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  742. perror("pthread_sigmask");
  743. exit(1);
  744. }
  745. #endif
  746. #ifdef _WIN32
  747. // Abort as early as possible if MSVC runtime is outdated
  748. if (vc_runtime_outdated())
  749. return 1;
  750. // Try to keep this as early as possible
  751. install_dll_blocklist_hook();
  752. obs_init_win32_crash_handler();
  753. SetErrorMode(SEM_FAILCRITICALERRORS);
  754. load_debug_privilege();
  755. base_set_crash_handler(main_crash_handler, nullptr);
  756. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  757. if (hRtwq) {
  758. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  759. PFN_RtwqStartup func = (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  760. func();
  761. }
  762. #endif
  763. base_get_log_handler(&def_log_handler, nullptr);
  764. #if defined(__FreeBSD__)
  765. move_to_xdg();
  766. #endif
  767. obs_set_cmdline_args(argc, argv);
  768. for (int i = 1; i < argc; i++) {
  769. if (arg_is(argv[i], "--multi", "-m")) {
  770. multi = true;
  771. disable_shutdown_check = true;
  772. #if ALLOW_PORTABLE_MODE
  773. } else if (arg_is(argv[i], "--portable", "-p")) {
  774. portable_mode = true;
  775. #endif
  776. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  777. log_verbose = true;
  778. } else if (arg_is(argv[i], "--safe-mode", nullptr)) {
  779. safe_mode = true;
  780. } else if (arg_is(argv[i], "--only-bundled-plugins", nullptr)) {
  781. disable_3p_plugins = true;
  782. } else if (arg_is(argv[i], "--disable-shutdown-check", nullptr)) {
  783. /* This exists mostly to bypass the dialog during development. */
  784. disable_shutdown_check = true;
  785. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  786. opt_always_on_top = true;
  787. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  788. unfiltered_log = true;
  789. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  790. opt_start_streaming = true;
  791. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  792. opt_start_recording = true;
  793. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  794. opt_start_replaybuffer = true;
  795. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  796. opt_start_virtualcam = true;
  797. } else if (arg_is(argv[i], "--collection", nullptr)) {
  798. if (++i < argc)
  799. opt_starting_collection = argv[i];
  800. } else if (arg_is(argv[i], "--profile", nullptr)) {
  801. if (++i < argc)
  802. opt_starting_profile = argv[i];
  803. } else if (arg_is(argv[i], "--scene", nullptr)) {
  804. if (++i < argc)
  805. opt_starting_scene = argv[i];
  806. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  807. opt_minimize_tray = true;
  808. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  809. opt_studio_mode = true;
  810. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  811. opt_allow_opengl = true;
  812. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  813. opt_disable_updater = true;
  814. } else if (arg_is(argv[i], "--disable-missing-files-check", nullptr)) {
  815. opt_disable_missing_files_check = true;
  816. } else if (arg_is(argv[i], "--steam", nullptr)) {
  817. steam = true;
  818. } else if (arg_is(argv[i], "--help", "-h")) {
  819. std::string help =
  820. "--help, -h: Get list of available commands.\n\n"
  821. "--startstreaming: Automatically start streaming.\n"
  822. "--startrecording: Automatically start recording.\n"
  823. "--startreplaybuffer: Start replay buffer.\n"
  824. "--startvirtualcam: Start virtual camera (if available).\n\n"
  825. "--collection <string>: Use specific scene collection."
  826. "\n"
  827. "--profile <string>: Use specific profile.\n"
  828. "--scene <string>: Start with specific scene.\n\n"
  829. "--studio-mode: Enable studio mode.\n"
  830. "--minimize-to-tray: Minimize to system tray.\n"
  831. #if ALLOW_PORTABLE_MODE
  832. "--portable, -p: Use portable mode.\n"
  833. #endif
  834. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  835. "--safe-mode: Run in Safe Mode (disables third-party plugins, scripting, and WebSockets).\n"
  836. "--only-bundled-plugins: Only load included (first-party) plugins\n"
  837. "--disable-shutdown-check: Disable unclean shutdown detection.\n"
  838. "--verbose: Make log more verbose.\n"
  839. "--always-on-top: Start in 'always on top' mode.\n\n"
  840. "--unfiltered_log: Make log unfiltered.\n\n"
  841. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  842. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n";
  843. #ifdef _WIN32
  844. MessageBoxA(NULL, help.c_str(), "Help", MB_OK | MB_ICONASTERISK);
  845. #else
  846. std::cout << help << "--version, -V: Get current version.\n";
  847. #endif
  848. exit(0);
  849. } else if (arg_is(argv[i], "--version", "-V")) {
  850. std::cout << "OBS Studio - " << App()->GetVersionString(false) << "\n";
  851. exit(0);
  852. }
  853. }
  854. #if ALLOW_PORTABLE_MODE
  855. if (!portable_mode) {
  856. portable_mode = os_file_exists(BASE_PATH "/portable_mode") ||
  857. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  858. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  859. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  860. }
  861. if (!opt_disable_updater) {
  862. opt_disable_updater = os_file_exists(BASE_PATH "/disable_updater") ||
  863. os_file_exists(BASE_PATH "/disable_updater.txt");
  864. }
  865. if (!opt_disable_missing_files_check) {
  866. opt_disable_missing_files_check = os_file_exists(BASE_PATH "/disable_missing_files_check") ||
  867. os_file_exists(BASE_PATH "/disable_missing_files_check.txt");
  868. }
  869. #endif
  870. check_safe_mode_sentinel();
  871. fstream logFile;
  872. curl_global_init(CURL_GLOBAL_ALL);
  873. int ret = run_program(logFile, argc, argv);
  874. #ifdef _WIN32
  875. if (hRtwq) {
  876. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  877. PFN_RtwqShutdown func = (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  878. func();
  879. FreeLibrary(hRtwq);
  880. }
  881. log_blocked_dlls();
  882. #endif
  883. delete_safe_mode_sentinel();
  884. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  885. base_set_log_handler(nullptr, nullptr);
  886. if (restart || restart_safe) {
  887. auto executable = arguments.takeFirst();
  888. QProcess::startDetached(executable, arguments);
  889. }
  890. return ret;
  891. }