obs-app.cpp 20 KB

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