obs-app.cpp 12 KB

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