obs-app.cpp 13 KB

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