obs-main.cpp 28 KB

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