obs-app.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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 <sstream>
  17. #include <util/bmem.h>
  18. #include <util/dstr.h>
  19. #include <util/platform.h>
  20. #include <obs-config.h>
  21. #include <obs.hpp>
  22. #include <QProxyStyle>
  23. #include "qt-wrappers.hpp"
  24. #include "obs-app.hpp"
  25. #include "window-basic-main.hpp"
  26. #include "window-basic-settings.hpp"
  27. #include "window-license-agreement.hpp"
  28. #include "crash-report.hpp"
  29. #include "platform.hpp"
  30. #include <fstream>
  31. #ifdef _WIN32
  32. #include <windows.h>
  33. #else
  34. #include <signal.h>
  35. #endif
  36. using namespace std;
  37. static log_handler_t def_log_handler;
  38. static string currentLogFile;
  39. static string lastLogFile;
  40. static bool portable_mode = false;
  41. QObject *CreateShortcutFilter()
  42. {
  43. return new OBSEventFilter([](QObject *, QEvent *event)
  44. {
  45. auto mouse_event = [](QMouseEvent &event)
  46. {
  47. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  48. bool pressed = event.type() == QEvent::MouseButtonPress;
  49. switch (event.button()) {
  50. case Qt::NoButton:
  51. case Qt::LeftButton:
  52. case Qt::RightButton:
  53. case Qt::AllButtons:
  54. case Qt::MouseButtonMask:
  55. return false;
  56. case Qt::MidButton:
  57. hotkey.key = OBS_KEY_MOUSE3;
  58. break;
  59. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  60. hotkey.key = OBS_KEY_MOUSE ## j; break;
  61. MAP_BUTTON( 1, 4);
  62. MAP_BUTTON( 2, 5);
  63. MAP_BUTTON( 3, 6);
  64. MAP_BUTTON( 4, 7);
  65. MAP_BUTTON( 5, 8);
  66. MAP_BUTTON( 6, 9);
  67. MAP_BUTTON( 7, 10);
  68. MAP_BUTTON( 8, 11);
  69. MAP_BUTTON( 9, 12);
  70. MAP_BUTTON(10, 13);
  71. MAP_BUTTON(11, 14);
  72. MAP_BUTTON(12, 15);
  73. MAP_BUTTON(13, 16);
  74. MAP_BUTTON(14, 17);
  75. MAP_BUTTON(15, 18);
  76. MAP_BUTTON(16, 19);
  77. MAP_BUTTON(17, 20);
  78. MAP_BUTTON(18, 21);
  79. MAP_BUTTON(19, 22);
  80. MAP_BUTTON(20, 23);
  81. MAP_BUTTON(21, 24);
  82. MAP_BUTTON(22, 25);
  83. MAP_BUTTON(23, 26);
  84. MAP_BUTTON(24, 27);
  85. #undef MAP_BUTTON
  86. }
  87. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  88. event.modifiers());
  89. obs_hotkey_inject_event(hotkey, pressed);
  90. return true;
  91. };
  92. auto key_event = [](QKeyEvent *event)
  93. {
  94. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  95. bool pressed = event->type() == QEvent::KeyPress;
  96. switch (event->key()) {
  97. case Qt::Key_Shift:
  98. case Qt::Key_Control:
  99. case Qt::Key_Alt:
  100. case Qt::Key_Meta:
  101. break;
  102. #ifdef __APPLE__
  103. case Qt::Key_CapsLock:
  104. // kVK_CapsLock == 57
  105. hotkey.key = obs_key_from_virtual_key(57);
  106. pressed = true;
  107. break;
  108. #endif
  109. default:
  110. hotkey.key = obs_key_from_virtual_key(
  111. event->nativeVirtualKey());
  112. }
  113. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  114. event->modifiers());
  115. obs_hotkey_inject_event(hotkey, pressed);
  116. };
  117. switch (event->type()) {
  118. case QEvent::MouseButtonPress:
  119. case QEvent::MouseButtonRelease:
  120. return mouse_event(*static_cast<QMouseEvent*>(event));
  121. /*case QEvent::MouseButtonDblClick:
  122. case QEvent::Wheel:*/
  123. case QEvent::KeyPress:
  124. case QEvent::KeyRelease:
  125. key_event(static_cast<QKeyEvent*>(event));
  126. return true;
  127. default:
  128. return false;
  129. }
  130. });
  131. }
  132. string CurrentTimeString()
  133. {
  134. time_t now = time(0);
  135. struct tm tstruct;
  136. char buf[80];
  137. tstruct = *localtime(&now);
  138. strftime(buf, sizeof(buf), "%X", &tstruct);
  139. return buf;
  140. }
  141. string CurrentDateTimeString()
  142. {
  143. time_t now = time(0);
  144. struct tm tstruct;
  145. char buf[80];
  146. tstruct = *localtime(&now);
  147. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  148. return buf;
  149. }
  150. static void do_log(int log_level, const char *msg, va_list args, void *param)
  151. {
  152. fstream &logFile = *static_cast<fstream*>(param);
  153. char str[4096];
  154. #ifndef _WIN32
  155. va_list args2;
  156. va_copy(args2, args);
  157. #endif
  158. vsnprintf(str, 4095, msg, args);
  159. #ifdef _WIN32
  160. OutputDebugStringA(str);
  161. OutputDebugStringA("\n");
  162. #else
  163. def_log_handler(log_level, msg, args2, nullptr);
  164. #endif
  165. if (log_level <= LOG_INFO)
  166. logFile << CurrentTimeString() << ": " << str << endl;
  167. #ifdef _WIN32
  168. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  169. __debugbreak();
  170. #endif
  171. }
  172. #define DEFAULT_LANG "en-US"
  173. bool OBSApp::InitGlobalConfigDefaults()
  174. {
  175. config_set_default_string(globalConfig, "General", "Language",
  176. DEFAULT_LANG);
  177. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  178. #if _WIN32
  179. config_set_default_string(globalConfig, "Video", "Renderer",
  180. "Direct3D 11");
  181. #else
  182. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  183. #endif
  184. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  185. true);
  186. return true;
  187. }
  188. static bool do_mkdir(const char *path)
  189. {
  190. if (os_mkdir(path) == MKDIR_ERROR) {
  191. OBSErrorBox(NULL, "Failed to create directory %s", path);
  192. return false;
  193. }
  194. return true;
  195. }
  196. static bool MakeUserDirs()
  197. {
  198. char path[512];
  199. if (portable_mode) {
  200. if (GetConfigPath(path, sizeof(path), "") <= 0)
  201. return false;
  202. if (!do_mkdir(path))
  203. return false;
  204. }
  205. if (GetConfigPath(path, sizeof(path), "obs-studio") <= 0)
  206. return false;
  207. if (!do_mkdir(path))
  208. return false;
  209. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  210. return false;
  211. if (!do_mkdir(path))
  212. return false;
  213. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  214. return false;
  215. if (!do_mkdir(path))
  216. return false;
  217. #ifdef _WIN32
  218. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  219. return false;
  220. if (!do_mkdir(path))
  221. return false;
  222. #endif
  223. return true;
  224. }
  225. bool OBSApp::InitGlobalConfig()
  226. {
  227. char path[512];
  228. int len = GetConfigPath(path, sizeof(path),
  229. "obs-studio/global.ini");
  230. if (len <= 0) {
  231. return false;
  232. }
  233. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  234. if (errorcode != CONFIG_SUCCESS) {
  235. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  236. return false;
  237. }
  238. return InitGlobalConfigDefaults();
  239. }
  240. bool OBSApp::InitLocale()
  241. {
  242. const char *lang = config_get_string(globalConfig, "General",
  243. "Language");
  244. locale = lang;
  245. string englishPath;
  246. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  247. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  248. return false;
  249. }
  250. textLookup = text_lookup_create(englishPath.c_str());
  251. if (!textLookup) {
  252. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  253. englishPath.c_str());
  254. return false;
  255. }
  256. bool userLocale = config_has_user_value(globalConfig, "General",
  257. "Language");
  258. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  259. if (userLocale && defaultLang)
  260. return true;
  261. if (!userLocale && defaultLang) {
  262. for (auto &locale_ : GetPreferredLocales()) {
  263. if (locale_ == lang)
  264. return true;
  265. stringstream file;
  266. file << "locale/" << locale_ << ".ini";
  267. string path;
  268. if (!GetDataFilePath(file.str().c_str(), path))
  269. continue;
  270. if (!text_lookup_add(textLookup, path.c_str()))
  271. continue;
  272. blog(LOG_INFO, "Using preferred locale '%s'",
  273. locale_.c_str());
  274. locale = locale_;
  275. return true;
  276. }
  277. return true;
  278. }
  279. stringstream file;
  280. file << "locale/" << lang << ".ini";
  281. string path;
  282. if (GetDataFilePath(file.str().c_str(), path)) {
  283. if (!text_lookup_add(textLookup, path.c_str()))
  284. blog(LOG_ERROR, "Failed to add locale file '%s'",
  285. path.c_str());
  286. } else {
  287. blog(LOG_ERROR, "Could not find locale file '%s'",
  288. file.str().c_str());
  289. }
  290. return true;
  291. }
  292. bool OBSApp::SetTheme(std::string name, std::string path)
  293. {
  294. theme = name;
  295. /* Check user dir first, then preinstalled themes. */
  296. if (path == "") {
  297. char userDir[512];
  298. name = "themes/" + name + ".qss";
  299. string temp = "obs-studio/" + name;
  300. int ret = GetConfigPath(userDir, sizeof(userDir),
  301. temp.c_str());
  302. if (ret > 0 && QFile::exists(userDir)) {
  303. path = string(userDir);
  304. } else if (!GetDataFilePath(name.c_str(), path)) {
  305. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  306. return false;
  307. }
  308. }
  309. QString mpath = QString("file:///") + path.c_str();
  310. setStyleSheet(mpath);
  311. return true;
  312. }
  313. bool OBSApp::InitTheme()
  314. {
  315. const char *themeName = config_get_string(globalConfig, "General",
  316. "Theme");
  317. if (!themeName)
  318. themeName = "Default";
  319. stringstream t;
  320. t << themeName;
  321. return SetTheme(t.str());
  322. }
  323. OBSApp::OBSApp(int &argc, char **argv)
  324. : QApplication(argc, argv)
  325. {}
  326. void OBSApp::AppInit()
  327. {
  328. if (!InitApplicationBundle())
  329. throw "Failed to initialize application bundle";
  330. if (!MakeUserDirs())
  331. throw "Failed to create required user directories";
  332. if (!InitGlobalConfig())
  333. throw "Failed to initialize global config";
  334. if (!InitLocale())
  335. throw "Failed to load locale";
  336. if (!InitTheme())
  337. throw "Failed to load theme";
  338. }
  339. const char *OBSApp::GetRenderModule() const
  340. {
  341. const char *renderer = config_get_string(globalConfig, "Video",
  342. "Renderer");
  343. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  344. DL_D3D11 : DL_OPENGL;
  345. }
  346. bool OBSApp::OBSInit()
  347. {
  348. bool licenseAccepted = config_get_bool(globalConfig, "General",
  349. "LicenseAccepted");
  350. OBSLicenseAgreement agreement(nullptr);
  351. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  352. if (!licenseAccepted) {
  353. config_set_bool(globalConfig, "General",
  354. "LicenseAccepted", true);
  355. config_save(globalConfig);
  356. }
  357. mainWindow = new OBSBasic();
  358. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  359. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  360. mainWindow->OBSInit();
  361. connect(this, &QGuiApplication::applicationStateChanged,
  362. [](Qt::ApplicationState state)
  363. {
  364. obs_hotkey_enable_background_press(
  365. state != Qt::ApplicationActive);
  366. });
  367. obs_hotkey_enable_background_press(
  368. applicationState() != Qt::ApplicationActive);
  369. return true;
  370. } else {
  371. return false;
  372. }
  373. }
  374. string OBSApp::GetVersionString() const
  375. {
  376. stringstream ver;
  377. #ifdef HAVE_OBSCONFIG_H
  378. ver << OBS_VERSION;
  379. #else
  380. ver << LIBOBS_API_MAJOR_VER << "." <<
  381. LIBOBS_API_MINOR_VER << "." <<
  382. LIBOBS_API_PATCH_VER;
  383. #endif
  384. ver << " (";
  385. #ifdef _WIN32
  386. if (sizeof(void*) == 8)
  387. ver << "64bit, ";
  388. ver << "windows)";
  389. #elif __APPLE__
  390. ver << "mac)";
  391. #elif __FreeBSD__
  392. ver << "freebsd)";
  393. #else /* assume linux for the time being */
  394. ver << "linux)";
  395. #endif
  396. return ver.str();
  397. }
  398. #ifdef __APPLE__
  399. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  400. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  401. #elif _WIN32
  402. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  403. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  404. #else
  405. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  406. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  407. #endif
  408. const char *OBSApp::InputAudioSource() const
  409. {
  410. return INPUT_AUDIO_SOURCE;
  411. }
  412. const char *OBSApp::OutputAudioSource() const
  413. {
  414. return OUTPUT_AUDIO_SOURCE;
  415. }
  416. const char *OBSApp::GetLastLog() const
  417. {
  418. return lastLogFile.c_str();
  419. }
  420. const char *OBSApp::GetCurrentLog() const
  421. {
  422. return currentLogFile.c_str();
  423. }
  424. QString OBSTranslator::translate(const char *context, const char *sourceText,
  425. const char *disambiguation, int n) const
  426. {
  427. const char *out = nullptr;
  428. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  429. return QString();
  430. UNUSED_PARAMETER(context);
  431. UNUSED_PARAMETER(disambiguation);
  432. UNUSED_PARAMETER(n);
  433. return QT_UTF8(out);
  434. }
  435. static bool get_token(lexer *lex, string &str, base_token_type type)
  436. {
  437. base_token token;
  438. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  439. return false;
  440. if (token.type != type)
  441. return false;
  442. str.assign(token.text.array, token.text.len);
  443. return true;
  444. }
  445. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  446. {
  447. base_token token;
  448. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  449. return false;
  450. if (token.type != type)
  451. return false;
  452. return strref_cmp(&token.text, str) == 0;
  453. }
  454. static uint64_t convert_log_name(const char *name)
  455. {
  456. BaseLexer lex;
  457. string year, month, day, hour, minute, second;
  458. lexer_start(lex, name);
  459. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  460. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  461. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  462. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  463. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  464. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  465. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  466. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  467. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  468. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  469. stringstream timestring;
  470. timestring << year << month << day << hour << minute << second;
  471. return std::stoull(timestring.str());
  472. }
  473. static void delete_oldest_file(const char *location)
  474. {
  475. BPtr<char> logDir(GetConfigPathPtr(location));
  476. string oldestLog;
  477. uint64_t oldest_ts = (uint64_t)-1;
  478. struct os_dirent *entry;
  479. unsigned int maxLogs = (unsigned int)config_get_uint(
  480. App()->GlobalConfig(), "General", "MaxLogs");
  481. os_dir_t *dir = os_opendir(logDir);
  482. if (dir) {
  483. unsigned int count = 0;
  484. while ((entry = os_readdir(dir)) != NULL) {
  485. if (entry->directory || *entry->d_name == '.')
  486. continue;
  487. uint64_t ts = convert_log_name(entry->d_name);
  488. if (ts) {
  489. if (ts < oldest_ts) {
  490. oldestLog = entry->d_name;
  491. oldest_ts = ts;
  492. }
  493. count++;
  494. }
  495. }
  496. os_closedir(dir);
  497. if (count > maxLogs) {
  498. stringstream delPath;
  499. delPath << logDir << "/" << oldestLog;
  500. os_unlink(delPath.str().c_str());
  501. }
  502. }
  503. }
  504. static void get_last_log(void)
  505. {
  506. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  507. struct os_dirent *entry;
  508. os_dir_t *dir = os_opendir(logDir);
  509. uint64_t highest_ts = 0;
  510. if (dir) {
  511. while ((entry = os_readdir(dir)) != NULL) {
  512. if (entry->directory || *entry->d_name == '.')
  513. continue;
  514. uint64_t ts = convert_log_name(entry->d_name);
  515. if (ts > highest_ts) {
  516. lastLogFile = entry->d_name;
  517. highest_ts = ts;
  518. }
  519. }
  520. os_closedir(dir);
  521. }
  522. }
  523. string GenerateTimeDateFilename(const char *extension)
  524. {
  525. time_t now = time(0);
  526. char file[256] = {};
  527. struct tm *cur_time;
  528. cur_time = localtime(&now);
  529. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  530. cur_time->tm_year+1900,
  531. cur_time->tm_mon+1,
  532. cur_time->tm_mday,
  533. cur_time->tm_hour,
  534. cur_time->tm_min,
  535. cur_time->tm_sec,
  536. extension);
  537. return string(file);
  538. }
  539. vector<pair<string, string>> GetLocaleNames()
  540. {
  541. string path;
  542. if (!GetDataFilePath("locale.ini", path))
  543. throw "Could not find locale.ini path";
  544. ConfigFile ini;
  545. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  546. throw "Could not open locale.ini";
  547. size_t sections = config_num_sections(ini);
  548. vector<pair<string, string>> names;
  549. names.reserve(sections);
  550. for (size_t i = 0; i < sections; i++) {
  551. const char *tag = config_get_section(ini, i);
  552. const char *name = config_get_string(ini, tag, "Name");
  553. names.emplace_back(tag, name);
  554. }
  555. return names;
  556. }
  557. static void create_log_file(fstream &logFile)
  558. {
  559. stringstream dst;
  560. get_last_log();
  561. currentLogFile = GenerateTimeDateFilename("txt");
  562. dst << "obs-studio/logs/" << currentLogFile.c_str();
  563. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  564. logFile.open(path,
  565. ios_base::in | ios_base::out | ios_base::trunc);
  566. if (logFile.is_open()) {
  567. delete_oldest_file("obs-studio/logs");
  568. base_set_log_handler(do_log, &logFile);
  569. } else {
  570. blog(LOG_ERROR, "Failed to open log file");
  571. }
  572. }
  573. static int run_program(fstream &logFile, int argc, char *argv[])
  574. {
  575. int ret = -1;
  576. QCoreApplication::addLibraryPath(".");
  577. OBSApp program(argc, argv);
  578. try {
  579. program.AppInit();
  580. OBSTranslator translator;
  581. create_log_file(logFile);
  582. program.installTranslator(&translator);
  583. ret = program.OBSInit() ? program.exec() : 0;
  584. } catch (const char *error) {
  585. blog(LOG_ERROR, "%s", error);
  586. OBSErrorBox(nullptr, "%s", error);
  587. }
  588. return ret;
  589. }
  590. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  591. #ifdef _WIN32
  592. #define CRASH_MESSAGE \
  593. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  594. "to the clipboard? (Crash logs will still be saved to the " \
  595. "%appdata%\\obs-studio\\crashes directory)"
  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. delete_oldest_file("obs-studio/crashes");
  601. string name = "obs-studio/crashes/Crash ";
  602. name += GenerateTimeDateFilename("txt");
  603. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  604. fstream file;
  605. file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  606. file << text;
  607. file.close();
  608. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  609. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  610. if (ret == IDYES) {
  611. size_t len = strlen(text);
  612. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  613. memcpy(GlobalLock(mem), text, len);
  614. GlobalUnlock(mem);
  615. OpenClipboard(0);
  616. EmptyClipboard();
  617. SetClipboardData(CF_TEXT, mem);
  618. CloseClipboard();
  619. }
  620. exit(-1);
  621. UNUSED_PARAMETER(param);
  622. }
  623. static void load_debug_privilege(void)
  624. {
  625. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  626. TOKEN_PRIVILEGES tp;
  627. HANDLE token;
  628. LUID val;
  629. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  630. return;
  631. }
  632. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  633. tp.PrivilegeCount = 1;
  634. tp.Privileges[0].Luid = val;
  635. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  636. AdjustTokenPrivileges(token, false, &tp,
  637. sizeof(tp), NULL, NULL);
  638. }
  639. CloseHandle(token);
  640. }
  641. #endif
  642. #ifdef __APPLE__
  643. #define BASE_PATH ".."
  644. #else
  645. #define BASE_PATH "../.."
  646. #endif
  647. #define CONFIG_PATH BASE_PATH "/config"
  648. #ifndef OBS_UNIX_STRUCTURE
  649. #define OBS_UNIX_STRUCTURE 0
  650. #endif
  651. int GetConfigPath(char *path, size_t size, const char *name)
  652. {
  653. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  654. if (name && *name) {
  655. return snprintf(path, size, CONFIG_PATH "/%s", name);
  656. } else {
  657. return snprintf(path, size, CONFIG_PATH);
  658. }
  659. } else {
  660. return os_get_config_path(path, size, name);
  661. }
  662. }
  663. char *GetConfigPathPtr(const char *name)
  664. {
  665. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  666. char path[512];
  667. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  668. return bstrdup(path);
  669. } else {
  670. return NULL;
  671. }
  672. } else {
  673. return os_get_config_path_ptr(name);
  674. }
  675. }
  676. static inline bool arg_is(const char *arg,
  677. const char *long_form, const char *short_form)
  678. {
  679. return (long_form && strcmp(arg, long_form) == 0) ||
  680. (short_form && strcmp(arg, short_form) == 0);
  681. }
  682. int main(int argc, char *argv[])
  683. {
  684. #ifndef _WIN32
  685. signal(SIGPIPE, SIG_IGN);
  686. #endif
  687. #ifdef _WIN32
  688. load_debug_privilege();
  689. base_set_crash_handler(main_crash_handler, nullptr);
  690. #endif
  691. base_get_log_handler(&def_log_handler, nullptr);
  692. for (int i = 1; i < argc; i++) {
  693. if (arg_is(argv[i], "--portable", "-p")) {
  694. portable_mode = true;
  695. }
  696. }
  697. #if !OBS_UNIX_STRUCTURE
  698. if (!portable_mode) {
  699. portable_mode =
  700. os_file_exists(BASE_PATH "/portable_mode") ||
  701. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  702. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  703. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  704. }
  705. #endif
  706. fstream logFile;
  707. int ret = run_program(logFile, argc, argv);
  708. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  709. base_set_log_handler(nullptr, nullptr);
  710. return ret;
  711. }