obs-app.cpp 15 KB

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