obs-app.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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.h>
  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. #ifdef _WIN32
  254. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  255. return false;
  256. if (!do_mkdir(path))
  257. return false;
  258. #endif
  259. return true;
  260. }
  261. static bool MakeUserProfileDirs()
  262. {
  263. char path[512];
  264. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  265. return false;
  266. if (!do_mkdir(path))
  267. return false;
  268. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  269. return false;
  270. if (!do_mkdir(path))
  271. return false;
  272. return true;
  273. }
  274. bool OBSApp::InitGlobalConfig()
  275. {
  276. char path[512];
  277. int len = GetConfigPath(path, sizeof(path),
  278. "obs-studio/global.ini");
  279. if (len <= 0) {
  280. return false;
  281. }
  282. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  283. if (errorcode != CONFIG_SUCCESS) {
  284. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  285. return false;
  286. }
  287. return InitGlobalConfigDefaults();
  288. }
  289. bool OBSApp::InitLocale()
  290. {
  291. const char *lang = config_get_string(globalConfig, "General",
  292. "Language");
  293. locale = lang;
  294. string englishPath;
  295. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  296. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  297. return false;
  298. }
  299. textLookup = text_lookup_create(englishPath.c_str());
  300. if (!textLookup) {
  301. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  302. englishPath.c_str());
  303. return false;
  304. }
  305. bool userLocale = config_has_user_value(globalConfig, "General",
  306. "Language");
  307. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  308. if (userLocale && defaultLang)
  309. return true;
  310. if (!userLocale && defaultLang) {
  311. for (auto &locale_ : GetPreferredLocales()) {
  312. if (locale_ == lang)
  313. return true;
  314. stringstream file;
  315. file << "locale/" << locale_ << ".ini";
  316. string path;
  317. if (!GetDataFilePath(file.str().c_str(), path))
  318. continue;
  319. if (!text_lookup_add(textLookup, path.c_str()))
  320. continue;
  321. blog(LOG_INFO, "Using preferred locale '%s'",
  322. locale_.c_str());
  323. locale = locale_;
  324. return true;
  325. }
  326. return true;
  327. }
  328. stringstream file;
  329. file << "locale/" << lang << ".ini";
  330. string path;
  331. if (GetDataFilePath(file.str().c_str(), path)) {
  332. if (!text_lookup_add(textLookup, path.c_str()))
  333. blog(LOG_ERROR, "Failed to add locale file '%s'",
  334. path.c_str());
  335. } else {
  336. blog(LOG_ERROR, "Could not find locale file '%s'",
  337. file.str().c_str());
  338. }
  339. return true;
  340. }
  341. bool OBSApp::SetTheme(std::string name, std::string path)
  342. {
  343. theme = name;
  344. /* Check user dir first, then preinstalled themes. */
  345. if (path == "") {
  346. char userDir[512];
  347. name = "themes/" + name + ".qss";
  348. string temp = "obs-studio/" + name;
  349. int ret = GetConfigPath(userDir, sizeof(userDir),
  350. temp.c_str());
  351. if (ret > 0 && QFile::exists(userDir)) {
  352. path = string(userDir);
  353. } else if (!GetDataFilePath(name.c_str(), path)) {
  354. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  355. return false;
  356. }
  357. }
  358. QString mpath = QString("file:///") + path.c_str();
  359. setStyleSheet(mpath);
  360. return true;
  361. }
  362. bool OBSApp::InitTheme()
  363. {
  364. const char *themeName = config_get_string(globalConfig, "General",
  365. "Theme");
  366. if (!themeName)
  367. themeName = "Default";
  368. stringstream t;
  369. t << themeName;
  370. return SetTheme(t.str());
  371. }
  372. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  373. : QApplication(argc, argv),
  374. profilerNameStore(store)
  375. {}
  376. static void move_basic_to_profiles(void)
  377. {
  378. char path[512];
  379. char new_path[512];
  380. os_glob_t *glob;
  381. /* if not first time use */
  382. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  383. return;
  384. if (!os_file_exists(path))
  385. return;
  386. /* if the profiles directory doesn't already exist */
  387. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  388. return;
  389. if (os_file_exists(new_path))
  390. return;
  391. if (os_mkdir(new_path) == MKDIR_ERROR)
  392. return;
  393. strcat(new_path, "/");
  394. strcat(new_path, Str("Untitled"));
  395. if (os_mkdir(new_path) == MKDIR_ERROR)
  396. return;
  397. strcat(path, "/*.*");
  398. if (os_glob(path, 0, &glob) != 0)
  399. return;
  400. strcpy(path, new_path);
  401. for (size_t i = 0; i < glob->gl_pathc; i++) {
  402. struct os_globent ent = glob->gl_pathv[i];
  403. char *file;
  404. if (ent.directory)
  405. continue;
  406. file = strrchr(ent.path, '/');
  407. if (!file++)
  408. continue;
  409. if (astrcmpi(file, "scenes.json") == 0)
  410. continue;
  411. strcpy(new_path, path);
  412. strcat(new_path, "/");
  413. strcat(new_path, file);
  414. os_rename(ent.path, new_path);
  415. }
  416. os_globfree(glob);
  417. }
  418. static void move_basic_to_scene_collections(void)
  419. {
  420. char path[512];
  421. char new_path[512];
  422. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  423. return;
  424. if (!os_file_exists(path))
  425. return;
  426. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  427. return;
  428. if (os_file_exists(new_path))
  429. return;
  430. if (os_mkdir(new_path) == MKDIR_ERROR)
  431. return;
  432. strcat(path, "/scenes.json");
  433. strcat(new_path, "/");
  434. strcat(new_path, Str("Untitled"));
  435. strcat(new_path, ".json");
  436. os_rename(path, new_path);
  437. }
  438. void OBSApp::AppInit()
  439. {
  440. if (!InitApplicationBundle())
  441. throw "Failed to initialize application bundle";
  442. if (!MakeUserDirs())
  443. throw "Failed to create required user directories";
  444. if (!InitGlobalConfig())
  445. throw "Failed to initialize global config";
  446. if (!InitLocale())
  447. throw "Failed to load locale";
  448. if (!InitTheme())
  449. throw "Failed to load theme";
  450. config_set_default_string(globalConfig, "Basic", "Profile",
  451. Str("Untitled"));
  452. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  453. Str("Untitled"));
  454. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  455. Str("Untitled"));
  456. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  457. Str("Untitled"));
  458. move_basic_to_profiles();
  459. move_basic_to_scene_collections();
  460. if (!MakeUserProfileDirs())
  461. throw "Failed to create profile directories";
  462. }
  463. const char *OBSApp::GetRenderModule() const
  464. {
  465. const char *renderer = config_get_string(globalConfig, "Video",
  466. "Renderer");
  467. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  468. DL_D3D11 : DL_OPENGL;
  469. }
  470. bool OBSApp::OBSInit()
  471. {
  472. bool licenseAccepted = config_get_bool(globalConfig, "General",
  473. "LicenseAccepted");
  474. OBSLicenseAgreement agreement(nullptr);
  475. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  476. if (!licenseAccepted) {
  477. config_set_bool(globalConfig, "General",
  478. "LicenseAccepted", true);
  479. config_save(globalConfig);
  480. }
  481. obs_startup(locale.c_str());
  482. mainWindow = new OBSBasic();
  483. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  484. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  485. mainWindow->OBSInit();
  486. connect(this, &QGuiApplication::applicationStateChanged,
  487. [](Qt::ApplicationState state)
  488. {
  489. obs_hotkey_enable_background_press(
  490. state != Qt::ApplicationActive);
  491. });
  492. obs_hotkey_enable_background_press(
  493. applicationState() != Qt::ApplicationActive);
  494. return true;
  495. } else {
  496. return false;
  497. }
  498. }
  499. string OBSApp::GetVersionString() const
  500. {
  501. stringstream ver;
  502. #ifdef HAVE_OBSCONFIG_H
  503. ver << OBS_VERSION;
  504. #else
  505. ver << LIBOBS_API_MAJOR_VER << "." <<
  506. LIBOBS_API_MINOR_VER << "." <<
  507. LIBOBS_API_PATCH_VER;
  508. #endif
  509. ver << " (";
  510. #ifdef _WIN32
  511. if (sizeof(void*) == 8)
  512. ver << "64bit, ";
  513. ver << "windows)";
  514. #elif __APPLE__
  515. ver << "mac)";
  516. #elif __FreeBSD__
  517. ver << "freebsd)";
  518. #else /* assume linux for the time being */
  519. ver << "linux)";
  520. #endif
  521. return ver.str();
  522. }
  523. #ifdef __APPLE__
  524. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  525. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  526. #elif _WIN32
  527. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  528. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  529. #else
  530. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  531. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  532. #endif
  533. const char *OBSApp::InputAudioSource() const
  534. {
  535. return INPUT_AUDIO_SOURCE;
  536. }
  537. const char *OBSApp::OutputAudioSource() const
  538. {
  539. return OUTPUT_AUDIO_SOURCE;
  540. }
  541. const char *OBSApp::GetLastLog() const
  542. {
  543. return lastLogFile.c_str();
  544. }
  545. const char *OBSApp::GetCurrentLog() const
  546. {
  547. return currentLogFile.c_str();
  548. }
  549. QString OBSTranslator::translate(const char *context, const char *sourceText,
  550. const char *disambiguation, int n) const
  551. {
  552. const char *out = nullptr;
  553. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  554. return QString();
  555. UNUSED_PARAMETER(context);
  556. UNUSED_PARAMETER(disambiguation);
  557. UNUSED_PARAMETER(n);
  558. return QT_UTF8(out);
  559. }
  560. static bool get_token(lexer *lex, string &str, base_token_type type)
  561. {
  562. base_token token;
  563. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  564. return false;
  565. if (token.type != type)
  566. return false;
  567. str.assign(token.text.array, token.text.len);
  568. return true;
  569. }
  570. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  571. {
  572. base_token token;
  573. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  574. return false;
  575. if (token.type != type)
  576. return false;
  577. return strref_cmp(&token.text, str) == 0;
  578. }
  579. static uint64_t convert_log_name(const char *name)
  580. {
  581. BaseLexer lex;
  582. string year, month, day, hour, minute, second;
  583. lexer_start(lex, name);
  584. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  585. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  586. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  587. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  588. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  589. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  590. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  591. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  592. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  593. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  594. stringstream timestring;
  595. timestring << year << month << day << hour << minute << second;
  596. return std::stoull(timestring.str());
  597. }
  598. static void delete_oldest_file(const char *location)
  599. {
  600. BPtr<char> logDir(GetConfigPathPtr(location));
  601. string oldestLog;
  602. uint64_t oldest_ts = (uint64_t)-1;
  603. struct os_dirent *entry;
  604. unsigned int maxLogs = (unsigned int)config_get_uint(
  605. App()->GlobalConfig(), "General", "MaxLogs");
  606. os_dir_t *dir = os_opendir(logDir);
  607. if (dir) {
  608. unsigned int count = 0;
  609. while ((entry = os_readdir(dir)) != NULL) {
  610. if (entry->directory || *entry->d_name == '.')
  611. continue;
  612. uint64_t ts = convert_log_name(entry->d_name);
  613. if (ts) {
  614. if (ts < oldest_ts) {
  615. oldestLog = entry->d_name;
  616. oldest_ts = ts;
  617. }
  618. count++;
  619. }
  620. }
  621. os_closedir(dir);
  622. if (count > maxLogs) {
  623. stringstream delPath;
  624. delPath << logDir << "/" << oldestLog;
  625. os_unlink(delPath.str().c_str());
  626. }
  627. }
  628. }
  629. static void get_last_log(void)
  630. {
  631. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  632. struct os_dirent *entry;
  633. os_dir_t *dir = os_opendir(logDir);
  634. uint64_t highest_ts = 0;
  635. if (dir) {
  636. while ((entry = os_readdir(dir)) != NULL) {
  637. if (entry->directory || *entry->d_name == '.')
  638. continue;
  639. uint64_t ts = convert_log_name(entry->d_name);
  640. if (ts > highest_ts) {
  641. lastLogFile = entry->d_name;
  642. highest_ts = ts;
  643. }
  644. }
  645. os_closedir(dir);
  646. }
  647. }
  648. string GenerateTimeDateFilename(const char *extension)
  649. {
  650. time_t now = time(0);
  651. char file[256] = {};
  652. struct tm *cur_time;
  653. cur_time = localtime(&now);
  654. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  655. cur_time->tm_year+1900,
  656. cur_time->tm_mon+1,
  657. cur_time->tm_mday,
  658. cur_time->tm_hour,
  659. cur_time->tm_min,
  660. cur_time->tm_sec,
  661. extension);
  662. return string(file);
  663. }
  664. vector<pair<string, string>> GetLocaleNames()
  665. {
  666. string path;
  667. if (!GetDataFilePath("locale.ini", path))
  668. throw "Could not find locale.ini path";
  669. ConfigFile ini;
  670. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  671. throw "Could not open locale.ini";
  672. size_t sections = config_num_sections(ini);
  673. vector<pair<string, string>> names;
  674. names.reserve(sections);
  675. for (size_t i = 0; i < sections; i++) {
  676. const char *tag = config_get_section(ini, i);
  677. const char *name = config_get_string(ini, tag, "Name");
  678. names.emplace_back(tag, name);
  679. }
  680. return names;
  681. }
  682. static void create_log_file(fstream &logFile)
  683. {
  684. stringstream dst;
  685. get_last_log();
  686. currentLogFile = GenerateTimeDateFilename("txt");
  687. dst << "obs-studio/logs/" << currentLogFile.c_str();
  688. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  689. logFile.open(path,
  690. ios_base::in | ios_base::out | ios_base::trunc);
  691. if (logFile.is_open()) {
  692. delete_oldest_file("obs-studio/logs");
  693. base_set_log_handler(do_log, &logFile);
  694. } else {
  695. blog(LOG_ERROR, "Failed to open log file");
  696. }
  697. }
  698. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  699. {
  700. profiler_name_store_free(store);
  701. };
  702. using ProfilerNameStore =
  703. std::unique_ptr<profiler_name_store_t,
  704. decltype(ProfilerNameStoreRelease)>;
  705. ProfilerNameStore CreateNameStore()
  706. {
  707. return ProfilerNameStore{profiler_name_store_create(),
  708. ProfilerNameStoreRelease};
  709. }
  710. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  711. {
  712. profile_snapshot_free(snap);
  713. };
  714. using ProfilerSnapshot =
  715. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  716. ProfilerSnapshot GetSnapshot()
  717. {
  718. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  719. }
  720. static auto ProfilerFree = [](void *)
  721. {
  722. profiler_stop();
  723. auto snap = GetSnapshot();
  724. profiler_print(snap.get());
  725. profiler_print_time_between_calls(snap.get());
  726. profiler_free();
  727. };
  728. static int run_program(fstream &logFile, int argc, char *argv[])
  729. {
  730. int ret = -1;
  731. auto profilerNameStore = CreateNameStore();
  732. std::unique_ptr<void, decltype(ProfilerFree)>
  733. prof_release(static_cast<void*>(&ProfilerFree),
  734. ProfilerFree);
  735. profiler_start();
  736. QCoreApplication::addLibraryPath(".");
  737. OBSApp program(argc, argv, profilerNameStore.get());
  738. try {
  739. program.AppInit();
  740. OBSTranslator translator;
  741. create_log_file(logFile);
  742. program.installTranslator(&translator);
  743. if (!program.OBSInit())
  744. return 0;
  745. return program.exec();
  746. } catch (const char *error) {
  747. blog(LOG_ERROR, "%s", error);
  748. OBSErrorBox(nullptr, "%s", error);
  749. }
  750. return ret;
  751. }
  752. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  753. #ifdef _WIN32
  754. #define CRASH_MESSAGE \
  755. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  756. "to the clipboard? (Crash logs will still be saved to the " \
  757. "%appdata%\\obs-studio\\crashes directory)"
  758. static void main_crash_handler(const char *format, va_list args, void *param)
  759. {
  760. char *text = new char[MAX_CRASH_REPORT_SIZE];
  761. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  762. delete_oldest_file("obs-studio/crashes");
  763. string name = "obs-studio/crashes/Crash ";
  764. name += GenerateTimeDateFilename("txt");
  765. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  766. fstream file;
  767. file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  768. file << text;
  769. file.close();
  770. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  771. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  772. if (ret == IDYES) {
  773. size_t len = strlen(text);
  774. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  775. memcpy(GlobalLock(mem), text, len);
  776. GlobalUnlock(mem);
  777. OpenClipboard(0);
  778. EmptyClipboard();
  779. SetClipboardData(CF_TEXT, mem);
  780. CloseClipboard();
  781. }
  782. exit(-1);
  783. UNUSED_PARAMETER(param);
  784. }
  785. static void load_debug_privilege(void)
  786. {
  787. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  788. TOKEN_PRIVILEGES tp;
  789. HANDLE token;
  790. LUID val;
  791. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  792. return;
  793. }
  794. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  795. tp.PrivilegeCount = 1;
  796. tp.Privileges[0].Luid = val;
  797. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  798. AdjustTokenPrivileges(token, false, &tp,
  799. sizeof(tp), NULL, NULL);
  800. }
  801. CloseHandle(token);
  802. }
  803. #endif
  804. #ifdef __APPLE__
  805. #define BASE_PATH ".."
  806. #else
  807. #define BASE_PATH "../.."
  808. #endif
  809. #define CONFIG_PATH BASE_PATH "/config"
  810. #ifndef OBS_UNIX_STRUCTURE
  811. #define OBS_UNIX_STRUCTURE 0
  812. #endif
  813. int GetConfigPath(char *path, size_t size, const char *name)
  814. {
  815. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  816. if (name && *name) {
  817. return snprintf(path, size, CONFIG_PATH "/%s", name);
  818. } else {
  819. return snprintf(path, size, CONFIG_PATH);
  820. }
  821. } else {
  822. return os_get_config_path(path, size, name);
  823. }
  824. }
  825. char *GetConfigPathPtr(const char *name)
  826. {
  827. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  828. char path[512];
  829. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  830. return bstrdup(path);
  831. } else {
  832. return NULL;
  833. }
  834. } else {
  835. return os_get_config_path_ptr(name);
  836. }
  837. }
  838. bool GetFileSafeName(const char *name, std::string &file)
  839. {
  840. size_t base_len = strlen(name);
  841. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  842. std::wstring wfile;
  843. if (!len)
  844. return false;
  845. wfile.resize(len);
  846. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  847. for (size_t i = wfile.size(); i > 0; i--) {
  848. size_t im1 = i - 1;
  849. if (iswspace(wfile[im1])) {
  850. wfile[im1] = '_';
  851. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  852. wfile.erase(im1, 1);
  853. }
  854. }
  855. if (wfile.size() == 0)
  856. wfile = L"characters_only";
  857. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  858. if (!len)
  859. return false;
  860. file.resize(len);
  861. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  862. return true;
  863. }
  864. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  865. {
  866. size_t len = path.size();
  867. if (extension) {
  868. path += ".";
  869. path += extension;
  870. }
  871. if (!os_file_exists(path.c_str()))
  872. return true;
  873. int index = 1;
  874. do {
  875. path.resize(len);
  876. path += std::to_string(++index);
  877. if (extension) {
  878. path += ".";
  879. path += extension;
  880. }
  881. } while (os_file_exists(path.c_str()));
  882. return true;
  883. }
  884. static inline bool arg_is(const char *arg,
  885. const char *long_form, const char *short_form)
  886. {
  887. return (long_form && strcmp(arg, long_form) == 0) ||
  888. (short_form && strcmp(arg, short_form) == 0);
  889. }
  890. #if !defined(_WIN32) && !defined(__APPLE__)
  891. #define IS_UNIX 1
  892. #endif
  893. /* if using XDG and was previously using an older build of OBS, move config
  894. * files to XDG directory */
  895. #if defined(USE_XDG) && defined(IS_UNIX)
  896. static void move_to_xdg(void)
  897. {
  898. char old_path[512];
  899. char new_path[512];
  900. char *home = getenv("HOME");
  901. if (!home)
  902. return;
  903. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  904. return;
  905. /* make base xdg path if it doesn't already exist */
  906. if (GetConfigPath(new_path, 512, "") <= 0)
  907. return;
  908. if (os_mkdirs(new_path) == MKDIR_ERROR)
  909. return;
  910. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  911. return;
  912. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  913. rename(old_path, new_path);
  914. }
  915. }
  916. #endif
  917. int main(int argc, char *argv[])
  918. {
  919. #ifndef _WIN32
  920. signal(SIGPIPE, SIG_IGN);
  921. #endif
  922. #ifdef _WIN32
  923. load_debug_privilege();
  924. base_set_crash_handler(main_crash_handler, nullptr);
  925. #endif
  926. base_get_log_handler(&def_log_handler, nullptr);
  927. #if defined(USE_XDG) && defined(IS_UNIX)
  928. move_to_xdg();
  929. #endif
  930. for (int i = 1; i < argc; i++) {
  931. if (arg_is(argv[i], "--portable", "-p")) {
  932. portable_mode = true;
  933. }
  934. }
  935. #if !OBS_UNIX_STRUCTURE
  936. if (!portable_mode) {
  937. portable_mode =
  938. os_file_exists(BASE_PATH "/portable_mode") ||
  939. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  940. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  941. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  942. }
  943. #endif
  944. fstream logFile;
  945. int ret = run_program(logFile, argc, argv);
  946. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  947. base_set_log_handler(nullptr, nullptr);
  948. return ret;
  949. }