1
0

obs-app.cpp 27 KB

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