obs-app.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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 <wchar.h>
  17. #include <chrono>
  18. #include <ratio>
  19. #include <sstream>
  20. #include <mutex>
  21. #include <util/bmem.h>
  22. #include <util/dstr.h>
  23. #include <util/platform.h>
  24. #include <util/profiler.hpp>
  25. #include <obs-config.h>
  26. #include <obs.hpp>
  27. #include <QProxyStyle>
  28. #include "qt-wrappers.hpp"
  29. #include "obs-app.hpp"
  30. #include "window-basic-main.hpp"
  31. #include "window-basic-settings.hpp"
  32. #include "window-license-agreement.hpp"
  33. #include "crash-report.hpp"
  34. #include "platform.hpp"
  35. #include <fstream>
  36. #include <curl/curl.h>
  37. #ifdef _WIN32
  38. #include <windows.h>
  39. #else
  40. #include <signal.h>
  41. #endif
  42. using namespace std;
  43. static log_handler_t def_log_handler;
  44. static string currentLogFile;
  45. static string lastLogFile;
  46. static bool portable_mode = false;
  47. QObject *CreateShortcutFilter()
  48. {
  49. return new OBSEventFilter([](QObject *obj, QEvent *event)
  50. {
  51. auto mouse_event = [](QMouseEvent &event)
  52. {
  53. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  54. bool pressed = event.type() == QEvent::MouseButtonPress;
  55. switch (event.button()) {
  56. case Qt::NoButton:
  57. case Qt::LeftButton:
  58. case Qt::RightButton:
  59. case Qt::AllButtons:
  60. case Qt::MouseButtonMask:
  61. return false;
  62. case Qt::MidButton:
  63. hotkey.key = OBS_KEY_MOUSE3;
  64. break;
  65. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  66. hotkey.key = OBS_KEY_MOUSE ## j; break;
  67. MAP_BUTTON( 1, 4);
  68. MAP_BUTTON( 2, 5);
  69. MAP_BUTTON( 3, 6);
  70. MAP_BUTTON( 4, 7);
  71. MAP_BUTTON( 5, 8);
  72. MAP_BUTTON( 6, 9);
  73. MAP_BUTTON( 7, 10);
  74. MAP_BUTTON( 8, 11);
  75. MAP_BUTTON( 9, 12);
  76. MAP_BUTTON(10, 13);
  77. MAP_BUTTON(11, 14);
  78. MAP_BUTTON(12, 15);
  79. MAP_BUTTON(13, 16);
  80. MAP_BUTTON(14, 17);
  81. MAP_BUTTON(15, 18);
  82. MAP_BUTTON(16, 19);
  83. MAP_BUTTON(17, 20);
  84. MAP_BUTTON(18, 21);
  85. MAP_BUTTON(19, 22);
  86. MAP_BUTTON(20, 23);
  87. MAP_BUTTON(21, 24);
  88. MAP_BUTTON(22, 25);
  89. MAP_BUTTON(23, 26);
  90. MAP_BUTTON(24, 27);
  91. #undef MAP_BUTTON
  92. }
  93. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  94. event.modifiers());
  95. obs_hotkey_inject_event(hotkey, pressed);
  96. return true;
  97. };
  98. auto key_event = [&](QKeyEvent *event)
  99. {
  100. QDialog *dialog = qobject_cast<QDialog*>(obj);
  101. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  102. bool pressed = event->type() == QEvent::KeyPress;
  103. switch (event->key()) {
  104. case Qt::Key_Shift:
  105. case Qt::Key_Control:
  106. case Qt::Key_Alt:
  107. case Qt::Key_Meta:
  108. break;
  109. #ifdef __APPLE__
  110. case Qt::Key_CapsLock:
  111. // kVK_CapsLock == 57
  112. hotkey.key = obs_key_from_virtual_key(57);
  113. pressed = true;
  114. break;
  115. #endif
  116. case Qt::Key_Enter:
  117. case Qt::Key_Escape:
  118. case Qt::Key_Return:
  119. if (dialog && pressed)
  120. return false;
  121. default:
  122. hotkey.key = obs_key_from_virtual_key(
  123. event->nativeVirtualKey());
  124. }
  125. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  126. event->modifiers());
  127. obs_hotkey_inject_event(hotkey, pressed);
  128. return true;
  129. };
  130. switch (event->type()) {
  131. case QEvent::MouseButtonPress:
  132. case QEvent::MouseButtonRelease:
  133. return mouse_event(*static_cast<QMouseEvent*>(event));
  134. /*case QEvent::MouseButtonDblClick:
  135. case QEvent::Wheel:*/
  136. case QEvent::KeyPress:
  137. case QEvent::KeyRelease:
  138. return key_event(static_cast<QKeyEvent*>(event));
  139. default:
  140. return false;
  141. }
  142. });
  143. }
  144. string CurrentTimeString()
  145. {
  146. using namespace std::chrono;
  147. struct tm tstruct;
  148. char buf[80];
  149. auto tp = system_clock::now();
  150. auto now = system_clock::to_time_t(tp);
  151. tstruct = *localtime(&now);
  152. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  153. if (ratio_less<system_clock::period, seconds::period>::value &&
  154. written && (sizeof(buf) - written) > 5) {
  155. auto tp_secs =
  156. time_point_cast<seconds>(tp);
  157. auto millis =
  158. duration_cast<milliseconds>(tp - tp_secs).count();
  159. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  160. static_cast<unsigned>(millis));
  161. }
  162. return buf;
  163. }
  164. string CurrentDateTimeString()
  165. {
  166. time_t now = time(0);
  167. struct tm tstruct;
  168. char buf[80];
  169. tstruct = *localtime(&now);
  170. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  171. return buf;
  172. }
  173. static inline void LogString(fstream &logFile, const char *timeString,
  174. char *str)
  175. {
  176. logFile << timeString << str << endl;
  177. }
  178. static inline void LogStringChunk(fstream &logFile, char *str)
  179. {
  180. char *nextLine = str;
  181. string timeString = CurrentTimeString();
  182. timeString += ": ";
  183. while (*nextLine) {
  184. char *nextLine = strchr(str, '\n');
  185. if (!nextLine)
  186. break;
  187. if (nextLine != str && nextLine[-1] == '\r') {
  188. nextLine[-1] = 0;
  189. } else {
  190. nextLine[0] = 0;
  191. }
  192. LogString(logFile, timeString.c_str(), str);
  193. nextLine++;
  194. str = nextLine;
  195. }
  196. LogString(logFile, timeString.c_str(), str);
  197. }
  198. #define MAX_REPEATED_LINES 30
  199. #define MAX_CHAR_VARIATION (255 * 3)
  200. static inline int sum_chars(const char *str)
  201. {
  202. int val = 0;
  203. for (; *str != 0; str++)
  204. val += *str;
  205. return val;
  206. }
  207. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  208. const char *output_str)
  209. {
  210. static mutex log_mutex;
  211. static const char *last_msg_ptr = nullptr;
  212. static int last_char_sum = 0;
  213. static char cmp_str[4096];
  214. static int rep_count = 0;
  215. int new_sum = sum_chars(output_str);
  216. lock_guard<mutex> guard(log_mutex);
  217. if (last_msg_ptr == msg) {
  218. int diff = std::abs(new_sum - last_char_sum);
  219. if (diff < MAX_CHAR_VARIATION) {
  220. return (rep_count++ >= MAX_REPEATED_LINES);
  221. }
  222. }
  223. if (rep_count > MAX_REPEATED_LINES) {
  224. logFile << CurrentTimeString() <<
  225. ": Last log entry repeated for " <<
  226. to_string(rep_count - MAX_REPEATED_LINES) <<
  227. " more lines" << endl;
  228. }
  229. last_msg_ptr = msg;
  230. strcpy(cmp_str, output_str);
  231. last_char_sum = new_sum;
  232. rep_count = 0;
  233. return false;
  234. }
  235. static void do_log(int log_level, const char *msg, va_list args, void *param)
  236. {
  237. fstream &logFile = *static_cast<fstream*>(param);
  238. char str[4096];
  239. #ifndef _WIN32
  240. va_list args2;
  241. va_copy(args2, args);
  242. #endif
  243. vsnprintf(str, 4095, msg, args);
  244. #ifdef _WIN32
  245. OutputDebugStringA(str);
  246. OutputDebugStringA("\n");
  247. #else
  248. def_log_handler(log_level, msg, args2, nullptr);
  249. #endif
  250. if (too_many_repeated_entries(logFile, msg, str))
  251. return;
  252. if (log_level <= LOG_INFO)
  253. LogStringChunk(logFile, str);
  254. #ifdef _WIN32
  255. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  256. __debugbreak();
  257. #endif
  258. }
  259. #define DEFAULT_LANG "en-US"
  260. bool OBSApp::InitGlobalConfigDefaults()
  261. {
  262. config_set_default_string(globalConfig, "General", "Language",
  263. DEFAULT_LANG);
  264. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  265. #if _WIN32
  266. config_set_default_string(globalConfig, "Video", "Renderer",
  267. "Direct3D 11");
  268. #else
  269. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  270. #endif
  271. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  272. true);
  273. return true;
  274. }
  275. static bool do_mkdir(const char *path)
  276. {
  277. if (os_mkdirs(path) == MKDIR_ERROR) {
  278. OBSErrorBox(NULL, "Failed to create directory %s", path);
  279. return false;
  280. }
  281. return true;
  282. }
  283. static bool MakeUserDirs()
  284. {
  285. char path[512];
  286. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  287. return false;
  288. if (!do_mkdir(path))
  289. return false;
  290. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  291. return false;
  292. if (!do_mkdir(path))
  293. return false;
  294. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  295. return false;
  296. if (!do_mkdir(path))
  297. return false;
  298. #ifdef _WIN32
  299. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  300. return false;
  301. if (!do_mkdir(path))
  302. return false;
  303. #endif
  304. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  305. return false;
  306. if (!do_mkdir(path))
  307. return false;
  308. return true;
  309. }
  310. static bool MakeUserProfileDirs()
  311. {
  312. char path[512];
  313. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  314. return false;
  315. if (!do_mkdir(path))
  316. return false;
  317. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  318. return false;
  319. if (!do_mkdir(path))
  320. return false;
  321. return true;
  322. }
  323. bool OBSApp::InitGlobalConfig()
  324. {
  325. char path[512];
  326. int len = GetConfigPath(path, sizeof(path),
  327. "obs-studio/global.ini");
  328. if (len <= 0) {
  329. return false;
  330. }
  331. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  332. if (errorcode != CONFIG_SUCCESS) {
  333. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  334. return false;
  335. }
  336. return InitGlobalConfigDefaults();
  337. }
  338. bool OBSApp::InitLocale()
  339. {
  340. ProfileScope("OBSApp::InitLocale");
  341. const char *lang = config_get_string(globalConfig, "General",
  342. "Language");
  343. locale = lang;
  344. string englishPath;
  345. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  346. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  347. return false;
  348. }
  349. textLookup = text_lookup_create(englishPath.c_str());
  350. if (!textLookup) {
  351. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  352. englishPath.c_str());
  353. return false;
  354. }
  355. bool userLocale = config_has_user_value(globalConfig, "General",
  356. "Language");
  357. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  358. if (userLocale && defaultLang)
  359. return true;
  360. if (!userLocale && defaultLang) {
  361. for (auto &locale_ : GetPreferredLocales()) {
  362. if (locale_ == lang)
  363. return true;
  364. stringstream file;
  365. file << "locale/" << locale_ << ".ini";
  366. string path;
  367. if (!GetDataFilePath(file.str().c_str(), path))
  368. continue;
  369. if (!text_lookup_add(textLookup, path.c_str()))
  370. continue;
  371. blog(LOG_INFO, "Using preferred locale '%s'",
  372. locale_.c_str());
  373. locale = locale_;
  374. return true;
  375. }
  376. return true;
  377. }
  378. stringstream file;
  379. file << "locale/" << lang << ".ini";
  380. string path;
  381. if (GetDataFilePath(file.str().c_str(), path)) {
  382. if (!text_lookup_add(textLookup, path.c_str()))
  383. blog(LOG_ERROR, "Failed to add locale file '%s'",
  384. path.c_str());
  385. } else {
  386. blog(LOG_ERROR, "Could not find locale file '%s'",
  387. file.str().c_str());
  388. }
  389. return true;
  390. }
  391. bool OBSApp::SetTheme(std::string name, std::string path)
  392. {
  393. theme = name;
  394. /* Check user dir first, then preinstalled themes. */
  395. if (path == "") {
  396. char userDir[512];
  397. name = "themes/" + name + ".qss";
  398. string temp = "obs-studio/" + name;
  399. int ret = GetConfigPath(userDir, sizeof(userDir),
  400. temp.c_str());
  401. if (ret > 0 && QFile::exists(userDir)) {
  402. path = string(userDir);
  403. } else if (!GetDataFilePath(name.c_str(), path)) {
  404. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  405. return false;
  406. }
  407. }
  408. QString mpath = QString("file:///") + path.c_str();
  409. setStyleSheet(mpath);
  410. return true;
  411. }
  412. bool OBSApp::InitTheme()
  413. {
  414. const char *themeName = config_get_string(globalConfig, "General",
  415. "Theme");
  416. if (!themeName)
  417. themeName = "Default";
  418. stringstream t;
  419. t << themeName;
  420. return SetTheme(t.str());
  421. }
  422. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  423. : QApplication(argc, argv),
  424. profilerNameStore(store)
  425. {}
  426. static void move_basic_to_profiles(void)
  427. {
  428. char path[512];
  429. char new_path[512];
  430. os_glob_t *glob;
  431. /* if not first time use */
  432. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  433. return;
  434. if (!os_file_exists(path))
  435. return;
  436. /* if the profiles directory doesn't already exist */
  437. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  438. return;
  439. if (os_file_exists(new_path))
  440. return;
  441. if (os_mkdir(new_path) == MKDIR_ERROR)
  442. return;
  443. strcat(new_path, "/");
  444. strcat(new_path, Str("Untitled"));
  445. if (os_mkdir(new_path) == MKDIR_ERROR)
  446. return;
  447. strcat(path, "/*.*");
  448. if (os_glob(path, 0, &glob) != 0)
  449. return;
  450. strcpy(path, new_path);
  451. for (size_t i = 0; i < glob->gl_pathc; i++) {
  452. struct os_globent ent = glob->gl_pathv[i];
  453. char *file;
  454. if (ent.directory)
  455. continue;
  456. file = strrchr(ent.path, '/');
  457. if (!file++)
  458. continue;
  459. if (astrcmpi(file, "scenes.json") == 0)
  460. continue;
  461. strcpy(new_path, path);
  462. strcat(new_path, "/");
  463. strcat(new_path, file);
  464. os_rename(ent.path, new_path);
  465. }
  466. os_globfree(glob);
  467. }
  468. static void move_basic_to_scene_collections(void)
  469. {
  470. char path[512];
  471. char new_path[512];
  472. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  473. return;
  474. if (!os_file_exists(path))
  475. return;
  476. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  477. return;
  478. if (os_file_exists(new_path))
  479. return;
  480. if (os_mkdir(new_path) == MKDIR_ERROR)
  481. return;
  482. strcat(path, "/scenes.json");
  483. strcat(new_path, "/");
  484. strcat(new_path, Str("Untitled"));
  485. strcat(new_path, ".json");
  486. os_rename(path, new_path);
  487. }
  488. void OBSApp::AppInit()
  489. {
  490. ProfileScope("OBSApp::AppInit");
  491. if (!InitApplicationBundle())
  492. throw "Failed to initialize application bundle";
  493. if (!MakeUserDirs())
  494. throw "Failed to create required user directories";
  495. if (!InitGlobalConfig())
  496. throw "Failed to initialize global config";
  497. if (!InitLocale())
  498. throw "Failed to load locale";
  499. if (!InitTheme())
  500. throw "Failed to load theme";
  501. config_set_default_string(globalConfig, "Basic", "Profile",
  502. Str("Untitled"));
  503. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  504. Str("Untitled"));
  505. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  506. Str("Untitled"));
  507. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  508. Str("Untitled"));
  509. move_basic_to_profiles();
  510. move_basic_to_scene_collections();
  511. if (!MakeUserProfileDirs())
  512. throw "Failed to create profile directories";
  513. }
  514. const char *OBSApp::GetRenderModule() const
  515. {
  516. const char *renderer = config_get_string(globalConfig, "Video",
  517. "Renderer");
  518. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  519. DL_D3D11 : DL_OPENGL;
  520. }
  521. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  522. {
  523. char path[512];
  524. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  525. return false;
  526. return obs_startup(locale, path, store);
  527. }
  528. bool OBSApp::OBSInit()
  529. {
  530. ProfileScope("OBSApp::OBSInit");
  531. bool licenseAccepted = config_get_bool(globalConfig, "General",
  532. "LicenseAccepted");
  533. OBSLicenseAgreement agreement(nullptr);
  534. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  535. if (!licenseAccepted) {
  536. config_set_bool(globalConfig, "General",
  537. "LicenseAccepted", true);
  538. config_save(globalConfig);
  539. }
  540. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  541. return false;
  542. mainWindow = new OBSBasic();
  543. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  544. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  545. mainWindow->OBSInit();
  546. connect(this, &QGuiApplication::applicationStateChanged,
  547. [](Qt::ApplicationState state)
  548. {
  549. obs_hotkey_enable_background_press(
  550. state != Qt::ApplicationActive);
  551. });
  552. obs_hotkey_enable_background_press(
  553. applicationState() != Qt::ApplicationActive);
  554. return true;
  555. } else {
  556. return false;
  557. }
  558. }
  559. string OBSApp::GetVersionString() const
  560. {
  561. stringstream ver;
  562. #ifdef HAVE_OBSCONFIG_H
  563. ver << OBS_VERSION;
  564. #else
  565. ver << LIBOBS_API_MAJOR_VER << "." <<
  566. LIBOBS_API_MINOR_VER << "." <<
  567. LIBOBS_API_PATCH_VER;
  568. #endif
  569. ver << " (";
  570. #ifdef _WIN32
  571. if (sizeof(void*) == 8)
  572. ver << "64bit, ";
  573. ver << "windows)";
  574. #elif __APPLE__
  575. ver << "mac)";
  576. #elif __FreeBSD__
  577. ver << "freebsd)";
  578. #else /* assume linux for the time being */
  579. ver << "linux)";
  580. #endif
  581. return ver.str();
  582. }
  583. #ifdef __APPLE__
  584. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  585. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  586. #elif _WIN32
  587. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  588. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  589. #else
  590. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  591. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  592. #endif
  593. const char *OBSApp::InputAudioSource() const
  594. {
  595. return INPUT_AUDIO_SOURCE;
  596. }
  597. const char *OBSApp::OutputAudioSource() const
  598. {
  599. return OUTPUT_AUDIO_SOURCE;
  600. }
  601. const char *OBSApp::GetLastLog() const
  602. {
  603. return lastLogFile.c_str();
  604. }
  605. const char *OBSApp::GetCurrentLog() const
  606. {
  607. return currentLogFile.c_str();
  608. }
  609. QString OBSTranslator::translate(const char *context, const char *sourceText,
  610. const char *disambiguation, int n) const
  611. {
  612. const char *out = nullptr;
  613. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  614. return QString();
  615. UNUSED_PARAMETER(context);
  616. UNUSED_PARAMETER(disambiguation);
  617. UNUSED_PARAMETER(n);
  618. return QT_UTF8(out);
  619. }
  620. static bool get_token(lexer *lex, string &str, base_token_type type)
  621. {
  622. base_token token;
  623. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  624. return false;
  625. if (token.type != type)
  626. return false;
  627. str.assign(token.text.array, token.text.len);
  628. return true;
  629. }
  630. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  631. {
  632. base_token token;
  633. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  634. return false;
  635. if (token.type != type)
  636. return false;
  637. return strref_cmp(&token.text, str) == 0;
  638. }
  639. static uint64_t convert_log_name(const char *name)
  640. {
  641. BaseLexer lex;
  642. string year, month, day, hour, minute, second;
  643. lexer_start(lex, name);
  644. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  645. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  646. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  647. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  648. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  649. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  650. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  651. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  652. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  653. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  654. stringstream timestring;
  655. timestring << year << month << day << hour << minute << second;
  656. return std::stoull(timestring.str());
  657. }
  658. static void delete_oldest_file(const char *location)
  659. {
  660. BPtr<char> logDir(GetConfigPathPtr(location));
  661. string oldestLog;
  662. uint64_t oldest_ts = (uint64_t)-1;
  663. struct os_dirent *entry;
  664. unsigned int maxLogs = (unsigned int)config_get_uint(
  665. App()->GlobalConfig(), "General", "MaxLogs");
  666. os_dir_t *dir = os_opendir(logDir);
  667. if (dir) {
  668. unsigned int count = 0;
  669. while ((entry = os_readdir(dir)) != NULL) {
  670. if (entry->directory || *entry->d_name == '.')
  671. continue;
  672. uint64_t ts = convert_log_name(entry->d_name);
  673. if (ts) {
  674. if (ts < oldest_ts) {
  675. oldestLog = entry->d_name;
  676. oldest_ts = ts;
  677. }
  678. count++;
  679. }
  680. }
  681. os_closedir(dir);
  682. if (count > maxLogs) {
  683. stringstream delPath;
  684. delPath << logDir << "/" << oldestLog;
  685. os_unlink(delPath.str().c_str());
  686. }
  687. }
  688. }
  689. static void get_last_log(void)
  690. {
  691. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  692. struct os_dirent *entry;
  693. os_dir_t *dir = os_opendir(logDir);
  694. uint64_t highest_ts = 0;
  695. if (dir) {
  696. while ((entry = os_readdir(dir)) != NULL) {
  697. if (entry->directory || *entry->d_name == '.')
  698. continue;
  699. uint64_t ts = convert_log_name(entry->d_name);
  700. if (ts > highest_ts) {
  701. lastLogFile = entry->d_name;
  702. highest_ts = ts;
  703. }
  704. }
  705. os_closedir(dir);
  706. }
  707. }
  708. string GenerateTimeDateFilename(const char *extension)
  709. {
  710. time_t now = time(0);
  711. char file[256] = {};
  712. struct tm *cur_time;
  713. cur_time = localtime(&now);
  714. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  715. cur_time->tm_year+1900,
  716. cur_time->tm_mon+1,
  717. cur_time->tm_mday,
  718. cur_time->tm_hour,
  719. cur_time->tm_min,
  720. cur_time->tm_sec,
  721. extension);
  722. return string(file);
  723. }
  724. vector<pair<string, string>> GetLocaleNames()
  725. {
  726. string path;
  727. if (!GetDataFilePath("locale.ini", path))
  728. throw "Could not find locale.ini path";
  729. ConfigFile ini;
  730. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  731. throw "Could not open locale.ini";
  732. size_t sections = config_num_sections(ini);
  733. vector<pair<string, string>> names;
  734. names.reserve(sections);
  735. for (size_t i = 0; i < sections; i++) {
  736. const char *tag = config_get_section(ini, i);
  737. const char *name = config_get_string(ini, tag, "Name");
  738. names.emplace_back(tag, name);
  739. }
  740. return names;
  741. }
  742. static void create_log_file(fstream &logFile)
  743. {
  744. stringstream dst;
  745. get_last_log();
  746. currentLogFile = GenerateTimeDateFilename("txt");
  747. dst << "obs-studio/logs/" << currentLogFile.c_str();
  748. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  749. logFile.open(path,
  750. ios_base::in | ios_base::out | ios_base::trunc);
  751. if (logFile.is_open()) {
  752. delete_oldest_file("obs-studio/logs");
  753. base_set_log_handler(do_log, &logFile);
  754. } else {
  755. blog(LOG_ERROR, "Failed to open log file");
  756. }
  757. }
  758. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  759. {
  760. profiler_name_store_free(store);
  761. };
  762. using ProfilerNameStore =
  763. std::unique_ptr<profiler_name_store_t,
  764. decltype(ProfilerNameStoreRelease)>;
  765. ProfilerNameStore CreateNameStore()
  766. {
  767. return ProfilerNameStore{profiler_name_store_create(),
  768. ProfilerNameStoreRelease};
  769. }
  770. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  771. {
  772. profile_snapshot_free(snap);
  773. };
  774. using ProfilerSnapshot =
  775. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  776. ProfilerSnapshot GetSnapshot()
  777. {
  778. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  779. }
  780. static void SaveProfilerData(const ProfilerSnapshot &snap)
  781. {
  782. if (currentLogFile.empty())
  783. return;
  784. auto pos = currentLogFile.rfind('.');
  785. if (pos == currentLogFile.npos)
  786. return;
  787. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  788. ostringstream dst;
  789. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  790. dst.write(currentLogFile.c_str(), pos);
  791. dst.write(LITERAL_SIZE(".csv.gz"));
  792. #undef LITERAL_SIZE
  793. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  794. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  795. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  796. static_cast<const char*>(path));
  797. }
  798. static auto ProfilerFree = [](void *)
  799. {
  800. profiler_stop();
  801. auto snap = GetSnapshot();
  802. profiler_print(snap.get());
  803. profiler_print_time_between_calls(snap.get());
  804. SaveProfilerData(snap);
  805. profiler_free();
  806. };
  807. static const char *run_program_init = "run_program_init";
  808. static int run_program(fstream &logFile, int argc, char *argv[])
  809. {
  810. int ret = -1;
  811. auto profilerNameStore = CreateNameStore();
  812. std::unique_ptr<void, decltype(ProfilerFree)>
  813. prof_release(static_cast<void*>(&ProfilerFree),
  814. ProfilerFree);
  815. profiler_start();
  816. profile_register_root(run_program_init, 0);
  817. auto PrintInitProfile = [&]()
  818. {
  819. auto snap = GetSnapshot();
  820. profiler_snapshot_filter_roots(snap.get(), [](void *data,
  821. const char *name, bool *remove)
  822. {
  823. *remove = (*static_cast<const char**>(data)) != name;
  824. return true;
  825. }, static_cast<void*>(&run_program_init));
  826. profiler_print(snap.get());
  827. };
  828. ScopeProfiler prof{run_program_init};
  829. QCoreApplication::addLibraryPath(".");
  830. OBSApp program(argc, argv, profilerNameStore.get());
  831. try {
  832. program.AppInit();
  833. OBSTranslator translator;
  834. create_log_file(logFile);
  835. delete_oldest_file("obs-studio/profiler_data");
  836. program.installTranslator(&translator);
  837. if (!program.OBSInit())
  838. return 0;
  839. prof.Stop();
  840. PrintInitProfile();
  841. return program.exec();
  842. } catch (const char *error) {
  843. blog(LOG_ERROR, "%s", error);
  844. OBSErrorBox(nullptr, "%s", error);
  845. }
  846. return ret;
  847. }
  848. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  849. #ifdef _WIN32
  850. #define CRASH_MESSAGE \
  851. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  852. "to the clipboard? (Crash logs will still be saved to the " \
  853. "%appdata%\\obs-studio\\crashes directory)"
  854. static void main_crash_handler(const char *format, va_list args, void *param)
  855. {
  856. char *text = new char[MAX_CRASH_REPORT_SIZE];
  857. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  858. delete_oldest_file("obs-studio/crashes");
  859. string name = "obs-studio/crashes/Crash ";
  860. name += GenerateTimeDateFilename("txt");
  861. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  862. fstream file;
  863. file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  864. file << text;
  865. file.close();
  866. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  867. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  868. if (ret == IDYES) {
  869. size_t len = strlen(text);
  870. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  871. memcpy(GlobalLock(mem), text, len);
  872. GlobalUnlock(mem);
  873. OpenClipboard(0);
  874. EmptyClipboard();
  875. SetClipboardData(CF_TEXT, mem);
  876. CloseClipboard();
  877. }
  878. exit(-1);
  879. UNUSED_PARAMETER(param);
  880. }
  881. static void load_debug_privilege(void)
  882. {
  883. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  884. TOKEN_PRIVILEGES tp;
  885. HANDLE token;
  886. LUID val;
  887. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  888. return;
  889. }
  890. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  891. tp.PrivilegeCount = 1;
  892. tp.Privileges[0].Luid = val;
  893. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  894. AdjustTokenPrivileges(token, false, &tp,
  895. sizeof(tp), NULL, NULL);
  896. }
  897. CloseHandle(token);
  898. }
  899. #endif
  900. #ifdef __APPLE__
  901. #define BASE_PATH ".."
  902. #else
  903. #define BASE_PATH "../.."
  904. #endif
  905. #define CONFIG_PATH BASE_PATH "/config"
  906. #ifndef OBS_UNIX_STRUCTURE
  907. #define OBS_UNIX_STRUCTURE 0
  908. #endif
  909. int GetConfigPath(char *path, size_t size, const char *name)
  910. {
  911. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  912. if (name && *name) {
  913. return snprintf(path, size, CONFIG_PATH "/%s", name);
  914. } else {
  915. return snprintf(path, size, CONFIG_PATH);
  916. }
  917. } else {
  918. return os_get_config_path(path, size, name);
  919. }
  920. }
  921. char *GetConfigPathPtr(const char *name)
  922. {
  923. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  924. char path[512];
  925. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  926. return bstrdup(path);
  927. } else {
  928. return NULL;
  929. }
  930. } else {
  931. return os_get_config_path_ptr(name);
  932. }
  933. }
  934. bool GetFileSafeName(const char *name, std::string &file)
  935. {
  936. size_t base_len = strlen(name);
  937. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  938. std::wstring wfile;
  939. if (!len)
  940. return false;
  941. wfile.resize(len);
  942. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  943. for (size_t i = wfile.size(); i > 0; i--) {
  944. size_t im1 = i - 1;
  945. if (iswspace(wfile[im1])) {
  946. wfile[im1] = '_';
  947. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  948. wfile.erase(im1, 1);
  949. }
  950. }
  951. if (wfile.size() == 0)
  952. wfile = L"characters_only";
  953. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  954. if (!len)
  955. return false;
  956. file.resize(len);
  957. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  958. return true;
  959. }
  960. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  961. {
  962. size_t len = path.size();
  963. if (extension) {
  964. path += ".";
  965. path += extension;
  966. }
  967. if (!os_file_exists(path.c_str()))
  968. return true;
  969. int index = 1;
  970. do {
  971. path.resize(len);
  972. path += std::to_string(++index);
  973. if (extension) {
  974. path += ".";
  975. path += extension;
  976. }
  977. } while (os_file_exists(path.c_str()));
  978. return true;
  979. }
  980. static inline bool arg_is(const char *arg,
  981. const char *long_form, const char *short_form)
  982. {
  983. return (long_form && strcmp(arg, long_form) == 0) ||
  984. (short_form && strcmp(arg, short_form) == 0);
  985. }
  986. #if !defined(_WIN32) && !defined(__APPLE__)
  987. #define IS_UNIX 1
  988. #endif
  989. /* if using XDG and was previously using an older build of OBS, move config
  990. * files to XDG directory */
  991. #if defined(USE_XDG) && defined(IS_UNIX)
  992. static void move_to_xdg(void)
  993. {
  994. char old_path[512];
  995. char new_path[512];
  996. char *home = getenv("HOME");
  997. if (!home)
  998. return;
  999. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1000. return;
  1001. /* make base xdg path if it doesn't already exist */
  1002. if (GetConfigPath(new_path, 512, "") <= 0)
  1003. return;
  1004. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1005. return;
  1006. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1007. return;
  1008. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1009. rename(old_path, new_path);
  1010. }
  1011. }
  1012. #endif
  1013. static void update_ffmpeg_output(const char *path)
  1014. {
  1015. ConfigFile config;
  1016. if (config.Open(path, CONFIG_OPEN_EXISTING) != CONFIG_SUCCESS)
  1017. return;
  1018. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1019. return;
  1020. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1021. if (!url)
  1022. return;
  1023. bool isActualURL = strstr(url, "://") != nullptr;
  1024. if (isActualURL)
  1025. return;
  1026. string urlStr = url;
  1027. string extension;
  1028. for (size_t i = urlStr.length(); i > 0; i--) {
  1029. size_t idx = i - 1;
  1030. if (urlStr[idx] == '.') {
  1031. extension = &urlStr[i];
  1032. }
  1033. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1034. urlStr[idx] = 0;
  1035. break;
  1036. }
  1037. }
  1038. if (urlStr.empty() || extension.empty())
  1039. return;
  1040. config_remove_value(config, "AdvOut", "FFURL");
  1041. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1042. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1043. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1044. config_save(config);
  1045. }
  1046. static void upgrade_settings(void)
  1047. {
  1048. char path[512];
  1049. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1050. if (pathlen <= 0)
  1051. return;
  1052. if (!os_file_exists(path))
  1053. return;
  1054. os_dir_t *dir = os_opendir(path);
  1055. if (!dir)
  1056. return;
  1057. struct os_dirent *ent = os_readdir(dir);
  1058. while (ent) {
  1059. if (ent->directory) {
  1060. strcat(path, "/");
  1061. strcat(path, ent->d_name);
  1062. strcat(path, "/basic.ini");
  1063. update_ffmpeg_output(path);
  1064. path[pathlen] = 0;
  1065. }
  1066. ent = os_readdir(dir);
  1067. }
  1068. os_closedir(dir);
  1069. }
  1070. int main(int argc, char *argv[])
  1071. {
  1072. #ifndef _WIN32
  1073. signal(SIGPIPE, SIG_IGN);
  1074. #endif
  1075. #ifdef _WIN32
  1076. load_debug_privilege();
  1077. base_set_crash_handler(main_crash_handler, nullptr);
  1078. #endif
  1079. base_get_log_handler(&def_log_handler, nullptr);
  1080. #if defined(USE_XDG) && defined(IS_UNIX)
  1081. move_to_xdg();
  1082. #endif
  1083. for (int i = 1; i < argc; i++) {
  1084. if (arg_is(argv[i], "--portable", "-p")) {
  1085. portable_mode = true;
  1086. }
  1087. }
  1088. #if !OBS_UNIX_STRUCTURE
  1089. if (!portable_mode) {
  1090. portable_mode =
  1091. os_file_exists(BASE_PATH "/portable_mode") ||
  1092. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1093. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1094. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1095. }
  1096. #endif
  1097. upgrade_settings();
  1098. fstream logFile;
  1099. curl_global_init(CURL_GLOBAL_ALL);
  1100. int ret = run_program(logFile, argc, argv);
  1101. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1102. base_set_log_handler(nullptr, nullptr);
  1103. return ret;
  1104. }