obs-app.cpp 42 KB

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