obs-app.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. #define snprintf _snprintf
  34. #else
  35. #include <signal.h>
  36. #endif
  37. using namespace std;
  38. static log_handler_t def_log_handler;
  39. static string currentLogFile;
  40. static string lastLogFile;
  41. string CurrentTimeString()
  42. {
  43. time_t now = time(0);
  44. struct tm tstruct;
  45. char buf[80];
  46. tstruct = *localtime(&now);
  47. strftime(buf, sizeof(buf), "%X", &tstruct);
  48. return buf;
  49. }
  50. string CurrentDateTimeString()
  51. {
  52. time_t now = time(0);
  53. struct tm tstruct;
  54. char buf[80];
  55. tstruct = *localtime(&now);
  56. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  57. return buf;
  58. }
  59. static void do_log(int log_level, const char *msg, va_list args, void *param)
  60. {
  61. fstream &logFile = *static_cast<fstream*>(param);
  62. char str[4096];
  63. #ifndef _WIN32
  64. va_list args2;
  65. va_copy(args2, args);
  66. #endif
  67. vsnprintf(str, 4095, msg, args);
  68. #ifdef _WIN32
  69. OutputDebugStringA(str);
  70. OutputDebugStringA("\n");
  71. #else
  72. def_log_handler(log_level, msg, args2, nullptr);
  73. #endif
  74. if (log_level <= LOG_INFO)
  75. logFile << CurrentTimeString() << ": " << str << endl;
  76. #ifdef _WIN32
  77. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  78. __debugbreak();
  79. #endif
  80. }
  81. #define DEFAULT_LANG "en-US"
  82. bool OBSApp::InitGlobalConfigDefaults()
  83. {
  84. config_set_default_string(globalConfig, "General", "Language",
  85. DEFAULT_LANG);
  86. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  87. #if _WIN32
  88. config_set_default_string(globalConfig, "Video", "Renderer",
  89. "Direct3D 11");
  90. #else
  91. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  92. #endif
  93. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  94. true);
  95. return true;
  96. }
  97. static bool do_mkdir(const char *path)
  98. {
  99. if (os_mkdir(path) == MKDIR_ERROR) {
  100. OBSErrorBox(NULL, "Failed to create directory %s", path);
  101. return false;
  102. }
  103. return true;
  104. }
  105. static bool MakeUserDirs()
  106. {
  107. char path[512];
  108. if (os_get_config_path(path, sizeof(path), "obs-studio") <= 0)
  109. return false;
  110. if (!do_mkdir(path))
  111. return false;
  112. if (os_get_config_path(path, sizeof(path), "obs-studio/basic") <= 0)
  113. return false;
  114. if (!do_mkdir(path))
  115. return false;
  116. if (os_get_config_path(path, sizeof(path), "obs-studio/logs") <= 0)
  117. return false;
  118. if (!do_mkdir(path))
  119. return false;
  120. #ifdef _WIN32
  121. if (os_get_config_path(path, sizeof(path), "obs-studio/crashes") <= 0)
  122. return false;
  123. if (!do_mkdir(path))
  124. return false;
  125. #endif
  126. return true;
  127. }
  128. bool OBSApp::InitGlobalConfig()
  129. {
  130. char path[512];
  131. int len = os_get_config_path(path, sizeof(path),
  132. "obs-studio/global.ini");
  133. if (len <= 0) {
  134. return false;
  135. }
  136. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  137. if (errorcode != CONFIG_SUCCESS) {
  138. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  139. return false;
  140. }
  141. return InitGlobalConfigDefaults();
  142. }
  143. bool OBSApp::InitLocale()
  144. {
  145. const char *lang = config_get_string(globalConfig, "General",
  146. "Language");
  147. locale = lang;
  148. string englishPath;
  149. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  150. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  151. return false;
  152. }
  153. textLookup = text_lookup_create(englishPath.c_str());
  154. if (!textLookup) {
  155. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  156. englishPath.c_str());
  157. return false;
  158. }
  159. bool userLocale = config_has_user_value(globalConfig, "General",
  160. "Language");
  161. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  162. if (userLocale && defaultLang)
  163. return true;
  164. if (!userLocale && defaultLang) {
  165. for (auto &locale_ : GetPreferredLocales()) {
  166. if (locale_ == lang)
  167. return true;
  168. stringstream file;
  169. file << "locale/" << locale_ << ".ini";
  170. string path;
  171. if (!GetDataFilePath(file.str().c_str(), path))
  172. continue;
  173. if (!text_lookup_add(textLookup, path.c_str()))
  174. continue;
  175. blog(LOG_INFO, "Using preferred locale '%s'",
  176. locale_.c_str());
  177. locale = locale_;
  178. return true;
  179. }
  180. return true;
  181. }
  182. stringstream file;
  183. file << "locale/" << lang << ".ini";
  184. string path;
  185. if (GetDataFilePath(file.str().c_str(), path)) {
  186. if (!text_lookup_add(textLookup, path.c_str()))
  187. blog(LOG_ERROR, "Failed to add locale file '%s'",
  188. path.c_str());
  189. } else {
  190. blog(LOG_ERROR, "Could not find locale file '%s'",
  191. file.str().c_str());
  192. }
  193. return true;
  194. }
  195. bool OBSApp::SetTheme(std::string name, std::string path)
  196. {
  197. theme = name;
  198. /* Check user dir first, then preinstalled themes. */
  199. if (path == "") {
  200. char userDir[512];
  201. name = "themes/" + name + ".qss";
  202. string temp = "obs-studio/" + name;
  203. int ret = os_get_config_path(userDir, sizeof(userDir),
  204. temp.c_str());
  205. if (ret > 0 && QFile::exists(userDir)) {
  206. path = string(userDir);
  207. } else if (!GetDataFilePath(name.c_str(), path)) {
  208. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  209. return false;
  210. }
  211. }
  212. QString mpath = QString("file:///") + path.c_str();
  213. setStyleSheet(mpath);
  214. return true;
  215. }
  216. bool OBSApp::InitTheme()
  217. {
  218. const char *themeName = config_get_string(globalConfig, "General",
  219. "Theme");
  220. if (!themeName)
  221. themeName = "Default";
  222. stringstream t;
  223. t << themeName;
  224. return SetTheme(t.str());
  225. }
  226. OBSApp::OBSApp(int &argc, char **argv)
  227. : QApplication(argc, argv)
  228. {}
  229. void OBSApp::AppInit()
  230. {
  231. if (!InitApplicationBundle())
  232. throw "Failed to initialize application bundle";
  233. if (!MakeUserDirs())
  234. throw "Failed to created required user directories";
  235. if (!InitGlobalConfig())
  236. throw "Failed to initialize global config";
  237. if (!InitLocale())
  238. throw "Failed to load locale";
  239. if (!InitTheme())
  240. throw "Failed to load theme";
  241. }
  242. const char *OBSApp::GetRenderModule() const
  243. {
  244. const char *renderer = config_get_string(globalConfig, "Video",
  245. "Renderer");
  246. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  247. DL_D3D11 : DL_OPENGL;
  248. }
  249. bool OBSApp::OBSInit()
  250. {
  251. bool licenseAccepted = config_get_bool(globalConfig, "General",
  252. "LicenseAccepted");
  253. OBSLicenseAgreement agreement(nullptr);
  254. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  255. if (!licenseAccepted) {
  256. config_set_bool(globalConfig, "General",
  257. "LicenseAccepted", true);
  258. config_save(globalConfig);
  259. }
  260. mainWindow = new OBSBasic();
  261. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  262. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  263. mainWindow->OBSInit();
  264. return true;
  265. } else {
  266. return false;
  267. }
  268. }
  269. string OBSApp::GetVersionString() const
  270. {
  271. stringstream ver;
  272. #ifdef HAVE_OBSCONFIG_H
  273. ver << OBS_VERSION;
  274. #else
  275. ver << LIBOBS_API_MAJOR_VER << "." <<
  276. LIBOBS_API_MINOR_VER << "." <<
  277. LIBOBS_API_PATCH_VER;
  278. #endif
  279. ver << " (";
  280. #ifdef _WIN32
  281. if (sizeof(void*) == 8)
  282. ver << "64bit, ";
  283. ver << "windows)";
  284. #elif __APPLE__
  285. ver << "mac)";
  286. #else /* assume linux for the time being */
  287. ver << "linux)";
  288. #endif
  289. return ver.str();
  290. }
  291. #ifdef __APPLE__
  292. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  293. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  294. #elif _WIN32
  295. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  296. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  297. #else
  298. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  299. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  300. #endif
  301. const char *OBSApp::InputAudioSource() const
  302. {
  303. return INPUT_AUDIO_SOURCE;
  304. }
  305. const char *OBSApp::OutputAudioSource() const
  306. {
  307. return OUTPUT_AUDIO_SOURCE;
  308. }
  309. const char *OBSApp::GetLastLog() const
  310. {
  311. return lastLogFile.c_str();
  312. }
  313. const char *OBSApp::GetCurrentLog() const
  314. {
  315. return currentLogFile.c_str();
  316. }
  317. QString OBSTranslator::translate(const char *context, const char *sourceText,
  318. const char *disambiguation, int n) const
  319. {
  320. const char *out = nullptr;
  321. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  322. return QString();
  323. UNUSED_PARAMETER(context);
  324. UNUSED_PARAMETER(disambiguation);
  325. UNUSED_PARAMETER(n);
  326. return QT_UTF8(out);
  327. }
  328. struct NoFocusFrameStyle : QProxyStyle
  329. {
  330. void drawControl(ControlElement element, const QStyleOption *option,
  331. QPainter *painter, const QWidget *widget=nullptr)
  332. const override
  333. {
  334. if (element == CE_FocusFrame)
  335. return;
  336. QProxyStyle::drawControl(element, option, painter, widget);
  337. }
  338. };
  339. static bool get_token(lexer *lex, string &str, base_token_type type)
  340. {
  341. base_token token;
  342. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  343. return false;
  344. if (token.type != type)
  345. return false;
  346. str.assign(token.text.array, token.text.len);
  347. return true;
  348. }
  349. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  350. {
  351. base_token token;
  352. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  353. return false;
  354. if (token.type != type)
  355. return false;
  356. return strref_cmp(&token.text, str) == 0;
  357. }
  358. static uint64_t convert_log_name(const char *name)
  359. {
  360. BaseLexer lex;
  361. string year, month, day, hour, minute, second;
  362. lexer_start(lex, name);
  363. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  364. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  365. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  366. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  367. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  368. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  369. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  370. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  371. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  372. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  373. stringstream timestring;
  374. timestring << year << month << day << hour << minute << second;
  375. return std::stoull(timestring.str());
  376. }
  377. static void delete_oldest_file(const char *location)
  378. {
  379. BPtr<char> logDir(os_get_config_path_ptr(location));
  380. string oldestLog;
  381. uint64_t oldest_ts = (uint64_t)-1;
  382. struct os_dirent *entry;
  383. unsigned int maxLogs = (unsigned int)config_get_uint(
  384. App()->GlobalConfig(), "General", "MaxLogs");
  385. os_dir_t *dir = os_opendir(logDir);
  386. if (dir) {
  387. unsigned int count = 0;
  388. while ((entry = os_readdir(dir)) != NULL) {
  389. if (entry->directory || *entry->d_name == '.')
  390. continue;
  391. uint64_t ts = convert_log_name(entry->d_name);
  392. if (ts) {
  393. if (ts < oldest_ts) {
  394. oldestLog = entry->d_name;
  395. oldest_ts = ts;
  396. }
  397. count++;
  398. }
  399. }
  400. os_closedir(dir);
  401. if (count > maxLogs) {
  402. stringstream delPath;
  403. delPath << logDir << "/" << oldestLog;
  404. os_unlink(delPath.str().c_str());
  405. }
  406. }
  407. }
  408. static void get_last_log(void)
  409. {
  410. BPtr<char> logDir(os_get_config_path_ptr("obs-studio/logs"));
  411. struct os_dirent *entry;
  412. os_dir_t *dir = os_opendir(logDir);
  413. uint64_t highest_ts = 0;
  414. if (dir) {
  415. while ((entry = os_readdir(dir)) != NULL) {
  416. if (entry->directory || *entry->d_name == '.')
  417. continue;
  418. uint64_t ts = convert_log_name(entry->d_name);
  419. if (ts > highest_ts) {
  420. lastLogFile = entry->d_name;
  421. highest_ts = ts;
  422. }
  423. }
  424. os_closedir(dir);
  425. }
  426. }
  427. string GenerateTimeDateFilename(const char *extension)
  428. {
  429. time_t now = time(0);
  430. char file[256] = {};
  431. struct tm *cur_time;
  432. cur_time = localtime(&now);
  433. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  434. cur_time->tm_year+1900,
  435. cur_time->tm_mon+1,
  436. cur_time->tm_mday,
  437. cur_time->tm_hour,
  438. cur_time->tm_min,
  439. cur_time->tm_sec,
  440. extension);
  441. return string(file);
  442. }
  443. vector<pair<string, string>> GetLocaleNames()
  444. {
  445. string path;
  446. if (!GetDataFilePath("locale.ini", path))
  447. throw "Could not find locale.ini path";
  448. ConfigFile ini;
  449. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  450. throw "Could not open locale.ini";
  451. size_t sections = config_num_sections(ini);
  452. vector<pair<string, string>> names;
  453. names.reserve(sections);
  454. for (size_t i = 0; i < sections; i++) {
  455. const char *tag = config_get_section(ini, i);
  456. const char *name = config_get_string(ini, tag, "Name");
  457. names.emplace_back(tag, name);
  458. }
  459. return names;
  460. }
  461. static void create_log_file(fstream &logFile)
  462. {
  463. stringstream dst;
  464. get_last_log();
  465. currentLogFile = GenerateTimeDateFilename("txt");
  466. dst << "obs-studio/logs/" << currentLogFile.c_str();
  467. BPtr<char> path(os_get_config_path_ptr(dst.str().c_str()));
  468. logFile.open(path,
  469. ios_base::in | ios_base::out | ios_base::trunc);
  470. if (logFile.is_open()) {
  471. delete_oldest_file("obs-studio/logs");
  472. base_set_log_handler(do_log, &logFile);
  473. } else {
  474. blog(LOG_ERROR, "Failed to open log file");
  475. }
  476. }
  477. static int run_program(fstream &logFile, int argc, char *argv[])
  478. {
  479. int ret = -1;
  480. QCoreApplication::addLibraryPath(".");
  481. OBSApp program(argc, argv);
  482. try {
  483. program.AppInit();
  484. OBSTranslator translator;
  485. create_log_file(logFile);
  486. program.installTranslator(&translator);
  487. program.setStyle(new NoFocusFrameStyle);
  488. ret = program.OBSInit() ? program.exec() : 0;
  489. } catch (const char *error) {
  490. blog(LOG_ERROR, "%s", error);
  491. OBSErrorBox(nullptr, "%s", error);
  492. }
  493. return ret;
  494. }
  495. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  496. #ifdef _WIN32
  497. #define CRASH_MESSAGE \
  498. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  499. "to the clipboard? (Crash logs will still be saved to the " \
  500. "%appdata%\\obs-studio\\crashes directory)"
  501. static void main_crash_handler(const char *format, va_list args, void *param)
  502. {
  503. char *text = new char[MAX_CRASH_REPORT_SIZE];
  504. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  505. delete_oldest_file("obs-studio/crashes");
  506. string name = "obs-studio/crashes/Crash ";
  507. name += GenerateTimeDateFilename("txt");
  508. BPtr<char> path(os_get_config_path_ptr(name.c_str()));
  509. fstream file;
  510. file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  511. file << text;
  512. file.close();
  513. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  514. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  515. if (ret == IDYES) {
  516. size_t len = strlen(text);
  517. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  518. memcpy(GlobalLock(mem), text, len);
  519. GlobalUnlock(mem);
  520. OpenClipboard(0);
  521. EmptyClipboard();
  522. SetClipboardData(CF_TEXT, mem);
  523. CloseClipboard();
  524. }
  525. exit(-1);
  526. UNUSED_PARAMETER(param);
  527. }
  528. static void load_debug_privilege(void)
  529. {
  530. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  531. TOKEN_PRIVILEGES tp;
  532. HANDLE token;
  533. LUID val;
  534. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  535. return;
  536. }
  537. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  538. tp.PrivilegeCount = 1;
  539. tp.Privileges[0].Luid = val;
  540. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  541. AdjustTokenPrivileges(token, false, &tp,
  542. sizeof(tp), NULL, NULL);
  543. }
  544. CloseHandle(token);
  545. }
  546. #endif
  547. int main(int argc, char *argv[])
  548. {
  549. #ifndef _WIN32
  550. signal(SIGPIPE, SIG_IGN);
  551. #endif
  552. #ifdef _WIN32
  553. load_debug_privilege();
  554. base_set_crash_handler(main_crash_handler, nullptr);
  555. #endif
  556. base_get_log_handler(&def_log_handler, nullptr);
  557. fstream logFile;
  558. int ret = run_program(logFile, argc, argv);
  559. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  560. base_set_log_handler(nullptr, nullptr);
  561. return ret;
  562. }