obs-app.cpp 32 KB

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