obs-app.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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 = new OBSBasic();
  210. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  211. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  212. mainWindow->OBSInit();
  213. return true;
  214. } else {
  215. return false;
  216. }
  217. }
  218. string OBSApp::GetVersionString() const
  219. {
  220. stringstream ver;
  221. #ifdef HAVE_OBSCONFIG_H
  222. ver << OBS_VERSION;
  223. #else
  224. ver << LIBOBS_API_MAJOR_VER << "." <<
  225. LIBOBS_API_MINOR_VER << "." <<
  226. LIBOBS_API_PATCH_VER;
  227. #endif
  228. ver << " (";
  229. #ifdef _WIN32
  230. if (sizeof(void*) == 8)
  231. ver << "64bit, ";
  232. ver << "windows)";
  233. #elif __APPLE__
  234. ver << "mac)";
  235. #else /* assume linux for the time being */
  236. ver << "linux)";
  237. #endif
  238. return ver.str();
  239. }
  240. #ifdef __APPLE__
  241. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  242. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  243. #elif _WIN32
  244. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  245. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  246. #else
  247. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  248. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  249. #endif
  250. const char *OBSApp::InputAudioSource() const
  251. {
  252. return INPUT_AUDIO_SOURCE;
  253. }
  254. const char *OBSApp::OutputAudioSource() const
  255. {
  256. return OUTPUT_AUDIO_SOURCE;
  257. }
  258. const char *OBSApp::GetLastLog() const
  259. {
  260. return lastLogFile.c_str();
  261. }
  262. const char *OBSApp::GetCurrentLog() const
  263. {
  264. return currentLogFile.c_str();
  265. }
  266. QString OBSTranslator::translate(const char *context, const char *sourceText,
  267. const char *disambiguation, int n) const
  268. {
  269. const char *out = nullptr;
  270. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  271. return QString();
  272. UNUSED_PARAMETER(context);
  273. UNUSED_PARAMETER(disambiguation);
  274. UNUSED_PARAMETER(n);
  275. return QT_UTF8(out);
  276. }
  277. struct NoFocusFrameStyle : QProxyStyle
  278. {
  279. void drawControl(ControlElement element, const QStyleOption *option,
  280. QPainter *painter, const QWidget *widget=nullptr)
  281. const override
  282. {
  283. if (element == CE_FocusFrame)
  284. return;
  285. QProxyStyle::drawControl(element, option, painter, widget);
  286. }
  287. };
  288. static bool get_token(lexer *lex, string &str, base_token_type type)
  289. {
  290. base_token token;
  291. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  292. return false;
  293. if (token.type != type)
  294. return false;
  295. str.assign(token.text.array, token.text.len);
  296. return true;
  297. }
  298. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  299. {
  300. base_token token;
  301. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  302. return false;
  303. if (token.type != type)
  304. return false;
  305. return strref_cmp(&token.text, str) == 0;
  306. }
  307. static uint64_t convert_log_name(const char *name)
  308. {
  309. BaseLexer lex;
  310. string year, month, day, hour, minute, second;
  311. lexer_start(lex, name);
  312. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  313. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  314. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  315. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  316. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  317. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  318. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  319. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  320. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  321. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  322. stringstream timestring;
  323. timestring << year << month << day << hour << minute << second;
  324. return std::stoull(timestring.str());
  325. }
  326. static void delete_oldest_log(void)
  327. {
  328. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  329. string oldestLog;
  330. uint64_t oldest_ts = (uint64_t)-1;
  331. struct os_dirent *entry;
  332. unsigned int maxLogs = (unsigned int)config_get_uint(
  333. App()->GlobalConfig(), "General", "MaxLogs");
  334. os_dir_t *dir = os_opendir(logDir);
  335. if (dir) {
  336. unsigned int count = 0;
  337. while ((entry = os_readdir(dir)) != NULL) {
  338. if (entry->directory || *entry->d_name == '.')
  339. continue;
  340. uint64_t ts = convert_log_name(entry->d_name);
  341. if (ts) {
  342. if (ts < oldest_ts) {
  343. oldestLog = entry->d_name;
  344. oldest_ts = ts;
  345. }
  346. count++;
  347. }
  348. }
  349. os_closedir(dir);
  350. if (count > maxLogs) {
  351. stringstream delPath;
  352. delPath << logDir << "/" << oldestLog;
  353. os_unlink(delPath.str().c_str());
  354. }
  355. }
  356. }
  357. static void get_last_log(void)
  358. {
  359. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  360. struct os_dirent *entry;
  361. os_dir_t *dir = os_opendir(logDir);
  362. uint64_t highest_ts = 0;
  363. if (dir) {
  364. while ((entry = os_readdir(dir)) != NULL) {
  365. if (entry->directory || *entry->d_name == '.')
  366. continue;
  367. uint64_t ts = convert_log_name(entry->d_name);
  368. if (ts > highest_ts) {
  369. lastLogFile = entry->d_name;
  370. highest_ts = ts;
  371. }
  372. }
  373. os_closedir(dir);
  374. }
  375. }
  376. string GenerateTimeDateFilename(const char *extension)
  377. {
  378. time_t now = time(0);
  379. char file[256] = {};
  380. struct tm *cur_time;
  381. cur_time = localtime(&now);
  382. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  383. cur_time->tm_year+1900,
  384. cur_time->tm_mon+1,
  385. cur_time->tm_mday,
  386. cur_time->tm_hour,
  387. cur_time->tm_min,
  388. cur_time->tm_sec,
  389. extension);
  390. return string(file);
  391. }
  392. vector<pair<string, string>> GetLocaleNames()
  393. {
  394. string path;
  395. if (!GetDataFilePath("locale.ini", path))
  396. throw "Could not find locale.ini path";
  397. ConfigFile ini;
  398. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  399. throw "Could not open locale.ini";
  400. size_t sections = config_num_sections(ini);
  401. vector<pair<string, string>> names;
  402. names.reserve(sections);
  403. for (size_t i = 0; i < sections; i++) {
  404. const char *tag = config_get_section(ini, i);
  405. const char *name = config_get_string(ini, tag, "Name");
  406. names.emplace_back(tag, name);
  407. }
  408. return names;
  409. }
  410. static void create_log_file(fstream &logFile)
  411. {
  412. stringstream dst;
  413. get_last_log();
  414. currentLogFile = GenerateTimeDateFilename("txt");
  415. dst << "obs-studio/logs/" << currentLogFile.c_str();
  416. BPtr<char> path(os_get_config_path(dst.str().c_str()));
  417. logFile.open(path,
  418. ios_base::in | ios_base::out | ios_base::trunc);
  419. if (logFile.is_open()) {
  420. delete_oldest_log();
  421. base_set_log_handler(do_log, &logFile);
  422. } else {
  423. blog(LOG_ERROR, "Failed to open log file");
  424. }
  425. }
  426. static int run_program(fstream &logFile, int argc, char *argv[])
  427. {
  428. int ret = -1;
  429. QCoreApplication::addLibraryPath(".");
  430. OBSApp program(argc, argv);
  431. try {
  432. program.AppInit();
  433. OBSTranslator translator;
  434. create_log_file(logFile);
  435. program.installTranslator(&translator);
  436. program.setStyle(new NoFocusFrameStyle);
  437. ret = program.OBSInit() ? program.exec() : 0;
  438. } catch (const char *error) {
  439. blog(LOG_ERROR, "%s", error);
  440. OBSErrorBox(nullptr, "%s", error);
  441. }
  442. return ret;
  443. }
  444. int main(int argc, char *argv[])
  445. {
  446. #ifndef WIN32
  447. signal(SIGPIPE, SIG_IGN);
  448. #endif
  449. base_get_log_handler(&def_log_handler, nullptr);
  450. fstream logFile;
  451. int ret = run_program(logFile, argc, argv);
  452. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  453. base_set_log_handler(nullptr, nullptr);
  454. return ret;
  455. }