obs-app.cpp 16 KB

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