obs-app.cpp 43 KB

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