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