obs-app.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  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 <QGuiApplication>
  28. #include <QProxyStyle>
  29. #include <QScreen>
  30. #include "qt-wrappers.hpp"
  31. #include "obs-app.hpp"
  32. #include "window-basic-main.hpp"
  33. #include "window-basic-settings.hpp"
  34. #include "window-license-agreement.hpp"
  35. #include "crash-report.hpp"
  36. #include "platform.hpp"
  37. #include <fstream>
  38. #include <curl/curl.h>
  39. #ifdef _WIN32
  40. #include <windows.h>
  41. #else
  42. #include <signal.h>
  43. #endif
  44. using namespace std;
  45. static log_handler_t def_log_handler;
  46. static string currentLogFile;
  47. static string lastLogFile;
  48. static bool portable_mode = false;
  49. static bool log_verbose = false;
  50. static bool unfiltered_log = false;
  51. bool opt_start_streaming = false;
  52. bool opt_start_recording = false;
  53. string opt_starting_collection;
  54. string opt_starting_profile;
  55. string opt_starting_scene;
  56. QObject *CreateShortcutFilter()
  57. {
  58. return new OBSEventFilter([](QObject *obj, QEvent *event)
  59. {
  60. auto mouse_event = [](QMouseEvent &event)
  61. {
  62. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  63. bool pressed = event.type() == QEvent::MouseButtonPress;
  64. switch (event.button()) {
  65. case Qt::NoButton:
  66. case Qt::LeftButton:
  67. case Qt::RightButton:
  68. case Qt::AllButtons:
  69. case Qt::MouseButtonMask:
  70. return false;
  71. case Qt::MidButton:
  72. hotkey.key = OBS_KEY_MOUSE3;
  73. break;
  74. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  75. hotkey.key = OBS_KEY_MOUSE ## j; break;
  76. MAP_BUTTON( 1, 4);
  77. MAP_BUTTON( 2, 5);
  78. MAP_BUTTON( 3, 6);
  79. MAP_BUTTON( 4, 7);
  80. MAP_BUTTON( 5, 8);
  81. MAP_BUTTON( 6, 9);
  82. MAP_BUTTON( 7, 10);
  83. MAP_BUTTON( 8, 11);
  84. MAP_BUTTON( 9, 12);
  85. MAP_BUTTON(10, 13);
  86. MAP_BUTTON(11, 14);
  87. MAP_BUTTON(12, 15);
  88. MAP_BUTTON(13, 16);
  89. MAP_BUTTON(14, 17);
  90. MAP_BUTTON(15, 18);
  91. MAP_BUTTON(16, 19);
  92. MAP_BUTTON(17, 20);
  93. MAP_BUTTON(18, 21);
  94. MAP_BUTTON(19, 22);
  95. MAP_BUTTON(20, 23);
  96. MAP_BUTTON(21, 24);
  97. MAP_BUTTON(22, 25);
  98. MAP_BUTTON(23, 26);
  99. MAP_BUTTON(24, 27);
  100. #undef MAP_BUTTON
  101. }
  102. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  103. event.modifiers());
  104. obs_hotkey_inject_event(hotkey, pressed);
  105. return true;
  106. };
  107. auto key_event = [&](QKeyEvent *event)
  108. {
  109. QDialog *dialog = qobject_cast<QDialog*>(obj);
  110. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  111. bool pressed = event->type() == QEvent::KeyPress;
  112. switch (event->key()) {
  113. case Qt::Key_Shift:
  114. case Qt::Key_Control:
  115. case Qt::Key_Alt:
  116. case Qt::Key_Meta:
  117. break;
  118. #ifdef __APPLE__
  119. case Qt::Key_CapsLock:
  120. // kVK_CapsLock == 57
  121. hotkey.key = obs_key_from_virtual_key(57);
  122. pressed = true;
  123. break;
  124. #endif
  125. case Qt::Key_Enter:
  126. case Qt::Key_Escape:
  127. case Qt::Key_Return:
  128. if (dialog && pressed)
  129. return false;
  130. default:
  131. hotkey.key = obs_key_from_virtual_key(
  132. event->nativeVirtualKey());
  133. }
  134. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  135. event->modifiers());
  136. obs_hotkey_inject_event(hotkey, pressed);
  137. return true;
  138. };
  139. switch (event->type()) {
  140. case QEvent::MouseButtonPress:
  141. case QEvent::MouseButtonRelease:
  142. return mouse_event(*static_cast<QMouseEvent*>(event));
  143. /*case QEvent::MouseButtonDblClick:
  144. case QEvent::Wheel:*/
  145. case QEvent::KeyPress:
  146. case QEvent::KeyRelease:
  147. return key_event(static_cast<QKeyEvent*>(event));
  148. default:
  149. return false;
  150. }
  151. });
  152. }
  153. string CurrentTimeString()
  154. {
  155. using namespace std::chrono;
  156. struct tm tstruct;
  157. char buf[80];
  158. auto tp = system_clock::now();
  159. auto now = system_clock::to_time_t(tp);
  160. tstruct = *localtime(&now);
  161. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  162. if (ratio_less<system_clock::period, seconds::period>::value &&
  163. written && (sizeof(buf) - written) > 5) {
  164. auto tp_secs =
  165. time_point_cast<seconds>(tp);
  166. auto millis =
  167. duration_cast<milliseconds>(tp - tp_secs).count();
  168. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  169. static_cast<unsigned>(millis));
  170. }
  171. return buf;
  172. }
  173. string CurrentDateTimeString()
  174. {
  175. time_t now = time(0);
  176. struct tm tstruct;
  177. char buf[80];
  178. tstruct = *localtime(&now);
  179. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  180. return buf;
  181. }
  182. static inline void LogString(fstream &logFile, const char *timeString,
  183. char *str)
  184. {
  185. logFile << timeString << str << endl;
  186. }
  187. static inline void LogStringChunk(fstream &logFile, char *str)
  188. {
  189. char *nextLine = str;
  190. string timeString = CurrentTimeString();
  191. timeString += ": ";
  192. while (*nextLine) {
  193. char *nextLine = strchr(str, '\n');
  194. if (!nextLine)
  195. break;
  196. if (nextLine != str && nextLine[-1] == '\r') {
  197. nextLine[-1] = 0;
  198. } else {
  199. nextLine[0] = 0;
  200. }
  201. LogString(logFile, timeString.c_str(), str);
  202. nextLine++;
  203. str = nextLine;
  204. }
  205. LogString(logFile, timeString.c_str(), str);
  206. }
  207. #define MAX_REPEATED_LINES 30
  208. #define MAX_CHAR_VARIATION (255 * 3)
  209. static inline int sum_chars(const char *str)
  210. {
  211. int val = 0;
  212. for (; *str != 0; str++)
  213. val += *str;
  214. return val;
  215. }
  216. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  217. const char *output_str)
  218. {
  219. static mutex log_mutex;
  220. static const char *last_msg_ptr = nullptr;
  221. static int last_char_sum = 0;
  222. static char cmp_str[4096];
  223. static int rep_count = 0;
  224. int new_sum = sum_chars(output_str);
  225. lock_guard<mutex> guard(log_mutex);
  226. if (unfiltered_log) {
  227. return false;
  228. }
  229. if (last_msg_ptr == msg) {
  230. int diff = std::abs(new_sum - last_char_sum);
  231. if (diff < MAX_CHAR_VARIATION) {
  232. return (rep_count++ >= MAX_REPEATED_LINES);
  233. }
  234. }
  235. if (rep_count > MAX_REPEATED_LINES) {
  236. logFile << CurrentTimeString() <<
  237. ": Last log entry repeated for " <<
  238. to_string(rep_count - MAX_REPEATED_LINES) <<
  239. " more lines" << endl;
  240. }
  241. last_msg_ptr = msg;
  242. strcpy(cmp_str, output_str);
  243. last_char_sum = new_sum;
  244. rep_count = 0;
  245. return false;
  246. }
  247. static void do_log(int log_level, const char *msg, va_list args, void *param)
  248. {
  249. fstream &logFile = *static_cast<fstream*>(param);
  250. char str[4096];
  251. #ifndef _WIN32
  252. va_list args2;
  253. va_copy(args2, args);
  254. #endif
  255. vsnprintf(str, 4095, msg, args);
  256. #ifdef _WIN32
  257. OutputDebugStringA(str);
  258. OutputDebugStringA("\n");
  259. #else
  260. def_log_handler(log_level, msg, args2, nullptr);
  261. #endif
  262. if (too_many_repeated_entries(logFile, msg, str))
  263. return;
  264. if (log_level <= LOG_INFO || log_verbose)
  265. LogStringChunk(logFile, str);
  266. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  267. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  268. __debugbreak();
  269. #endif
  270. }
  271. #define DEFAULT_LANG "en-US"
  272. bool OBSApp::InitGlobalConfigDefaults()
  273. {
  274. config_set_default_string(globalConfig, "General", "Language",
  275. DEFAULT_LANG);
  276. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  277. config_set_default_string(globalConfig, "General", "ProcessPriority",
  278. "Normal");
  279. #if _WIN32
  280. config_set_default_string(globalConfig, "Video", "Renderer",
  281. "Direct3D 11");
  282. #else
  283. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  284. #endif
  285. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  286. true);
  287. config_set_default_bool(globalConfig, "BasicWindow",
  288. "PreviewProgramMode", false);
  289. config_set_default_bool(globalConfig, "BasicWindow",
  290. "SceneDuplicationMode", true);
  291. config_set_default_bool(globalConfig, "BasicWindow",
  292. "SwapScenesMode", true);
  293. config_set_default_bool(globalConfig, "BasicWindow",
  294. "SnappingEnabled", true);
  295. config_set_default_bool(globalConfig, "BasicWindow",
  296. "ScreenSnapping", true);
  297. config_set_default_bool(globalConfig, "BasicWindow",
  298. "SourceSnapping", true);
  299. config_set_default_bool(globalConfig, "BasicWindow",
  300. "CenterSnapping", false);
  301. config_set_default_double(globalConfig, "BasicWindow",
  302. "SnapDistance", 10.0);
  303. config_set_default_bool(globalConfig, "BasicWindow",
  304. "RecordWhenStreaming", false);
  305. config_set_default_bool(globalConfig, "BasicWindow",
  306. "KeepRecordingWhenStreamStops", false);
  307. config_set_default_bool(globalConfig, "BasicWindow",
  308. "SysTrayEnabled", true);
  309. config_set_default_bool(globalConfig, "BasicWindow",
  310. "SysTrayWhenStarted", false);
  311. config_set_default_bool(globalConfig, "BasicWindow",
  312. "ShowTransitions", true);
  313. config_set_default_bool(globalConfig, "BasicWindow",
  314. "ShowListboxToolbars", true);
  315. config_set_default_bool(globalConfig, "BasicWindow",
  316. "ShowStatusBar", true);
  317. #ifdef __APPLE__
  318. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  319. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  320. true);
  321. #endif
  322. return true;
  323. }
  324. static bool do_mkdir(const char *path)
  325. {
  326. if (os_mkdirs(path) == MKDIR_ERROR) {
  327. OBSErrorBox(NULL, "Failed to create directory %s", path);
  328. return false;
  329. }
  330. return true;
  331. }
  332. static bool MakeUserDirs()
  333. {
  334. char path[512];
  335. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  336. return false;
  337. if (!do_mkdir(path))
  338. return false;
  339. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  340. return false;
  341. if (!do_mkdir(path))
  342. return false;
  343. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  344. return false;
  345. if (!do_mkdir(path))
  346. return false;
  347. #ifdef _WIN32
  348. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  349. return false;
  350. if (!do_mkdir(path))
  351. return false;
  352. #endif
  353. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  354. return false;
  355. if (!do_mkdir(path))
  356. return false;
  357. return true;
  358. }
  359. static bool MakeUserProfileDirs()
  360. {
  361. char path[512];
  362. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  363. return false;
  364. if (!do_mkdir(path))
  365. return false;
  366. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  367. return false;
  368. if (!do_mkdir(path))
  369. return false;
  370. return true;
  371. }
  372. static string GetProfileDirFromName(const char *name)
  373. {
  374. string outputPath;
  375. os_glob_t *glob;
  376. char path[512];
  377. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  378. return outputPath;
  379. strcat(path, "/*");
  380. if (os_glob(path, 0, &glob) != 0)
  381. return outputPath;
  382. for (size_t i = 0; i < glob->gl_pathc; i++) {
  383. struct os_globent ent = glob->gl_pathv[i];
  384. if (!ent.directory)
  385. continue;
  386. strcpy(path, ent.path);
  387. strcat(path, "/basic.ini");
  388. ConfigFile config;
  389. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  390. continue;
  391. const char *curName = config_get_string(config, "General",
  392. "Name");
  393. if (astrcmpi(curName, name) == 0) {
  394. outputPath = ent.path;
  395. break;
  396. }
  397. }
  398. os_globfree(glob);
  399. if (!outputPath.empty()) {
  400. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  401. const char *start = strrchr(outputPath.c_str(), '/');
  402. if (start)
  403. outputPath.erase(0, start - outputPath.c_str() + 1);
  404. }
  405. return outputPath;
  406. }
  407. static string GetSceneCollectionFileFromName(const char *name)
  408. {
  409. string outputPath;
  410. os_glob_t *glob;
  411. char path[512];
  412. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  413. return outputPath;
  414. strcat(path, "/*.json");
  415. if (os_glob(path, 0, &glob) != 0)
  416. return outputPath;
  417. for (size_t i = 0; i < glob->gl_pathc; i++) {
  418. struct os_globent ent = glob->gl_pathv[i];
  419. if (ent.directory)
  420. continue;
  421. obs_data_t *data =
  422. obs_data_create_from_json_file_safe(ent.path, "bak");
  423. const char *curName = obs_data_get_string(data, "name");
  424. if (astrcmpi(name, curName) == 0) {
  425. outputPath = ent.path;
  426. obs_data_release(data);
  427. break;
  428. }
  429. obs_data_release(data);
  430. }
  431. os_globfree(glob);
  432. if (!outputPath.empty()) {
  433. outputPath.resize(outputPath.size() - 5);
  434. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  435. const char *start = strrchr(outputPath.c_str(), '/');
  436. if (start)
  437. outputPath.erase(0, start - outputPath.c_str() + 1);
  438. }
  439. return outputPath;
  440. }
  441. bool OBSApp::InitGlobalConfig()
  442. {
  443. char path[512];
  444. int len = GetConfigPath(path, sizeof(path),
  445. "obs-studio/global.ini");
  446. if (len <= 0) {
  447. return false;
  448. }
  449. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  450. if (errorcode != CONFIG_SUCCESS) {
  451. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  452. return false;
  453. }
  454. if (!opt_starting_collection.empty()) {
  455. string path = GetSceneCollectionFileFromName(
  456. opt_starting_collection.c_str());
  457. if (!path.empty()) {
  458. config_set_string(globalConfig,
  459. "Basic", "SceneCollection",
  460. opt_starting_collection.c_str());
  461. config_set_string(globalConfig,
  462. "Basic", "SceneCollectionFile",
  463. path.c_str());
  464. }
  465. }
  466. if (!opt_starting_profile.empty()) {
  467. string path = GetProfileDirFromName(
  468. opt_starting_profile.c_str());
  469. if (!path.empty()) {
  470. config_set_string(globalConfig, "Basic", "Profile",
  471. opt_starting_profile.c_str());
  472. config_set_string(globalConfig, "Basic", "ProfileDir",
  473. path.c_str());
  474. }
  475. }
  476. return InitGlobalConfigDefaults();
  477. }
  478. bool OBSApp::InitLocale()
  479. {
  480. ProfileScope("OBSApp::InitLocale");
  481. const char *lang = config_get_string(globalConfig, "General",
  482. "Language");
  483. locale = lang;
  484. string englishPath;
  485. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  486. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  487. return false;
  488. }
  489. textLookup = text_lookup_create(englishPath.c_str());
  490. if (!textLookup) {
  491. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  492. englishPath.c_str());
  493. return false;
  494. }
  495. bool userLocale = config_has_user_value(globalConfig, "General",
  496. "Language");
  497. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  498. if (userLocale && defaultLang)
  499. return true;
  500. if (!userLocale && defaultLang) {
  501. for (auto &locale_ : GetPreferredLocales()) {
  502. if (locale_ == lang)
  503. return true;
  504. stringstream file;
  505. file << "locale/" << locale_ << ".ini";
  506. string path;
  507. if (!GetDataFilePath(file.str().c_str(), path))
  508. continue;
  509. if (!text_lookup_add(textLookup, path.c_str()))
  510. continue;
  511. blog(LOG_INFO, "Using preferred locale '%s'",
  512. locale_.c_str());
  513. locale = locale_;
  514. return true;
  515. }
  516. return true;
  517. }
  518. stringstream file;
  519. file << "locale/" << lang << ".ini";
  520. string path;
  521. if (GetDataFilePath(file.str().c_str(), path)) {
  522. if (!text_lookup_add(textLookup, path.c_str()))
  523. blog(LOG_ERROR, "Failed to add locale file '%s'",
  524. path.c_str());
  525. } else {
  526. blog(LOG_ERROR, "Could not find locale file '%s'",
  527. file.str().c_str());
  528. }
  529. return true;
  530. }
  531. bool OBSApp::SetTheme(std::string name, std::string path)
  532. {
  533. theme = name;
  534. /* Check user dir first, then preinstalled themes. */
  535. if (path == "") {
  536. char userDir[512];
  537. name = "themes/" + name + ".qss";
  538. string temp = "obs-studio/" + name;
  539. int ret = GetConfigPath(userDir, sizeof(userDir),
  540. temp.c_str());
  541. if (ret > 0 && QFile::exists(userDir)) {
  542. path = string(userDir);
  543. } else if (!GetDataFilePath(name.c_str(), path)) {
  544. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  545. return false;
  546. }
  547. }
  548. QString mpath = QString("file:///") + path.c_str();
  549. setStyleSheet(mpath);
  550. return true;
  551. }
  552. bool OBSApp::InitTheme()
  553. {
  554. const char *themeName = config_get_string(globalConfig, "General",
  555. "Theme");
  556. if (!themeName)
  557. themeName = "Default";
  558. stringstream t;
  559. t << themeName;
  560. return SetTheme(t.str());
  561. }
  562. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  563. : QApplication(argc, argv),
  564. profilerNameStore(store)
  565. {
  566. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  567. }
  568. OBSApp::~OBSApp()
  569. {
  570. #ifdef __APPLE__
  571. bool vsyncDiabled = config_get_bool(globalConfig, "Video",
  572. "DisableOSXVSync");
  573. bool resetVSync = config_get_bool(globalConfig, "Video",
  574. "ResetOSXVSyncOnExit");
  575. if (vsyncDiabled && resetVSync)
  576. EnableOSXVSync(true);
  577. #endif
  578. os_inhibit_sleep_set_active(sleepInhibitor, false);
  579. os_inhibit_sleep_destroy(sleepInhibitor);
  580. }
  581. static void move_basic_to_profiles(void)
  582. {
  583. char path[512];
  584. char new_path[512];
  585. os_glob_t *glob;
  586. /* if not first time use */
  587. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  588. return;
  589. if (!os_file_exists(path))
  590. return;
  591. /* if the profiles directory doesn't already exist */
  592. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  593. return;
  594. if (os_file_exists(new_path))
  595. return;
  596. if (os_mkdir(new_path) == MKDIR_ERROR)
  597. return;
  598. strcat(new_path, "/");
  599. strcat(new_path, Str("Untitled"));
  600. if (os_mkdir(new_path) == MKDIR_ERROR)
  601. return;
  602. strcat(path, "/*.*");
  603. if (os_glob(path, 0, &glob) != 0)
  604. return;
  605. strcpy(path, new_path);
  606. for (size_t i = 0; i < glob->gl_pathc; i++) {
  607. struct os_globent ent = glob->gl_pathv[i];
  608. char *file;
  609. if (ent.directory)
  610. continue;
  611. file = strrchr(ent.path, '/');
  612. if (!file++)
  613. continue;
  614. if (astrcmpi(file, "scenes.json") == 0)
  615. continue;
  616. strcpy(new_path, path);
  617. strcat(new_path, "/");
  618. strcat(new_path, file);
  619. os_rename(ent.path, new_path);
  620. }
  621. os_globfree(glob);
  622. }
  623. static void move_basic_to_scene_collections(void)
  624. {
  625. char path[512];
  626. char new_path[512];
  627. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  628. return;
  629. if (!os_file_exists(path))
  630. return;
  631. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  632. return;
  633. if (os_file_exists(new_path))
  634. return;
  635. if (os_mkdir(new_path) == MKDIR_ERROR)
  636. return;
  637. strcat(path, "/scenes.json");
  638. strcat(new_path, "/");
  639. strcat(new_path, Str("Untitled"));
  640. strcat(new_path, ".json");
  641. os_rename(path, new_path);
  642. }
  643. void OBSApp::AppInit()
  644. {
  645. ProfileScope("OBSApp::AppInit");
  646. if (!InitApplicationBundle())
  647. throw "Failed to initialize application bundle";
  648. if (!MakeUserDirs())
  649. throw "Failed to create required user directories";
  650. if (!InitGlobalConfig())
  651. throw "Failed to initialize global config";
  652. if (!InitLocale())
  653. throw "Failed to load locale";
  654. if (!InitTheme())
  655. throw "Failed to load theme";
  656. config_set_default_string(globalConfig, "Basic", "Profile",
  657. Str("Untitled"));
  658. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  659. Str("Untitled"));
  660. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  661. Str("Untitled"));
  662. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  663. Str("Untitled"));
  664. #ifdef __APPLE__
  665. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  666. EnableOSXVSync(false);
  667. #endif
  668. move_basic_to_profiles();
  669. move_basic_to_scene_collections();
  670. if (!MakeUserProfileDirs())
  671. throw "Failed to create profile directories";
  672. }
  673. const char *OBSApp::GetRenderModule() const
  674. {
  675. const char *renderer = config_get_string(globalConfig, "Video",
  676. "Renderer");
  677. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  678. DL_D3D11 : DL_OPENGL;
  679. }
  680. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  681. {
  682. char path[512];
  683. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  684. return false;
  685. return obs_startup(locale, path, store);
  686. }
  687. bool OBSApp::OBSInit()
  688. {
  689. ProfileScope("OBSApp::OBSInit");
  690. bool licenseAccepted = config_get_bool(globalConfig, "General",
  691. "LicenseAccepted");
  692. OBSLicenseAgreement agreement(nullptr);
  693. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  694. if (!licenseAccepted) {
  695. config_set_bool(globalConfig, "General",
  696. "LicenseAccepted", true);
  697. config_save(globalConfig);
  698. }
  699. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  700. return false;
  701. blog(LOG_INFO, "Portable mode: %s",
  702. portable_mode ? "true" : "false");
  703. mainWindow = new OBSBasic();
  704. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  705. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  706. mainWindow->OBSInit();
  707. connect(this, &QGuiApplication::applicationStateChanged,
  708. [](Qt::ApplicationState state)
  709. {
  710. obs_hotkey_enable_background_press(
  711. state != Qt::ApplicationActive);
  712. });
  713. obs_hotkey_enable_background_press(
  714. applicationState() != Qt::ApplicationActive);
  715. return true;
  716. } else {
  717. return false;
  718. }
  719. }
  720. string OBSApp::GetVersionString() const
  721. {
  722. stringstream ver;
  723. #ifdef HAVE_OBSCONFIG_H
  724. ver << OBS_VERSION;
  725. #else
  726. ver << LIBOBS_API_MAJOR_VER << "." <<
  727. LIBOBS_API_MINOR_VER << "." <<
  728. LIBOBS_API_PATCH_VER;
  729. #endif
  730. ver << " (";
  731. #ifdef _WIN32
  732. if (sizeof(void*) == 8)
  733. ver << "64bit, ";
  734. ver << "windows)";
  735. #elif __APPLE__
  736. ver << "mac)";
  737. #elif __FreeBSD__
  738. ver << "freebsd)";
  739. #else /* assume linux for the time being */
  740. ver << "linux)";
  741. #endif
  742. return ver.str();
  743. }
  744. bool OBSApp::IsPortableMode()
  745. {
  746. return portable_mode;
  747. }
  748. #ifdef __APPLE__
  749. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  750. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  751. #elif _WIN32
  752. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  753. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  754. #else
  755. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  756. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  757. #endif
  758. const char *OBSApp::InputAudioSource() const
  759. {
  760. return INPUT_AUDIO_SOURCE;
  761. }
  762. const char *OBSApp::OutputAudioSource() const
  763. {
  764. return OUTPUT_AUDIO_SOURCE;
  765. }
  766. const char *OBSApp::GetLastLog() const
  767. {
  768. return lastLogFile.c_str();
  769. }
  770. const char *OBSApp::GetCurrentLog() const
  771. {
  772. return currentLogFile.c_str();
  773. }
  774. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  775. {
  776. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  777. if (cb(lookupVal, out))
  778. return true;
  779. }
  780. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  781. }
  782. QString OBSTranslator::translate(const char *context, const char *sourceText,
  783. const char *disambiguation, int n) const
  784. {
  785. const char *out = nullptr;
  786. if (!App()->TranslateString(sourceText, &out))
  787. return QString(sourceText);
  788. UNUSED_PARAMETER(context);
  789. UNUSED_PARAMETER(disambiguation);
  790. UNUSED_PARAMETER(n);
  791. return QT_UTF8(out);
  792. }
  793. static bool get_token(lexer *lex, string &str, base_token_type type)
  794. {
  795. base_token token;
  796. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  797. return false;
  798. if (token.type != type)
  799. return false;
  800. str.assign(token.text.array, token.text.len);
  801. return true;
  802. }
  803. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  804. {
  805. base_token token;
  806. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  807. return false;
  808. if (token.type != type)
  809. return false;
  810. return strref_cmp(&token.text, str) == 0;
  811. }
  812. static uint64_t convert_log_name(const char *name)
  813. {
  814. BaseLexer lex;
  815. string year, month, day, hour, minute, second;
  816. lexer_start(lex, name);
  817. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  818. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  819. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  820. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  821. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  822. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  823. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  824. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  825. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  826. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  827. stringstream timestring;
  828. timestring << year << month << day << hour << minute << second;
  829. return std::stoull(timestring.str());
  830. }
  831. static void delete_oldest_file(const char *location)
  832. {
  833. BPtr<char> logDir(GetConfigPathPtr(location));
  834. string oldestLog;
  835. uint64_t oldest_ts = (uint64_t)-1;
  836. struct os_dirent *entry;
  837. unsigned int maxLogs = (unsigned int)config_get_uint(
  838. App()->GlobalConfig(), "General", "MaxLogs");
  839. os_dir_t *dir = os_opendir(logDir);
  840. if (dir) {
  841. unsigned int count = 0;
  842. while ((entry = os_readdir(dir)) != NULL) {
  843. if (entry->directory || *entry->d_name == '.')
  844. continue;
  845. uint64_t ts = convert_log_name(entry->d_name);
  846. if (ts) {
  847. if (ts < oldest_ts) {
  848. oldestLog = entry->d_name;
  849. oldest_ts = ts;
  850. }
  851. count++;
  852. }
  853. }
  854. os_closedir(dir);
  855. if (count > maxLogs) {
  856. stringstream delPath;
  857. delPath << logDir << "/" << oldestLog;
  858. os_unlink(delPath.str().c_str());
  859. }
  860. }
  861. }
  862. static void get_last_log(void)
  863. {
  864. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  865. struct os_dirent *entry;
  866. os_dir_t *dir = os_opendir(logDir);
  867. uint64_t highest_ts = 0;
  868. if (dir) {
  869. while ((entry = os_readdir(dir)) != NULL) {
  870. if (entry->directory || *entry->d_name == '.')
  871. continue;
  872. uint64_t ts = convert_log_name(entry->d_name);
  873. if (ts > highest_ts) {
  874. lastLogFile = entry->d_name;
  875. highest_ts = ts;
  876. }
  877. }
  878. os_closedir(dir);
  879. }
  880. }
  881. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  882. {
  883. time_t now = time(0);
  884. char file[256] = {};
  885. struct tm *cur_time;
  886. cur_time = localtime(&now);
  887. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  888. cur_time->tm_year+1900,
  889. cur_time->tm_mon+1,
  890. cur_time->tm_mday,
  891. noSpace ? '_' : ' ',
  892. cur_time->tm_hour,
  893. cur_time->tm_min,
  894. cur_time->tm_sec,
  895. extension);
  896. return string(file);
  897. }
  898. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  899. const char *format)
  900. {
  901. time_t now = time(0);
  902. struct tm *cur_time;
  903. cur_time = localtime(&now);
  904. const size_t spec_count = 23;
  905. const char *spec[][2] = {
  906. {"%CCYY", "%Y"},
  907. {"%YY", "%y"},
  908. {"%MM", "%m"},
  909. {"%DD", "%d"},
  910. {"%hh", "%H"},
  911. {"%mm", "%M"},
  912. {"%ss", "%S"},
  913. {"%%", "%%"},
  914. {"%a", ""},
  915. {"%A", ""},
  916. {"%b", ""},
  917. {"%B", ""},
  918. {"%d", ""},
  919. {"%H", ""},
  920. {"%I", ""},
  921. {"%m", ""},
  922. {"%M", ""},
  923. {"%p", ""},
  924. {"%S", ""},
  925. {"%y", ""},
  926. {"%Y", ""},
  927. {"%z", ""},
  928. {"%Z", ""},
  929. };
  930. char convert[128] = {};
  931. string sf = format;
  932. string c;
  933. size_t pos = 0, len;
  934. while (pos < sf.length()) {
  935. len = 0;
  936. for (size_t i = 0; i < spec_count && len == 0; i++) {
  937. if (sf.find(spec[i][0], pos) == pos) {
  938. if (strlen(spec[i][1]))
  939. strftime(convert, sizeof(convert),
  940. spec[i][1], cur_time);
  941. else
  942. strftime(convert, sizeof(convert),
  943. spec[i][0], cur_time);
  944. len = strlen(spec[i][0]);
  945. c = convert;
  946. if (c.length() && c.find_first_not_of(' ') !=
  947. std::string::npos)
  948. sf.replace(pos, len, convert);
  949. }
  950. }
  951. if (len)
  952. pos += strlen(convert);
  953. else if (!len && sf.at(pos) == '%')
  954. sf.erase(pos,1);
  955. else
  956. pos++;
  957. }
  958. if (noSpace)
  959. replace(sf.begin(), sf.end(), ' ', '_');
  960. sf += '.';
  961. sf += extension;
  962. return (sf.length() < 256) ? sf : sf.substr(0, 255);
  963. }
  964. vector<pair<string, string>> GetLocaleNames()
  965. {
  966. string path;
  967. if (!GetDataFilePath("locale.ini", path))
  968. throw "Could not find locale.ini path";
  969. ConfigFile ini;
  970. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  971. throw "Could not open locale.ini";
  972. size_t sections = config_num_sections(ini);
  973. vector<pair<string, string>> names;
  974. names.reserve(sections);
  975. for (size_t i = 0; i < sections; i++) {
  976. const char *tag = config_get_section(ini, i);
  977. const char *name = config_get_string(ini, tag, "Name");
  978. names.emplace_back(tag, name);
  979. }
  980. return names;
  981. }
  982. static void create_log_file(fstream &logFile)
  983. {
  984. stringstream dst;
  985. get_last_log();
  986. currentLogFile = GenerateTimeDateFilename("txt");
  987. dst << "obs-studio/logs/" << currentLogFile.c_str();
  988. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  989. logFile.open(path,
  990. ios_base::in | ios_base::out | ios_base::trunc);
  991. if (logFile.is_open()) {
  992. delete_oldest_file("obs-studio/logs");
  993. base_set_log_handler(do_log, &logFile);
  994. } else {
  995. blog(LOG_ERROR, "Failed to open log file");
  996. }
  997. }
  998. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  999. {
  1000. profiler_name_store_free(store);
  1001. };
  1002. using ProfilerNameStore =
  1003. std::unique_ptr<profiler_name_store_t,
  1004. decltype(ProfilerNameStoreRelease)>;
  1005. ProfilerNameStore CreateNameStore()
  1006. {
  1007. return ProfilerNameStore{profiler_name_store_create(),
  1008. ProfilerNameStoreRelease};
  1009. }
  1010. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  1011. {
  1012. profile_snapshot_free(snap);
  1013. };
  1014. using ProfilerSnapshot =
  1015. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1016. ProfilerSnapshot GetSnapshot()
  1017. {
  1018. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1019. }
  1020. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1021. {
  1022. if (currentLogFile.empty())
  1023. return;
  1024. auto pos = currentLogFile.rfind('.');
  1025. if (pos == currentLogFile.npos)
  1026. return;
  1027. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1028. ostringstream dst;
  1029. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1030. dst.write(currentLogFile.c_str(), pos);
  1031. dst.write(LITERAL_SIZE(".csv.gz"));
  1032. #undef LITERAL_SIZE
  1033. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1034. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1035. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1036. static_cast<const char*>(path));
  1037. }
  1038. static auto ProfilerFree = [](void *)
  1039. {
  1040. profiler_stop();
  1041. auto snap = GetSnapshot();
  1042. profiler_print(snap.get());
  1043. profiler_print_time_between_calls(snap.get());
  1044. SaveProfilerData(snap);
  1045. profiler_free();
  1046. };
  1047. static const char *run_program_init = "run_program_init";
  1048. static int run_program(fstream &logFile, int argc, char *argv[])
  1049. {
  1050. int ret = -1;
  1051. auto profilerNameStore = CreateNameStore();
  1052. std::unique_ptr<void, decltype(ProfilerFree)>
  1053. prof_release(static_cast<void*>(&ProfilerFree),
  1054. ProfilerFree);
  1055. profiler_start();
  1056. profile_register_root(run_program_init, 0);
  1057. auto PrintInitProfile = [&]()
  1058. {
  1059. auto snap = GetSnapshot();
  1060. profiler_snapshot_filter_roots(snap.get(), [](void *data,
  1061. const char *name, bool *remove)
  1062. {
  1063. *remove = (*static_cast<const char**>(data)) != name;
  1064. return true;
  1065. }, static_cast<void*>(&run_program_init));
  1066. profiler_print(snap.get());
  1067. };
  1068. ScopeProfiler prof{run_program_init};
  1069. QCoreApplication::addLibraryPath(".");
  1070. OBSApp program(argc, argv, profilerNameStore.get());
  1071. try {
  1072. program.AppInit();
  1073. OBSTranslator translator;
  1074. create_log_file(logFile);
  1075. delete_oldest_file("obs-studio/profiler_data");
  1076. program.installTranslator(&translator);
  1077. if (!program.OBSInit())
  1078. return 0;
  1079. prof.Stop();
  1080. return program.exec();
  1081. } catch (const char *error) {
  1082. blog(LOG_ERROR, "%s", error);
  1083. OBSErrorBox(nullptr, "%s", error);
  1084. }
  1085. return ret;
  1086. }
  1087. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  1088. #ifdef _WIN32
  1089. #define CRASH_MESSAGE \
  1090. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1091. "to the clipboard? (Crash logs will still be saved to the " \
  1092. "%appdata%\\obs-studio\\crashes directory)"
  1093. static void main_crash_handler(const char *format, va_list args, void *param)
  1094. {
  1095. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1096. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1097. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1098. delete_oldest_file("obs-studio/crashes");
  1099. string name = "obs-studio/crashes/Crash ";
  1100. name += GenerateTimeDateFilename("txt");
  1101. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1102. fstream file;
  1103. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1104. ios_base::binary);
  1105. file << text;
  1106. file.close();
  1107. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1108. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1109. if (ret == IDYES) {
  1110. size_t len = strlen(text);
  1111. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1112. memcpy(GlobalLock(mem), text, len);
  1113. GlobalUnlock(mem);
  1114. OpenClipboard(0);
  1115. EmptyClipboard();
  1116. SetClipboardData(CF_TEXT, mem);
  1117. CloseClipboard();
  1118. }
  1119. exit(-1);
  1120. UNUSED_PARAMETER(param);
  1121. }
  1122. static void load_debug_privilege(void)
  1123. {
  1124. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1125. TOKEN_PRIVILEGES tp;
  1126. HANDLE token;
  1127. LUID val;
  1128. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1129. return;
  1130. }
  1131. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1132. tp.PrivilegeCount = 1;
  1133. tp.Privileges[0].Luid = val;
  1134. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1135. AdjustTokenPrivileges(token, false, &tp,
  1136. sizeof(tp), NULL, NULL);
  1137. }
  1138. CloseHandle(token);
  1139. }
  1140. #endif
  1141. #ifdef __APPLE__
  1142. #define BASE_PATH ".."
  1143. #else
  1144. #define BASE_PATH "../.."
  1145. #endif
  1146. #define CONFIG_PATH BASE_PATH "/config"
  1147. #ifndef OBS_UNIX_STRUCTURE
  1148. #define OBS_UNIX_STRUCTURE 0
  1149. #endif
  1150. int GetConfigPath(char *path, size_t size, const char *name)
  1151. {
  1152. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1153. if (name && *name) {
  1154. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1155. } else {
  1156. return snprintf(path, size, CONFIG_PATH);
  1157. }
  1158. } else {
  1159. return os_get_config_path(path, size, name);
  1160. }
  1161. }
  1162. char *GetConfigPathPtr(const char *name)
  1163. {
  1164. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1165. char path[512];
  1166. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1167. return bstrdup(path);
  1168. } else {
  1169. return NULL;
  1170. }
  1171. } else {
  1172. return os_get_config_path_ptr(name);
  1173. }
  1174. }
  1175. int GetProgramDataPath(char *path, size_t size, const char *name)
  1176. {
  1177. return os_get_program_data_path(path, size, name);
  1178. }
  1179. char *GetProgramDataPathPtr(const char *name)
  1180. {
  1181. return os_get_program_data_path_ptr(name);
  1182. }
  1183. bool GetFileSafeName(const char *name, std::string &file)
  1184. {
  1185. size_t base_len = strlen(name);
  1186. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1187. std::wstring wfile;
  1188. if (!len)
  1189. return false;
  1190. wfile.resize(len);
  1191. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1192. for (size_t i = wfile.size(); i > 0; i--) {
  1193. size_t im1 = i - 1;
  1194. if (iswspace(wfile[im1])) {
  1195. wfile[im1] = '_';
  1196. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1197. wfile.erase(im1, 1);
  1198. }
  1199. }
  1200. if (wfile.size() == 0)
  1201. wfile = L"characters_only";
  1202. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1203. if (!len)
  1204. return false;
  1205. file.resize(len);
  1206. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1207. return true;
  1208. }
  1209. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1210. {
  1211. size_t len = path.size();
  1212. if (extension) {
  1213. path += ".";
  1214. path += extension;
  1215. }
  1216. if (!os_file_exists(path.c_str()))
  1217. return true;
  1218. int index = 1;
  1219. do {
  1220. path.resize(len);
  1221. path += std::to_string(++index);
  1222. if (extension) {
  1223. path += ".";
  1224. path += extension;
  1225. }
  1226. } while (os_file_exists(path.c_str()));
  1227. return true;
  1228. }
  1229. bool WindowPositionValid(QRect rect)
  1230. {
  1231. for (QScreen* screen: QGuiApplication::screens()) {
  1232. if (screen->availableGeometry().intersects(rect))
  1233. return true;
  1234. }
  1235. return false;
  1236. }
  1237. static inline bool arg_is(const char *arg,
  1238. const char *long_form, const char *short_form)
  1239. {
  1240. return (long_form && strcmp(arg, long_form) == 0) ||
  1241. (short_form && strcmp(arg, short_form) == 0);
  1242. }
  1243. #if !defined(_WIN32) && !defined(__APPLE__)
  1244. #define IS_UNIX 1
  1245. #endif
  1246. /* if using XDG and was previously using an older build of OBS, move config
  1247. * files to XDG directory */
  1248. #if defined(USE_XDG) && defined(IS_UNIX)
  1249. static void move_to_xdg(void)
  1250. {
  1251. char old_path[512];
  1252. char new_path[512];
  1253. char *home = getenv("HOME");
  1254. if (!home)
  1255. return;
  1256. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1257. return;
  1258. /* make base xdg path if it doesn't already exist */
  1259. if (GetConfigPath(new_path, 512, "") <= 0)
  1260. return;
  1261. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1262. return;
  1263. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1264. return;
  1265. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1266. rename(old_path, new_path);
  1267. }
  1268. }
  1269. #endif
  1270. static bool update_ffmpeg_output(ConfigFile &config)
  1271. {
  1272. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1273. return false;
  1274. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1275. if (!url)
  1276. return false;
  1277. bool isActualURL = strstr(url, "://") != nullptr;
  1278. if (isActualURL)
  1279. return false;
  1280. string urlStr = url;
  1281. string extension;
  1282. for (size_t i = urlStr.length(); i > 0; i--) {
  1283. size_t idx = i - 1;
  1284. if (urlStr[idx] == '.') {
  1285. extension = &urlStr[i];
  1286. }
  1287. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1288. urlStr[idx] = 0;
  1289. break;
  1290. }
  1291. }
  1292. if (urlStr.empty() || extension.empty())
  1293. return false;
  1294. config_remove_value(config, "AdvOut", "FFURL");
  1295. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1296. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1297. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1298. return true;
  1299. }
  1300. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1301. {
  1302. bool changed = false;
  1303. if (config_has_user_value(config, sec, "Reconnect")) {
  1304. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1305. config_set_bool(config, "Output", "Reconnect", reconnect);
  1306. changed = true;
  1307. }
  1308. if (config_has_user_value(config, sec, "RetryDelay")) {
  1309. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1310. config_set_uint(config, "Output", "RetryDelay", delay);
  1311. changed = true;
  1312. }
  1313. if (config_has_user_value(config, sec, "MaxRetries")) {
  1314. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1315. config_set_uint(config, "Output", "MaxRetries", retries);
  1316. changed = true;
  1317. }
  1318. return changed;
  1319. }
  1320. static bool update_reconnect(ConfigFile &config)
  1321. {
  1322. if (!config_has_user_value(config, "Output", "Mode"))
  1323. return false;
  1324. const char *mode = config_get_string(config, "Output", "Mode");
  1325. if (!mode)
  1326. return false;
  1327. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1328. "AdvOut" : "SimpleOutput";
  1329. if (move_reconnect_settings(config, section)) {
  1330. config_remove_value(config, "SimpleOutput", "Reconnect");
  1331. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1332. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1333. config_remove_value(config, "AdvOut", "Reconnect");
  1334. config_remove_value(config, "AdvOut", "RetryDelay");
  1335. config_remove_value(config, "AdvOut", "MaxRetries");
  1336. return true;
  1337. }
  1338. return false;
  1339. }
  1340. static void convert_x264_settings(obs_data_t *data)
  1341. {
  1342. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1343. if (use_bufsize) {
  1344. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1345. if (buffer_size == 0)
  1346. obs_data_set_string(data, "rate_control", "CRF");
  1347. }
  1348. }
  1349. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1350. {
  1351. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1352. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1353. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1354. bool modified = false;
  1355. bool cbr = true;
  1356. if (cbr_item) {
  1357. cbr = obs_data_item_get_bool(cbr_item);
  1358. obs_data_item_unset_user_value(cbr_item);
  1359. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1360. modified = true;
  1361. }
  1362. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1363. if (!cbr_item)
  1364. obs_data_set_string(data, "rate_control", "CBR");
  1365. else if (!cbr)
  1366. convert_x264_settings(data);
  1367. modified = true;
  1368. }
  1369. if (modified)
  1370. obs_data_save_json_safe(data, file, "tmp", "bak");
  1371. obs_data_item_release(&rc_item);
  1372. obs_data_item_release(&cbr_item);
  1373. obs_data_release(data);
  1374. }
  1375. static void upgrade_settings(void)
  1376. {
  1377. char path[512];
  1378. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1379. if (pathlen <= 0)
  1380. return;
  1381. if (!os_file_exists(path))
  1382. return;
  1383. os_dir_t *dir = os_opendir(path);
  1384. if (!dir)
  1385. return;
  1386. struct os_dirent *ent = os_readdir(dir);
  1387. while (ent) {
  1388. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1389. strcmp(ent->d_name, "..") != 0) {
  1390. strcat(path, "/");
  1391. strcat(path, ent->d_name);
  1392. strcat(path, "/basic.ini");
  1393. ConfigFile config;
  1394. int ret;
  1395. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1396. if (ret == CONFIG_SUCCESS) {
  1397. if (update_ffmpeg_output(config) ||
  1398. update_reconnect(config)) {
  1399. config_save_safe(config, "tmp",
  1400. nullptr);
  1401. }
  1402. }
  1403. if (config) {
  1404. const char *sEnc = config_get_string(config,
  1405. "AdvOut", "Encoder");
  1406. const char *rEnc = config_get_string(config,
  1407. "AdvOut", "RecEncoder");
  1408. /* replace "cbr" option with "rate_control" for
  1409. * each profile's encoder data */
  1410. path[pathlen] = 0;
  1411. strcat(path, "/");
  1412. strcat(path, ent->d_name);
  1413. strcat(path, "/recordEncoder.json");
  1414. convert_14_2_encoder_setting(rEnc, path);
  1415. path[pathlen] = 0;
  1416. strcat(path, "/");
  1417. strcat(path, ent->d_name);
  1418. strcat(path, "/streamEncoder.json");
  1419. convert_14_2_encoder_setting(sEnc, path);
  1420. }
  1421. path[pathlen] = 0;
  1422. }
  1423. ent = os_readdir(dir);
  1424. }
  1425. os_closedir(dir);
  1426. }
  1427. int main(int argc, char *argv[])
  1428. {
  1429. #ifndef _WIN32
  1430. signal(SIGPIPE, SIG_IGN);
  1431. #endif
  1432. #ifdef _WIN32
  1433. load_debug_privilege();
  1434. base_set_crash_handler(main_crash_handler, nullptr);
  1435. #endif
  1436. base_get_log_handler(&def_log_handler, nullptr);
  1437. #if defined(USE_XDG) && defined(IS_UNIX)
  1438. move_to_xdg();
  1439. #endif
  1440. for (int i = 1; i < argc; i++) {
  1441. if (arg_is(argv[i], "--portable", "-p")) {
  1442. portable_mode = true;
  1443. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1444. log_verbose = true;
  1445. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1446. unfiltered_log = true;
  1447. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1448. opt_start_streaming = true;
  1449. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1450. opt_start_recording = true;
  1451. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1452. if (++i < argc) opt_starting_collection = argv[i];
  1453. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1454. if (++i < argc) opt_starting_profile = argv[i];
  1455. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1456. if (++i < argc) opt_starting_scene = argv[i];
  1457. }
  1458. }
  1459. #if !OBS_UNIX_STRUCTURE
  1460. if (!portable_mode) {
  1461. portable_mode =
  1462. os_file_exists(BASE_PATH "/portable_mode") ||
  1463. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1464. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1465. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1466. }
  1467. #endif
  1468. upgrade_settings();
  1469. fstream logFile;
  1470. curl_global_init(CURL_GLOBAL_ALL);
  1471. int ret = run_program(logFile, argc, argv);
  1472. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1473. base_set_log_handler(nullptr, nullptr);
  1474. return ret;
  1475. }