obs-app.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. bool OBSApp::InitGlobalConfigDefaults()
  79. {
  80. config_set_default_string(globalConfig, "General", "Language", "en-US");
  81. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  82. #if _WIN32
  83. config_set_default_string(globalConfig, "Video", "Renderer",
  84. "Direct3D 11");
  85. #else
  86. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  87. #endif
  88. return true;
  89. }
  90. static bool do_mkdir(const char *path)
  91. {
  92. if (os_mkdir(path) == MKDIR_ERROR) {
  93. OBSErrorBox(NULL, "Failed to create directory %s", path);
  94. return false;
  95. }
  96. return true;
  97. }
  98. static bool MakeUserDirs()
  99. {
  100. BPtr<char> path;
  101. path = os_get_config_path("obs-studio");
  102. if (!do_mkdir(path))
  103. return false;
  104. path = os_get_config_path("obs-studio/basic");
  105. if (!do_mkdir(path))
  106. return false;
  107. path = os_get_config_path("obs-studio/logs");
  108. if (!do_mkdir(path))
  109. return false;
  110. return true;
  111. }
  112. bool OBSApp::InitGlobalConfig()
  113. {
  114. BPtr<char> path(os_get_config_path("obs-studio/global.ini"));
  115. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  116. if (errorcode != CONFIG_SUCCESS) {
  117. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  118. return false;
  119. }
  120. return InitGlobalConfigDefaults();
  121. }
  122. #define DEFAULT_LANG "en-US"
  123. bool OBSApp::InitLocale()
  124. {
  125. const char *lang = config_get_string(globalConfig, "General",
  126. "Language");
  127. locale = lang;
  128. stringstream file;
  129. file << "locale/" << lang << ".ini";
  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. if (astrcmpi(lang, DEFAULT_LANG) == 0)
  142. return true;
  143. string path;
  144. if (GetDataFilePath(file.str().c_str(), path)) {
  145. if (!text_lookup_add(textLookup, path.c_str()))
  146. blog(LOG_ERROR, "Failed to add locale file '%s'",
  147. path.c_str());
  148. } else {
  149. blog(LOG_ERROR, "Could not find locale file '%s'",
  150. file.str().c_str());
  151. }
  152. return true;
  153. }
  154. OBSApp::OBSApp(int &argc, char **argv)
  155. : QApplication(argc, argv)
  156. {}
  157. void OBSApp::AppInit()
  158. {
  159. if (!InitApplicationBundle())
  160. throw "Failed to initialize application bundle";
  161. if (!MakeUserDirs())
  162. throw "Failed to created required user directories";
  163. if (!InitGlobalConfig())
  164. throw "Failed to initialize global config";
  165. if (!InitLocale())
  166. throw "Failed to load locale";
  167. }
  168. const char *OBSApp::GetRenderModule() const
  169. {
  170. const char *renderer = config_get_string(globalConfig, "Video",
  171. "Renderer");
  172. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  173. "libobs-d3d11" : "libobs-opengl";
  174. }
  175. void OBSApp::OBSInit()
  176. {
  177. mainWindow = move(unique_ptr<OBSBasic>(new OBSBasic()));
  178. mainWindow->OBSInit();
  179. }
  180. string OBSApp::GetVersionString() const
  181. {
  182. stringstream ver;
  183. ver << "v" <<
  184. LIBOBS_API_MAJOR_VER << "." <<
  185. LIBOBS_API_MINOR_VER << "." <<
  186. LIBOBS_API_PATCH_VER;
  187. ver << " (";
  188. #ifdef HAVE_OBSCONFIG_H
  189. ver << OBS_VERSION << ", ";
  190. #endif
  191. #ifdef _WIN32
  192. if (sizeof(void*) == 8)
  193. ver << "64bit, ";
  194. ver << "windows)";
  195. #elif __APPLE__
  196. ver << "mac)";
  197. #else /* assume linux for the time being */
  198. ver << "linux)";
  199. #endif
  200. return ver.str();
  201. }
  202. #ifdef __APPLE__
  203. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  204. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  205. #elif _WIN32
  206. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  207. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  208. #else
  209. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  210. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  211. #endif
  212. const char *OBSApp::InputAudioSource() const
  213. {
  214. return INPUT_AUDIO_SOURCE;
  215. }
  216. const char *OBSApp::OutputAudioSource() const
  217. {
  218. return OUTPUT_AUDIO_SOURCE;
  219. }
  220. const char *OBSApp::GetLastLog() const
  221. {
  222. return lastLogFile.c_str();
  223. }
  224. const char *OBSApp::GetCurrentLog() const
  225. {
  226. return currentLogFile.c_str();
  227. }
  228. QString OBSTranslator::translate(const char *context, const char *sourceText,
  229. const char *disambiguation, int n) const
  230. {
  231. const char *out = nullptr;
  232. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  233. return QString();
  234. UNUSED_PARAMETER(context);
  235. UNUSED_PARAMETER(disambiguation);
  236. UNUSED_PARAMETER(n);
  237. return QT_UTF8(out);
  238. }
  239. struct NoFocusFrameStyle : QProxyStyle
  240. {
  241. void drawControl(ControlElement element, const QStyleOption *option,
  242. QPainter *painter, const QWidget *widget=nullptr)
  243. const override
  244. {
  245. if (element == CE_FocusFrame)
  246. return;
  247. QProxyStyle::drawControl(element, option, painter, widget);
  248. }
  249. };
  250. static bool get_token(lexer *lex, string &str, base_token_type type)
  251. {
  252. base_token token;
  253. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  254. return false;
  255. if (token.type != type)
  256. return false;
  257. str.assign(token.text.array, token.text.len);
  258. return true;
  259. }
  260. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  261. {
  262. base_token token;
  263. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  264. return false;
  265. if (token.type != type)
  266. return false;
  267. return strref_cmp(&token.text, str) == 0;
  268. }
  269. static uint64_t convert_log_name(const char *name)
  270. {
  271. BaseLexer lex;
  272. string year, month, day, hour, minute, second;
  273. lexer_start(lex, name);
  274. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  275. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  276. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  277. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  278. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  279. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  280. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  281. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  282. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  283. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  284. stringstream timestring;
  285. timestring << year << month << day << hour << minute << second;
  286. return std::stoull(timestring.str());
  287. }
  288. static void delete_oldest_log(void)
  289. {
  290. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  291. string oldestLog;
  292. uint64_t oldest_ts = (uint64_t)-1;
  293. struct os_dirent *entry;
  294. unsigned int maxLogs = (unsigned int)config_get_uint(
  295. App()->GlobalConfig(), "General", "MaxLogs");
  296. os_dir_t dir = os_opendir(logDir);
  297. if (dir) {
  298. unsigned int count = 0;
  299. while ((entry = os_readdir(dir)) != NULL) {
  300. if (entry->directory || *entry->d_name == '.')
  301. continue;
  302. uint64_t ts = convert_log_name(entry->d_name);
  303. if (ts) {
  304. if (ts < oldest_ts) {
  305. oldestLog = entry->d_name;
  306. oldest_ts = ts;
  307. }
  308. count++;
  309. }
  310. }
  311. os_closedir(dir);
  312. if (count > maxLogs) {
  313. stringstream delPath;
  314. delPath << logDir << "/" << oldestLog;
  315. os_unlink(delPath.str().c_str());
  316. }
  317. }
  318. }
  319. static void get_last_log(void)
  320. {
  321. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  322. struct os_dirent *entry;
  323. os_dir_t dir = os_opendir(logDir);
  324. uint64_t highest_ts = 0;
  325. if (dir) {
  326. while ((entry = os_readdir(dir)) != NULL) {
  327. if (entry->directory || *entry->d_name == '.')
  328. continue;
  329. uint64_t ts = convert_log_name(entry->d_name);
  330. if (ts > highest_ts) {
  331. lastLogFile = entry->d_name;
  332. highest_ts = ts;
  333. }
  334. }
  335. os_closedir(dir);
  336. }
  337. }
  338. string GenerateTimeDateFilename(const char *extension)
  339. {
  340. time_t now = time(0);
  341. char file[256] = {};
  342. struct tm *cur_time;
  343. cur_time = localtime(&now);
  344. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  345. cur_time->tm_year+1900,
  346. cur_time->tm_mon+1,
  347. cur_time->tm_mday,
  348. cur_time->tm_hour,
  349. cur_time->tm_min,
  350. cur_time->tm_sec,
  351. extension);
  352. return string(file);
  353. }
  354. static void create_log_file(fstream &logFile)
  355. {
  356. stringstream dst;
  357. get_last_log();
  358. currentLogFile = GenerateTimeDateFilename("txt");
  359. dst << "obs-studio/logs/" << currentLogFile.c_str();
  360. BPtr<char> path(os_get_config_path(dst.str().c_str()));
  361. logFile.open(path,
  362. ios_base::in | ios_base::out | ios_base::trunc);
  363. if (logFile.is_open()) {
  364. delete_oldest_log();
  365. base_set_log_handler(do_log, &logFile);
  366. } else {
  367. blog(LOG_ERROR, "Failed to open log file");
  368. }
  369. }
  370. static int run_program(fstream &logFile, int argc, char *argv[])
  371. {
  372. int ret = -1;
  373. QCoreApplication::addLibraryPath(".");
  374. OBSApp program(argc, argv);
  375. try {
  376. program.AppInit();
  377. OBSTranslator translator;
  378. create_log_file(logFile);
  379. program.installTranslator(&translator);
  380. program.setStyle(new NoFocusFrameStyle);
  381. program.OBSInit();
  382. ret = program.exec();
  383. } catch (const char *error) {
  384. blog(LOG_ERROR, "%s", error);
  385. OBSErrorBox(nullptr, "%s", error);
  386. }
  387. return ret;
  388. }
  389. int main(int argc, char *argv[])
  390. {
  391. #ifndef WIN32
  392. signal(SIGPIPE, SIG_IGN);
  393. #endif
  394. base_get_log_handler(&def_log_handler, nullptr);
  395. fstream logFile;
  396. int ret = run_program(logFile, argc, argv);
  397. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  398. base_set_log_handler(nullptr, nullptr);
  399. return ret;
  400. }