obs-app.cpp 27 KB

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