obs-app.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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-license-agreement.hpp"
  27. #include "crash-report.hpp"
  28. #include "platform.hpp"
  29. #include <fstream>
  30. #ifdef _WIN32
  31. #include <windows.h>
  32. #define snprintf _snprintf
  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. string CurrentTimeString()
  41. {
  42. time_t now = time(0);
  43. struct tm tstruct;
  44. char buf[80];
  45. tstruct = *localtime(&now);
  46. strftime(buf, sizeof(buf), "%X", &tstruct);
  47. return buf;
  48. }
  49. string CurrentDateTimeString()
  50. {
  51. time_t now = time(0);
  52. struct tm tstruct;
  53. char buf[80];
  54. tstruct = *localtime(&now);
  55. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  56. return buf;
  57. }
  58. static void do_log(int log_level, const char *msg, va_list args, void *param)
  59. {
  60. fstream &logFile = *static_cast<fstream*>(param);
  61. char str[4096];
  62. #ifndef _WIN32
  63. va_list args2;
  64. va_copy(args2, args);
  65. #endif
  66. vsnprintf(str, 4095, msg, args);
  67. #ifdef _WIN32
  68. OutputDebugStringA(str);
  69. OutputDebugStringA("\n");
  70. #else
  71. def_log_handler(log_level, msg, args2, nullptr);
  72. #endif
  73. if (log_level <= LOG_INFO)
  74. logFile << CurrentTimeString() << ": " << str << endl;
  75. #ifdef _WIN32
  76. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  77. __debugbreak();
  78. #endif
  79. }
  80. #define DEFAULT_LANG "en-US"
  81. bool OBSApp::InitGlobalConfigDefaults()
  82. {
  83. config_set_default_string(globalConfig, "General", "Language",
  84. DEFAULT_LANG);
  85. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  86. #if _WIN32
  87. config_set_default_string(globalConfig, "Video", "Renderer",
  88. "Direct3D 11");
  89. #else
  90. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  91. #endif
  92. return true;
  93. }
  94. static bool do_mkdir(const char *path)
  95. {
  96. if (os_mkdir(path) == MKDIR_ERROR) {
  97. OBSErrorBox(NULL, "Failed to create directory %s", path);
  98. return false;
  99. }
  100. return true;
  101. }
  102. static bool MakeUserDirs()
  103. {
  104. BPtr<char> path;
  105. path = os_get_config_path("obs-studio");
  106. if (!do_mkdir(path))
  107. return false;
  108. path = os_get_config_path("obs-studio/basic");
  109. if (!do_mkdir(path))
  110. return false;
  111. path = os_get_config_path("obs-studio/logs");
  112. if (!do_mkdir(path))
  113. return false;
  114. return true;
  115. }
  116. bool OBSApp::InitGlobalConfig()
  117. {
  118. BPtr<char> path(os_get_config_path("obs-studio/global.ini"));
  119. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  120. if (errorcode != CONFIG_SUCCESS) {
  121. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  122. return false;
  123. }
  124. return InitGlobalConfigDefaults();
  125. }
  126. bool OBSApp::InitLocale()
  127. {
  128. const char *lang = config_get_string(globalConfig, "General",
  129. "Language");
  130. locale = lang;
  131. string englishPath;
  132. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  133. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  134. return false;
  135. }
  136. textLookup = text_lookup_create(englishPath.c_str());
  137. if (!textLookup) {
  138. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  139. englishPath.c_str());
  140. return false;
  141. }
  142. bool userLocale = config_has_user_value(globalConfig, "General",
  143. "Language");
  144. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  145. if (userLocale && defaultLang)
  146. return true;
  147. if (!userLocale && defaultLang) {
  148. for (auto &locale_ : GetPreferredLocales()) {
  149. if (locale_ == lang)
  150. return true;
  151. stringstream file;
  152. file << "locale/" << locale_ << ".ini";
  153. string path;
  154. if (!GetDataFilePath(file.str().c_str(), path))
  155. continue;
  156. if (!text_lookup_add(textLookup, path.c_str()))
  157. continue;
  158. blog(LOG_INFO, "Using preferred locale '%s'",
  159. locale_.c_str());
  160. locale = locale_;
  161. return true;
  162. }
  163. return true;
  164. }
  165. stringstream file;
  166. file << "locale/" << lang << ".ini";
  167. string path;
  168. if (GetDataFilePath(file.str().c_str(), path)) {
  169. if (!text_lookup_add(textLookup, path.c_str()))
  170. blog(LOG_ERROR, "Failed to add locale file '%s'",
  171. path.c_str());
  172. } else {
  173. blog(LOG_ERROR, "Could not find locale file '%s'",
  174. file.str().c_str());
  175. }
  176. return true;
  177. }
  178. OBSApp::OBSApp(int &argc, char **argv)
  179. : QApplication(argc, argv)
  180. {}
  181. void OBSApp::AppInit()
  182. {
  183. if (!InitApplicationBundle())
  184. throw "Failed to initialize application bundle";
  185. if (!MakeUserDirs())
  186. throw "Failed to created required user directories";
  187. if (!InitGlobalConfig())
  188. throw "Failed to initialize global config";
  189. if (!InitLocale())
  190. throw "Failed to load locale";
  191. }
  192. const char *OBSApp::GetRenderModule() const
  193. {
  194. const char *renderer = config_get_string(globalConfig, "Video",
  195. "Renderer");
  196. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  197. "libobs-d3d11" : "libobs-opengl";
  198. }
  199. bool OBSApp::OBSInit()
  200. {
  201. bool licenseAccepted = config_get_bool(globalConfig, "General",
  202. "LicenseAccepted");
  203. OBSLicenseAgreement agreement(nullptr);
  204. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  205. if (!licenseAccepted) {
  206. config_set_bool(globalConfig, "General",
  207. "LicenseAccepted", true);
  208. config_save(globalConfig);
  209. }
  210. mainWindow = new OBSBasic();
  211. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  212. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  213. mainWindow->OBSInit();
  214. return true;
  215. } else {
  216. return false;
  217. }
  218. }
  219. string OBSApp::GetVersionString() const
  220. {
  221. stringstream ver;
  222. #ifdef HAVE_OBSCONFIG_H
  223. ver << OBS_VERSION;
  224. #else
  225. ver << LIBOBS_API_MAJOR_VER << "." <<
  226. LIBOBS_API_MINOR_VER << "." <<
  227. LIBOBS_API_PATCH_VER;
  228. #endif
  229. ver << " (";
  230. #ifdef _WIN32
  231. if (sizeof(void*) == 8)
  232. ver << "64bit, ";
  233. ver << "windows)";
  234. #elif __APPLE__
  235. ver << "mac)";
  236. #else /* assume linux for the time being */
  237. ver << "linux)";
  238. #endif
  239. return ver.str();
  240. }
  241. #ifdef __APPLE__
  242. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  243. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  244. #elif _WIN32
  245. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  246. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  247. #else
  248. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  249. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  250. #endif
  251. const char *OBSApp::InputAudioSource() const
  252. {
  253. return INPUT_AUDIO_SOURCE;
  254. }
  255. const char *OBSApp::OutputAudioSource() const
  256. {
  257. return OUTPUT_AUDIO_SOURCE;
  258. }
  259. const char *OBSApp::GetLastLog() const
  260. {
  261. return lastLogFile.c_str();
  262. }
  263. const char *OBSApp::GetCurrentLog() const
  264. {
  265. return currentLogFile.c_str();
  266. }
  267. QString OBSTranslator::translate(const char *context, const char *sourceText,
  268. const char *disambiguation, int n) const
  269. {
  270. const char *out = nullptr;
  271. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  272. return QString();
  273. UNUSED_PARAMETER(context);
  274. UNUSED_PARAMETER(disambiguation);
  275. UNUSED_PARAMETER(n);
  276. return QT_UTF8(out);
  277. }
  278. struct NoFocusFrameStyle : QProxyStyle
  279. {
  280. void drawControl(ControlElement element, const QStyleOption *option,
  281. QPainter *painter, const QWidget *widget=nullptr)
  282. const override
  283. {
  284. if (element == CE_FocusFrame)
  285. return;
  286. QProxyStyle::drawControl(element, option, painter, widget);
  287. }
  288. };
  289. static bool get_token(lexer *lex, string &str, base_token_type type)
  290. {
  291. base_token token;
  292. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  293. return false;
  294. if (token.type != type)
  295. return false;
  296. str.assign(token.text.array, token.text.len);
  297. return true;
  298. }
  299. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  300. {
  301. base_token token;
  302. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  303. return false;
  304. if (token.type != type)
  305. return false;
  306. return strref_cmp(&token.text, str) == 0;
  307. }
  308. static uint64_t convert_log_name(const char *name)
  309. {
  310. BaseLexer lex;
  311. string year, month, day, hour, minute, second;
  312. lexer_start(lex, name);
  313. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  314. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  315. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  316. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  317. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  318. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  319. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  320. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  321. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  322. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  323. stringstream timestring;
  324. timestring << year << month << day << hour << minute << second;
  325. return std::stoull(timestring.str());
  326. }
  327. static void delete_oldest_log(void)
  328. {
  329. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  330. string oldestLog;
  331. uint64_t oldest_ts = (uint64_t)-1;
  332. struct os_dirent *entry;
  333. unsigned int maxLogs = (unsigned int)config_get_uint(
  334. App()->GlobalConfig(), "General", "MaxLogs");
  335. os_dir_t *dir = os_opendir(logDir);
  336. if (dir) {
  337. unsigned int count = 0;
  338. while ((entry = os_readdir(dir)) != NULL) {
  339. if (entry->directory || *entry->d_name == '.')
  340. continue;
  341. uint64_t ts = convert_log_name(entry->d_name);
  342. if (ts) {
  343. if (ts < oldest_ts) {
  344. oldestLog = entry->d_name;
  345. oldest_ts = ts;
  346. }
  347. count++;
  348. }
  349. }
  350. os_closedir(dir);
  351. if (count > maxLogs) {
  352. stringstream delPath;
  353. delPath << logDir << "/" << oldestLog;
  354. os_unlink(delPath.str().c_str());
  355. }
  356. }
  357. }
  358. static void get_last_log(void)
  359. {
  360. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  361. struct os_dirent *entry;
  362. os_dir_t *dir = os_opendir(logDir);
  363. uint64_t highest_ts = 0;
  364. if (dir) {
  365. while ((entry = os_readdir(dir)) != NULL) {
  366. if (entry->directory || *entry->d_name == '.')
  367. continue;
  368. uint64_t ts = convert_log_name(entry->d_name);
  369. if (ts > highest_ts) {
  370. lastLogFile = entry->d_name;
  371. highest_ts = ts;
  372. }
  373. }
  374. os_closedir(dir);
  375. }
  376. }
  377. string GenerateTimeDateFilename(const char *extension)
  378. {
  379. time_t now = time(0);
  380. char file[256] = {};
  381. struct tm *cur_time;
  382. cur_time = localtime(&now);
  383. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  384. cur_time->tm_year+1900,
  385. cur_time->tm_mon+1,
  386. cur_time->tm_mday,
  387. cur_time->tm_hour,
  388. cur_time->tm_min,
  389. cur_time->tm_sec,
  390. extension);
  391. return string(file);
  392. }
  393. vector<pair<string, string>> GetLocaleNames()
  394. {
  395. string path;
  396. if (!GetDataFilePath("locale.ini", path))
  397. throw "Could not find locale.ini path";
  398. ConfigFile ini;
  399. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  400. throw "Could not open locale.ini";
  401. size_t sections = config_num_sections(ini);
  402. vector<pair<string, string>> names;
  403. names.reserve(sections);
  404. for (size_t i = 0; i < sections; i++) {
  405. const char *tag = config_get_section(ini, i);
  406. const char *name = config_get_string(ini, tag, "Name");
  407. names.emplace_back(tag, name);
  408. }
  409. return names;
  410. }
  411. static void create_log_file(fstream &logFile)
  412. {
  413. stringstream dst;
  414. get_last_log();
  415. currentLogFile = GenerateTimeDateFilename("txt");
  416. dst << "obs-studio/logs/" << currentLogFile.c_str();
  417. BPtr<char> path(os_get_config_path(dst.str().c_str()));
  418. logFile.open(path,
  419. ios_base::in | ios_base::out | ios_base::trunc);
  420. if (logFile.is_open()) {
  421. delete_oldest_log();
  422. base_set_log_handler(do_log, &logFile);
  423. } else {
  424. blog(LOG_ERROR, "Failed to open log file");
  425. }
  426. }
  427. static int run_program(fstream &logFile, int argc, char *argv[])
  428. {
  429. int ret = -1;
  430. QCoreApplication::addLibraryPath(".");
  431. OBSApp program(argc, argv);
  432. try {
  433. program.AppInit();
  434. OBSTranslator translator;
  435. create_log_file(logFile);
  436. program.installTranslator(&translator);
  437. program.setStyle(new NoFocusFrameStyle);
  438. ret = program.OBSInit() ? program.exec() : 0;
  439. } catch (const char *error) {
  440. blog(LOG_ERROR, "%s", error);
  441. OBSErrorBox(nullptr, "%s", error);
  442. }
  443. return ret;
  444. }
  445. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  446. static void main_crash_handler(const char *format, va_list args, void *param)
  447. {
  448. char *test = new char[MAX_CRASH_REPORT_SIZE];
  449. vsnprintf(test, MAX_CRASH_REPORT_SIZE, format, args);
  450. OBSCrashReport crashReport(nullptr, test);
  451. crashReport.exec();
  452. exit(-1);
  453. UNUSED_PARAMETER(param);
  454. }
  455. int main(int argc, char *argv[])
  456. {
  457. #ifndef WIN32
  458. signal(SIGPIPE, SIG_IGN);
  459. #endif
  460. base_set_crash_handler(main_crash_handler, nullptr);
  461. base_get_log_handler(&def_log_handler, nullptr);
  462. fstream logFile;
  463. int ret = run_program(logFile, argc, argv);
  464. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  465. base_set_log_handler(nullptr, nullptr);
  466. return ret;
  467. }