obs-app.cpp 20 KB

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