obs-app.cpp 13 KB

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