obs-app.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335
  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.hpp>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <util/cf-parser.h>
  27. #include <obs-config.h>
  28. #include <obs.hpp>
  29. #include <QGuiApplication>
  30. #include <QProxyStyle>
  31. #include <QScreen>
  32. #include "qt-wrappers.hpp"
  33. #include "obs-app.hpp"
  34. #include "window-basic-main.hpp"
  35. #include "window-basic-settings.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 string lastCrashLogFile;
  51. bool portable_mode = false;
  52. static bool multi = false;
  53. static bool log_verbose = false;
  54. static bool unfiltered_log = false;
  55. bool opt_start_streaming = false;
  56. bool opt_start_recording = false;
  57. bool opt_studio_mode = false;
  58. bool opt_start_replaybuffer = false;
  59. bool opt_minimize_tray = false;
  60. bool opt_allow_opengl = false;
  61. bool opt_always_on_top = false;
  62. string opt_starting_collection;
  63. string opt_starting_profile;
  64. string opt_starting_scene;
  65. bool remuxAfterRecord = false;
  66. string remuxFilename;
  67. // GPU hint exports for AMD/NVIDIA laptops
  68. #ifdef _MSC_VER
  69. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  70. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  71. #endif
  72. QObject *CreateShortcutFilter()
  73. {
  74. return new OBSEventFilter([](QObject *obj, QEvent *event)
  75. {
  76. auto mouse_event = [](QMouseEvent &event)
  77. {
  78. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  79. bool pressed = event.type() == QEvent::MouseButtonPress;
  80. switch (event.button()) {
  81. case Qt::NoButton:
  82. case Qt::LeftButton:
  83. case Qt::RightButton:
  84. case Qt::AllButtons:
  85. case Qt::MouseButtonMask:
  86. return false;
  87. case Qt::MidButton:
  88. hotkey.key = OBS_KEY_MOUSE3;
  89. break;
  90. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  91. hotkey.key = OBS_KEY_MOUSE ## j; break;
  92. MAP_BUTTON( 1, 4);
  93. MAP_BUTTON( 2, 5);
  94. MAP_BUTTON( 3, 6);
  95. MAP_BUTTON( 4, 7);
  96. MAP_BUTTON( 5, 8);
  97. MAP_BUTTON( 6, 9);
  98. MAP_BUTTON( 7, 10);
  99. MAP_BUTTON( 8, 11);
  100. MAP_BUTTON( 9, 12);
  101. MAP_BUTTON(10, 13);
  102. MAP_BUTTON(11, 14);
  103. MAP_BUTTON(12, 15);
  104. MAP_BUTTON(13, 16);
  105. MAP_BUTTON(14, 17);
  106. MAP_BUTTON(15, 18);
  107. MAP_BUTTON(16, 19);
  108. MAP_BUTTON(17, 20);
  109. MAP_BUTTON(18, 21);
  110. MAP_BUTTON(19, 22);
  111. MAP_BUTTON(20, 23);
  112. MAP_BUTTON(21, 24);
  113. MAP_BUTTON(22, 25);
  114. MAP_BUTTON(23, 26);
  115. MAP_BUTTON(24, 27);
  116. #undef MAP_BUTTON
  117. }
  118. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  119. event.modifiers());
  120. obs_hotkey_inject_event(hotkey, pressed);
  121. return true;
  122. };
  123. auto key_event = [&](QKeyEvent *event)
  124. {
  125. QDialog *dialog = qobject_cast<QDialog*>(obj);
  126. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  127. bool pressed = event->type() == QEvent::KeyPress;
  128. switch (event->key()) {
  129. case Qt::Key_Shift:
  130. case Qt::Key_Control:
  131. case Qt::Key_Alt:
  132. case Qt::Key_Meta:
  133. break;
  134. #ifdef __APPLE__
  135. case Qt::Key_CapsLock:
  136. // kVK_CapsLock == 57
  137. hotkey.key = obs_key_from_virtual_key(57);
  138. pressed = true;
  139. break;
  140. #endif
  141. case Qt::Key_Enter:
  142. case Qt::Key_Escape:
  143. case Qt::Key_Return:
  144. if (dialog && pressed)
  145. return false;
  146. /* Falls through. */
  147. default:
  148. hotkey.key = obs_key_from_virtual_key(
  149. event->nativeVirtualKey());
  150. }
  151. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  152. event->modifiers());
  153. obs_hotkey_inject_event(hotkey, pressed);
  154. return true;
  155. };
  156. switch (event->type()) {
  157. case QEvent::MouseButtonPress:
  158. case QEvent::MouseButtonRelease:
  159. return mouse_event(*static_cast<QMouseEvent*>(event));
  160. /*case QEvent::MouseButtonDblClick:
  161. case QEvent::Wheel:*/
  162. case QEvent::KeyPress:
  163. case QEvent::KeyRelease:
  164. return key_event(static_cast<QKeyEvent*>(event));
  165. default:
  166. return false;
  167. }
  168. });
  169. }
  170. string CurrentTimeString()
  171. {
  172. using namespace std::chrono;
  173. struct tm tstruct;
  174. char buf[80];
  175. auto tp = system_clock::now();
  176. auto now = system_clock::to_time_t(tp);
  177. tstruct = *localtime(&now);
  178. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  179. if (ratio_less<system_clock::period, seconds::period>::value &&
  180. written && (sizeof(buf) - written) > 5) {
  181. auto tp_secs =
  182. time_point_cast<seconds>(tp);
  183. auto millis =
  184. duration_cast<milliseconds>(tp - tp_secs).count();
  185. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  186. static_cast<unsigned>(millis));
  187. }
  188. return buf;
  189. }
  190. string CurrentDateTimeString()
  191. {
  192. time_t now = time(0);
  193. struct tm tstruct;
  194. char buf[80];
  195. tstruct = *localtime(&now);
  196. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  197. return buf;
  198. }
  199. static inline void LogString(fstream &logFile, const char *timeString,
  200. char *str)
  201. {
  202. logFile << timeString << str << endl;
  203. }
  204. static inline void LogStringChunk(fstream &logFile, char *str)
  205. {
  206. char *nextLine = str;
  207. string timeString = CurrentTimeString();
  208. timeString += ": ";
  209. while (*nextLine) {
  210. char *nextLine = strchr(str, '\n');
  211. if (!nextLine)
  212. break;
  213. if (nextLine != str && nextLine[-1] == '\r') {
  214. nextLine[-1] = 0;
  215. } else {
  216. nextLine[0] = 0;
  217. }
  218. LogString(logFile, timeString.c_str(), str);
  219. nextLine++;
  220. str = nextLine;
  221. }
  222. LogString(logFile, timeString.c_str(), str);
  223. }
  224. #define MAX_REPEATED_LINES 30
  225. #define MAX_CHAR_VARIATION (255 * 3)
  226. static inline int sum_chars(const char *str)
  227. {
  228. int val = 0;
  229. for (; *str != 0; str++)
  230. val += *str;
  231. return val;
  232. }
  233. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  234. const char *output_str)
  235. {
  236. static mutex log_mutex;
  237. static const char *last_msg_ptr = nullptr;
  238. static int last_char_sum = 0;
  239. static char cmp_str[4096];
  240. static int rep_count = 0;
  241. int new_sum = sum_chars(output_str);
  242. lock_guard<mutex> guard(log_mutex);
  243. if (unfiltered_log) {
  244. return false;
  245. }
  246. if (last_msg_ptr == msg) {
  247. int diff = std::abs(new_sum - last_char_sum);
  248. if (diff < MAX_CHAR_VARIATION) {
  249. return (rep_count++ >= MAX_REPEATED_LINES);
  250. }
  251. }
  252. if (rep_count > MAX_REPEATED_LINES) {
  253. logFile << CurrentTimeString() <<
  254. ": Last log entry repeated for " <<
  255. to_string(rep_count - MAX_REPEATED_LINES) <<
  256. " more lines" << endl;
  257. }
  258. last_msg_ptr = msg;
  259. strcpy(cmp_str, output_str);
  260. last_char_sum = new_sum;
  261. rep_count = 0;
  262. return false;
  263. }
  264. static void do_log(int log_level, const char *msg, va_list args, void *param)
  265. {
  266. fstream &logFile = *static_cast<fstream*>(param);
  267. char str[4096];
  268. #ifndef _WIN32
  269. va_list args2;
  270. va_copy(args2, args);
  271. #endif
  272. vsnprintf(str, 4095, msg, args);
  273. #ifdef _WIN32
  274. if (IsDebuggerPresent()) {
  275. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  276. if (wNum > 1) {
  277. static wstring wide_buf;
  278. static mutex wide_mutex;
  279. lock_guard<mutex> lock(wide_mutex);
  280. wide_buf.reserve(wNum + 1);
  281. wide_buf.resize(wNum - 1);
  282. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  283. wNum);
  284. wide_buf.push_back('\n');
  285. OutputDebugStringW(wide_buf.c_str());
  286. }
  287. }
  288. #else
  289. def_log_handler(log_level, msg, args2, nullptr);
  290. va_end(args2);
  291. #endif
  292. if (log_level <= LOG_INFO || log_verbose) {
  293. if (too_many_repeated_entries(logFile, msg, str))
  294. return;
  295. LogStringChunk(logFile, str);
  296. }
  297. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  298. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  299. __debugbreak();
  300. #endif
  301. }
  302. #define DEFAULT_LANG "en-US"
  303. bool OBSApp::InitGlobalConfigDefaults()
  304. {
  305. config_set_default_string(globalConfig, "General", "Language",
  306. DEFAULT_LANG);
  307. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  308. config_set_default_int(globalConfig, "General", "InfoIncrement", -1);
  309. config_set_default_string(globalConfig, "General", "ProcessPriority",
  310. "Normal");
  311. config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
  312. true);
  313. #if _WIN32
  314. config_set_default_string(globalConfig, "Video", "Renderer",
  315. "Direct3D 11");
  316. #else
  317. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  318. #endif
  319. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  320. true);
  321. config_set_default_bool(globalConfig, "BasicWindow",
  322. "PreviewProgramMode", false);
  323. config_set_default_bool(globalConfig, "BasicWindow",
  324. "SceneDuplicationMode", true);
  325. config_set_default_bool(globalConfig, "BasicWindow",
  326. "SwapScenesMode", true);
  327. config_set_default_bool(globalConfig, "BasicWindow",
  328. "SnappingEnabled", true);
  329. config_set_default_bool(globalConfig, "BasicWindow",
  330. "ScreenSnapping", true);
  331. config_set_default_bool(globalConfig, "BasicWindow",
  332. "SourceSnapping", true);
  333. config_set_default_bool(globalConfig, "BasicWindow",
  334. "CenterSnapping", false);
  335. config_set_default_double(globalConfig, "BasicWindow",
  336. "SnapDistance", 10.0);
  337. config_set_default_bool(globalConfig, "BasicWindow",
  338. "RecordWhenStreaming", false);
  339. config_set_default_bool(globalConfig, "BasicWindow",
  340. "KeepRecordingWhenStreamStops", false);
  341. config_set_default_bool(globalConfig, "BasicWindow",
  342. "SysTrayEnabled", true);
  343. config_set_default_bool(globalConfig, "BasicWindow",
  344. "SysTrayWhenStarted", false);
  345. config_set_default_bool(globalConfig, "BasicWindow",
  346. "SaveProjectors", false);
  347. config_set_default_bool(globalConfig, "BasicWindow",
  348. "ShowTransitions", true);
  349. config_set_default_bool(globalConfig, "BasicWindow",
  350. "ShowListboxToolbars", true);
  351. config_set_default_bool(globalConfig, "BasicWindow",
  352. "ShowStatusBar", true);
  353. config_set_default_bool(globalConfig, "BasicWindow",
  354. "StudioModeLabels", true);
  355. if (!config_get_bool(globalConfig, "General", "Pre21Defaults")) {
  356. config_set_default_string(globalConfig, "General",
  357. "CurrentTheme", "Dark");
  358. }
  359. config_set_default_bool(globalConfig, "BasicWindow",
  360. "VerticalVolControl", false);
  361. config_set_default_bool(globalConfig, "BasicWindow",
  362. "MultiviewMouseSwitch", true);
  363. config_set_default_bool(globalConfig, "BasicWindow",
  364. "MultiviewDrawNames", true);
  365. config_set_default_bool(globalConfig, "BasicWindow",
  366. "MultiviewDrawAreas", true);
  367. #ifdef _WIN32
  368. uint32_t winver = GetWindowsVersion();
  369. config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
  370. true);
  371. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  372. winver > 0x601);
  373. #endif
  374. #ifdef __APPLE__
  375. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  376. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  377. true);
  378. #endif
  379. return true;
  380. }
  381. static bool do_mkdir(const char *path)
  382. {
  383. if (os_mkdirs(path) == MKDIR_ERROR) {
  384. OBSErrorBox(NULL, "Failed to create directory %s", path);
  385. return false;
  386. }
  387. return true;
  388. }
  389. static bool MakeUserDirs()
  390. {
  391. char path[512];
  392. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  393. return false;
  394. if (!do_mkdir(path))
  395. return false;
  396. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  397. return false;
  398. if (!do_mkdir(path))
  399. return false;
  400. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  401. return false;
  402. if (!do_mkdir(path))
  403. return false;
  404. #ifdef _WIN32
  405. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  406. return false;
  407. if (!do_mkdir(path))
  408. return false;
  409. if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  410. return false;
  411. if (!do_mkdir(path))
  412. return false;
  413. #endif
  414. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  415. return false;
  416. if (!do_mkdir(path))
  417. return false;
  418. return true;
  419. }
  420. static bool MakeUserProfileDirs()
  421. {
  422. char path[512];
  423. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  424. return false;
  425. if (!do_mkdir(path))
  426. return false;
  427. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  428. return false;
  429. if (!do_mkdir(path))
  430. return false;
  431. return true;
  432. }
  433. static string GetProfileDirFromName(const char *name)
  434. {
  435. string outputPath;
  436. os_glob_t *glob;
  437. char path[512];
  438. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  439. return outputPath;
  440. strcat(path, "/*");
  441. if (os_glob(path, 0, &glob) != 0)
  442. return outputPath;
  443. for (size_t i = 0; i < glob->gl_pathc; i++) {
  444. struct os_globent ent = glob->gl_pathv[i];
  445. if (!ent.directory)
  446. continue;
  447. strcpy(path, ent.path);
  448. strcat(path, "/basic.ini");
  449. ConfigFile config;
  450. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  451. continue;
  452. const char *curName = config_get_string(config, "General",
  453. "Name");
  454. if (astrcmpi(curName, name) == 0) {
  455. outputPath = ent.path;
  456. break;
  457. }
  458. }
  459. os_globfree(glob);
  460. if (!outputPath.empty()) {
  461. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  462. const char *start = strrchr(outputPath.c_str(), '/');
  463. if (start)
  464. outputPath.erase(0, start - outputPath.c_str() + 1);
  465. }
  466. return outputPath;
  467. }
  468. static string GetSceneCollectionFileFromName(const char *name)
  469. {
  470. string outputPath;
  471. os_glob_t *glob;
  472. char path[512];
  473. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  474. return outputPath;
  475. strcat(path, "/*.json");
  476. if (os_glob(path, 0, &glob) != 0)
  477. return outputPath;
  478. for (size_t i = 0; i < glob->gl_pathc; i++) {
  479. struct os_globent ent = glob->gl_pathv[i];
  480. if (ent.directory)
  481. continue;
  482. obs_data_t *data =
  483. obs_data_create_from_json_file_safe(ent.path, "bak");
  484. const char *curName = obs_data_get_string(data, "name");
  485. if (astrcmpi(name, curName) == 0) {
  486. outputPath = ent.path;
  487. obs_data_release(data);
  488. break;
  489. }
  490. obs_data_release(data);
  491. }
  492. os_globfree(glob);
  493. if (!outputPath.empty()) {
  494. outputPath.resize(outputPath.size() - 5);
  495. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  496. const char *start = strrchr(outputPath.c_str(), '/');
  497. if (start)
  498. outputPath.erase(0, start - outputPath.c_str() + 1);
  499. }
  500. return outputPath;
  501. }
  502. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  503. {
  504. if (!layout)
  505. return false;
  506. if (astrcmpi(layout, "horizontaltop") == 0) {
  507. config_set_int(globalConfig, "BasicWindow", "MultiviewLayout",
  508. static_cast<int>(
  509. MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  510. return true;
  511. }
  512. if (astrcmpi(layout, "horizontalbottom") == 0) {
  513. config_set_int(globalConfig, "BasicWindow", "MultiviewLayout",
  514. static_cast<int>(
  515. MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  516. return true;
  517. }
  518. if (astrcmpi(layout, "verticalleft") == 0) {
  519. config_set_int(globalConfig, "BasicWindow", "MultiviewLayout",
  520. static_cast<int>(
  521. MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  522. return true;
  523. }
  524. if (astrcmpi(layout, "verticalright") == 0) {
  525. config_set_int(globalConfig, "BasicWindow", "MultiviewLayout",
  526. static_cast<int>(
  527. MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  528. return true;
  529. }
  530. return false;
  531. }
  532. bool OBSApp::InitGlobalConfig()
  533. {
  534. char path[512];
  535. bool changed = false;
  536. int len = GetConfigPath(path, sizeof(path),
  537. "obs-studio/global.ini");
  538. if (len <= 0) {
  539. return false;
  540. }
  541. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  542. if (errorcode != CONFIG_SUCCESS) {
  543. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  544. return false;
  545. }
  546. if (!opt_starting_collection.empty()) {
  547. string path = GetSceneCollectionFileFromName(
  548. opt_starting_collection.c_str());
  549. if (!path.empty()) {
  550. config_set_string(globalConfig,
  551. "Basic", "SceneCollection",
  552. opt_starting_collection.c_str());
  553. config_set_string(globalConfig,
  554. "Basic", "SceneCollectionFile",
  555. path.c_str());
  556. changed = true;
  557. }
  558. }
  559. if (!opt_starting_profile.empty()) {
  560. string path = GetProfileDirFromName(
  561. opt_starting_profile.c_str());
  562. if (!path.empty()) {
  563. config_set_string(globalConfig, "Basic", "Profile",
  564. opt_starting_profile.c_str());
  565. config_set_string(globalConfig, "Basic", "ProfileDir",
  566. path.c_str());
  567. changed = true;
  568. }
  569. }
  570. if (!config_has_user_value(globalConfig, "General", "Pre19Defaults")) {
  571. uint32_t lastVersion = config_get_int(globalConfig, "General",
  572. "LastVersion");
  573. bool useOldDefaults = lastVersion &&
  574. lastVersion < MAKE_SEMANTIC_VERSION(19, 0, 0);
  575. config_set_bool(globalConfig, "General", "Pre19Defaults",
  576. useOldDefaults);
  577. changed = true;
  578. }
  579. if (!config_has_user_value(globalConfig, "General", "Pre21Defaults")) {
  580. uint32_t lastVersion = config_get_int(globalConfig, "General",
  581. "LastVersion");
  582. bool useOldDefaults = lastVersion &&
  583. lastVersion < MAKE_SEMANTIC_VERSION(21, 0, 0);
  584. config_set_bool(globalConfig, "General", "Pre21Defaults",
  585. useOldDefaults);
  586. changed = true;
  587. }
  588. if (!config_has_user_value(globalConfig, "General", "Pre23Defaults")) {
  589. uint32_t lastVersion = config_get_int(globalConfig, "General",
  590. "LastVersion");
  591. bool useOldDefaults = lastVersion &&
  592. lastVersion < MAKE_SEMANTIC_VERSION(23, 0, 0);
  593. config_set_bool(globalConfig, "General", "Pre23Defaults",
  594. useOldDefaults);
  595. changed = true;
  596. }
  597. if (config_has_user_value(globalConfig, "BasicWindow",
  598. "MultiviewLayout")) {
  599. const char *layout = config_get_string(globalConfig,
  600. "BasicWindow", "MultiviewLayout");
  601. changed |= UpdatePre22MultiviewLayout(layout);
  602. }
  603. if (changed)
  604. config_save_safe(globalConfig, "tmp", nullptr);
  605. return InitGlobalConfigDefaults();
  606. }
  607. bool OBSApp::InitLocale()
  608. {
  609. ProfileScope("OBSApp::InitLocale");
  610. const char *lang = config_get_string(globalConfig, "General",
  611. "Language");
  612. locale = lang;
  613. string englishPath;
  614. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  615. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  616. return false;
  617. }
  618. textLookup = text_lookup_create(englishPath.c_str());
  619. if (!textLookup) {
  620. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  621. englishPath.c_str());
  622. return false;
  623. }
  624. bool userLocale = config_has_user_value(globalConfig, "General",
  625. "Language");
  626. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  627. if (userLocale && defaultLang)
  628. return true;
  629. if (!userLocale && defaultLang) {
  630. for (auto &locale_ : GetPreferredLocales()) {
  631. if (locale_ == lang)
  632. return true;
  633. stringstream file;
  634. file << "locale/" << locale_ << ".ini";
  635. string path;
  636. if (!GetDataFilePath(file.str().c_str(), path))
  637. continue;
  638. if (!text_lookup_add(textLookup, path.c_str()))
  639. continue;
  640. blog(LOG_INFO, "Using preferred locale '%s'",
  641. locale_.c_str());
  642. locale = locale_;
  643. return true;
  644. }
  645. return true;
  646. }
  647. stringstream file;
  648. file << "locale/" << lang << ".ini";
  649. string path;
  650. if (GetDataFilePath(file.str().c_str(), path)) {
  651. if (!text_lookup_add(textLookup, path.c_str()))
  652. blog(LOG_ERROR, "Failed to add locale file '%s'",
  653. path.c_str());
  654. } else {
  655. blog(LOG_ERROR, "Could not find locale file '%s'",
  656. file.str().c_str());
  657. }
  658. return true;
  659. }
  660. void OBSApp::AddExtraThemeColor(QPalette &pal, int group,
  661. const char *name, uint32_t color)
  662. {
  663. std::function<void(QPalette::ColorGroup)> func;
  664. #define DEF_PALETTE_ASSIGN(name) \
  665. do { \
  666. func = [&] (QPalette::ColorGroup group) \
  667. { \
  668. pal.setColor(group, QPalette::name, \
  669. QColor::fromRgb(color)); \
  670. }; \
  671. } while (false)
  672. if (astrcmpi(name, "alternateBase") == 0) {
  673. DEF_PALETTE_ASSIGN(AlternateBase);
  674. } else if (astrcmpi(name, "base") == 0) {
  675. DEF_PALETTE_ASSIGN(Base);
  676. } else if (astrcmpi(name, "brightText") == 0) {
  677. DEF_PALETTE_ASSIGN(BrightText);
  678. } else if (astrcmpi(name, "button") == 0) {
  679. DEF_PALETTE_ASSIGN(Button);
  680. } else if (astrcmpi(name, "buttonText") == 0) {
  681. DEF_PALETTE_ASSIGN(ButtonText);
  682. } else if (astrcmpi(name, "brightText") == 0) {
  683. DEF_PALETTE_ASSIGN(BrightText);
  684. } else if (astrcmpi(name, "dark") == 0) {
  685. DEF_PALETTE_ASSIGN(Dark);
  686. } else if (astrcmpi(name, "highlight") == 0) {
  687. DEF_PALETTE_ASSIGN(Highlight);
  688. } else if (astrcmpi(name, "highlightedText") == 0) {
  689. DEF_PALETTE_ASSIGN(HighlightedText);
  690. } else if (astrcmpi(name, "light") == 0) {
  691. DEF_PALETTE_ASSIGN(Light);
  692. } else if (astrcmpi(name, "link") == 0) {
  693. DEF_PALETTE_ASSIGN(Link);
  694. } else if (astrcmpi(name, "linkVisited") == 0) {
  695. DEF_PALETTE_ASSIGN(LinkVisited);
  696. } else if (astrcmpi(name, "mid") == 0) {
  697. DEF_PALETTE_ASSIGN(Mid);
  698. } else if (astrcmpi(name, "midlight") == 0) {
  699. DEF_PALETTE_ASSIGN(Midlight);
  700. } else if (astrcmpi(name, "shadow") == 0) {
  701. DEF_PALETTE_ASSIGN(Shadow);
  702. } else if (astrcmpi(name, "text") == 0 ||
  703. astrcmpi(name, "foreground") == 0) {
  704. DEF_PALETTE_ASSIGN(Text);
  705. } else if (astrcmpi(name, "toolTipBase") == 0) {
  706. DEF_PALETTE_ASSIGN(ToolTipBase);
  707. } else if (astrcmpi(name, "toolTipText") == 0) {
  708. DEF_PALETTE_ASSIGN(ToolTipText);
  709. } else if (astrcmpi(name, "windowText") == 0) {
  710. DEF_PALETTE_ASSIGN(WindowText);
  711. } else if (astrcmpi(name, "window") == 0 ||
  712. astrcmpi(name, "background") == 0) {
  713. DEF_PALETTE_ASSIGN(Window);
  714. } else {
  715. return;
  716. }
  717. #undef DEF_PALETTE_ASSIGN
  718. switch (group) {
  719. case QPalette::Disabled:
  720. case QPalette::Active:
  721. case QPalette::Inactive:
  722. func((QPalette::ColorGroup)group);
  723. break;
  724. default:
  725. func((QPalette::ColorGroup)QPalette::Disabled);
  726. func((QPalette::ColorGroup)QPalette::Active);
  727. func((QPalette::ColorGroup)QPalette::Inactive);
  728. }
  729. }
  730. struct CFParser {
  731. cf_parser cfp = {};
  732. inline ~CFParser() {cf_parser_free(&cfp);}
  733. inline operator cf_parser*() {return &cfp;}
  734. inline cf_parser *operator->() {return &cfp;}
  735. };
  736. void OBSApp::ParseExtraThemeData(const char *path)
  737. {
  738. BPtr<char> data = os_quick_read_utf8_file(path);
  739. QPalette pal = palette();
  740. CFParser cfp;
  741. int ret;
  742. cf_parser_parse(cfp, data, path);
  743. while (cf_go_to_token(cfp, "OBSTheme", nullptr)) {
  744. if (!cf_next_token(cfp)) return;
  745. int group = -1;
  746. if (cf_token_is(cfp, ":")) {
  747. ret = cf_next_token_should_be(cfp, ":", nullptr,
  748. nullptr);
  749. if (ret != PARSE_SUCCESS) continue;
  750. if (!cf_next_token(cfp)) return;
  751. if (cf_token_is(cfp, "disabled")) {
  752. group = QPalette::Disabled;
  753. } else if (cf_token_is(cfp, "active")) {
  754. group = QPalette::Active;
  755. } else if (cf_token_is(cfp, "inactive")) {
  756. group = QPalette::Inactive;
  757. } else {
  758. continue;
  759. }
  760. if (!cf_next_token(cfp)) return;
  761. }
  762. if (!cf_token_is(cfp, "{")) continue;
  763. for (;;) {
  764. if (!cf_next_token(cfp)) return;
  765. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name",
  766. nullptr);
  767. if (ret != PARSE_SUCCESS)
  768. break;
  769. DStr name;
  770. dstr_copy_strref(name, &cfp->cur_token->str);
  771. ret = cf_next_token_should_be(cfp, ":", ";",
  772. nullptr);
  773. if (ret != PARSE_SUCCESS) continue;
  774. if (!cf_next_token(cfp)) return;
  775. const char *array;
  776. uint32_t color = 0;
  777. if (cf_token_is(cfp, "#")) {
  778. array = cfp->cur_token->str.array;
  779. color = strtol(array + 1, nullptr, 16);
  780. } else if (cf_token_is(cfp, "rgb")) {
  781. ret = cf_next_token_should_be(cfp, "(", ";",
  782. nullptr);
  783. if (ret != PARSE_SUCCESS) continue;
  784. if (!cf_next_token(cfp)) return;
  785. array = cfp->cur_token->str.array;
  786. color |= strtol(array, nullptr, 10) << 16;
  787. ret = cf_next_token_should_be(cfp, ",", ";",
  788. nullptr);
  789. if (ret != PARSE_SUCCESS) continue;
  790. if (!cf_next_token(cfp)) return;
  791. array = cfp->cur_token->str.array;
  792. color |= strtol(array, nullptr, 10) << 8;
  793. ret = cf_next_token_should_be(cfp, ",", ";",
  794. nullptr);
  795. if (ret != PARSE_SUCCESS) continue;
  796. if (!cf_next_token(cfp)) return;
  797. array = cfp->cur_token->str.array;
  798. color |= strtol(array, nullptr, 10);
  799. } else if (cf_token_is(cfp, "white")) {
  800. color = 0xFFFFFF;
  801. } else if (cf_token_is(cfp, "black")) {
  802. color = 0;
  803. }
  804. if (!cf_go_to_token(cfp, ";", nullptr)) return;
  805. AddExtraThemeColor(pal, group, name->array, color);
  806. }
  807. ret = cf_token_should_be(cfp, "}", "}", nullptr);
  808. if (ret != PARSE_SUCCESS) continue;
  809. }
  810. setPalette(pal);
  811. }
  812. bool OBSApp::SetTheme(std::string name, std::string path)
  813. {
  814. theme = name;
  815. /* Check user dir first, then preinstalled themes. */
  816. if (path == "") {
  817. char userDir[512];
  818. name = "themes/" + name + ".qss";
  819. string temp = "obs-studio/" + name;
  820. int ret = GetConfigPath(userDir, sizeof(userDir),
  821. temp.c_str());
  822. if (ret > 0 && QFile::exists(userDir)) {
  823. path = string(userDir);
  824. } else if (!GetDataFilePath(name.c_str(), path)) {
  825. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  826. return false;
  827. }
  828. }
  829. QString mpath = QString("file:///") + path.c_str();
  830. setPalette(defaultPalette);
  831. setStyleSheet(mpath);
  832. ParseExtraThemeData(path.c_str());
  833. emit StyleChanged();
  834. return true;
  835. }
  836. bool OBSApp::InitTheme()
  837. {
  838. defaultPalette = palette();
  839. const char *themeName = config_get_string(globalConfig, "General",
  840. "CurrentTheme");
  841. if (!themeName) {
  842. /* Use deprecated "Theme" value if available */
  843. themeName = config_get_string(globalConfig,
  844. "General", "Theme");
  845. if (!themeName)
  846. themeName = "Default";
  847. }
  848. if (strcmp(themeName, "Default") != 0 && SetTheme(themeName))
  849. return true;
  850. return SetTheme("Default");
  851. }
  852. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  853. : QApplication(argc, argv),
  854. profilerNameStore(store)
  855. {
  856. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  857. }
  858. OBSApp::~OBSApp()
  859. {
  860. #ifdef _WIN32
  861. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  862. "DisableAudioDucking");
  863. if (disableAudioDucking)
  864. DisableAudioDucking(false);
  865. #endif
  866. #ifdef __APPLE__
  867. bool vsyncDiabled = config_get_bool(globalConfig, "Video",
  868. "DisableOSXVSync");
  869. bool resetVSync = config_get_bool(globalConfig, "Video",
  870. "ResetOSXVSyncOnExit");
  871. if (vsyncDiabled && resetVSync)
  872. EnableOSXVSync(true);
  873. #endif
  874. os_inhibit_sleep_set_active(sleepInhibitor, false);
  875. os_inhibit_sleep_destroy(sleepInhibitor);
  876. }
  877. static void move_basic_to_profiles(void)
  878. {
  879. char path[512];
  880. char new_path[512];
  881. os_glob_t *glob;
  882. /* if not first time use */
  883. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  884. return;
  885. if (!os_file_exists(path))
  886. return;
  887. /* if the profiles directory doesn't already exist */
  888. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  889. return;
  890. if (os_file_exists(new_path))
  891. return;
  892. if (os_mkdir(new_path) == MKDIR_ERROR)
  893. return;
  894. strcat(new_path, "/");
  895. strcat(new_path, Str("Untitled"));
  896. if (os_mkdir(new_path) == MKDIR_ERROR)
  897. return;
  898. strcat(path, "/*.*");
  899. if (os_glob(path, 0, &glob) != 0)
  900. return;
  901. strcpy(path, new_path);
  902. for (size_t i = 0; i < glob->gl_pathc; i++) {
  903. struct os_globent ent = glob->gl_pathv[i];
  904. char *file;
  905. if (ent.directory)
  906. continue;
  907. file = strrchr(ent.path, '/');
  908. if (!file++)
  909. continue;
  910. if (astrcmpi(file, "scenes.json") == 0)
  911. continue;
  912. strcpy(new_path, path);
  913. strcat(new_path, "/");
  914. strcat(new_path, file);
  915. os_rename(ent.path, new_path);
  916. }
  917. os_globfree(glob);
  918. }
  919. static void move_basic_to_scene_collections(void)
  920. {
  921. char path[512];
  922. char new_path[512];
  923. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  924. return;
  925. if (!os_file_exists(path))
  926. return;
  927. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  928. return;
  929. if (os_file_exists(new_path))
  930. return;
  931. if (os_mkdir(new_path) == MKDIR_ERROR)
  932. return;
  933. strcat(path, "/scenes.json");
  934. strcat(new_path, "/");
  935. strcat(new_path, Str("Untitled"));
  936. strcat(new_path, ".json");
  937. os_rename(path, new_path);
  938. }
  939. void OBSApp::AppInit()
  940. {
  941. ProfileScope("OBSApp::AppInit");
  942. if (!InitApplicationBundle())
  943. throw "Failed to initialize application bundle";
  944. if (!MakeUserDirs())
  945. throw "Failed to create required user directories";
  946. if (!InitGlobalConfig())
  947. throw "Failed to initialize global config";
  948. if (!InitLocale())
  949. throw "Failed to load locale";
  950. if (!InitTheme())
  951. throw "Failed to load theme";
  952. config_set_default_string(globalConfig, "Basic", "Profile",
  953. Str("Untitled"));
  954. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  955. Str("Untitled"));
  956. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  957. Str("Untitled"));
  958. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  959. Str("Untitled"));
  960. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  961. config_set_string(globalConfig, "Basic", "Profile",
  962. Str("Untitled"));
  963. config_set_string(globalConfig, "Basic", "ProfileDir",
  964. Str("Untitled"));
  965. }
  966. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  967. config_set_string(globalConfig, "Basic",
  968. "SceneCollection", Str("Untitled"));
  969. config_set_string(globalConfig, "Basic",
  970. "SceneCollectionFile", Str("Untitled"));
  971. }
  972. #ifdef _WIN32
  973. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  974. "DisableAudioDucking");
  975. if (disableAudioDucking)
  976. DisableAudioDucking(true);
  977. #endif
  978. #ifdef __APPLE__
  979. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  980. EnableOSXVSync(false);
  981. #endif
  982. enableHotkeysInFocus = !config_get_bool(globalConfig, "General",
  983. "DisableHotkeysInFocus");
  984. move_basic_to_profiles();
  985. move_basic_to_scene_collections();
  986. if (!MakeUserProfileDirs())
  987. throw "Failed to create profile directories";
  988. }
  989. const char *OBSApp::GetRenderModule() const
  990. {
  991. const char *renderer = config_get_string(globalConfig, "Video",
  992. "Renderer");
  993. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  994. DL_D3D11 : DL_OPENGL;
  995. }
  996. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  997. {
  998. char path[512];
  999. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1000. return false;
  1001. return obs_startup(locale, path, store);
  1002. }
  1003. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1004. {
  1005. obs_hotkey_enable_background_press(
  1006. inFocus || enableHotkeysInFocus);
  1007. }
  1008. void OBSApp::EnableInFocusHotkeys(bool enable)
  1009. {
  1010. enableHotkeysInFocus = enable;
  1011. ResetHotkeyState(applicationState() != Qt::ApplicationActive);
  1012. }
  1013. Q_DECLARE_METATYPE(VoidFunc)
  1014. void OBSApp::Exec(VoidFunc func)
  1015. {
  1016. func();
  1017. }
  1018. bool OBSApp::OBSInit()
  1019. {
  1020. ProfileScope("OBSApp::OBSInit");
  1021. setAttribute(Qt::AA_UseHighDpiPixmaps);
  1022. qRegisterMetaType<VoidFunc>();
  1023. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1024. return false;
  1025. #ifdef _WIN32
  1026. bool browserHWAccel = config_get_bool(globalConfig, "General",
  1027. "BrowserHWAccel");
  1028. obs_data_t *settings = obs_data_create();
  1029. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1030. obs_apply_private_data(settings);
  1031. obs_data_release(settings);
  1032. blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str());
  1033. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1034. browserHWAccel ? "true" : "false");
  1035. #endif
  1036. blog(LOG_INFO, "Portable mode: %s",
  1037. portable_mode ? "true" : "false");
  1038. setQuitOnLastWindowClosed(false);
  1039. mainWindow = new OBSBasic();
  1040. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1041. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1042. mainWindow->OBSInit();
  1043. connect(this, &QGuiApplication::applicationStateChanged,
  1044. [this](Qt::ApplicationState state)
  1045. {
  1046. ResetHotkeyState(
  1047. state != Qt::ApplicationActive);
  1048. });
  1049. ResetHotkeyState(applicationState() != Qt::ApplicationActive);
  1050. return true;
  1051. }
  1052. string OBSApp::GetVersionString() const
  1053. {
  1054. stringstream ver;
  1055. #ifdef HAVE_OBSCONFIG_H
  1056. ver << OBS_VERSION;
  1057. #else
  1058. ver << LIBOBS_API_MAJOR_VER << "." <<
  1059. LIBOBS_API_MINOR_VER << "." <<
  1060. LIBOBS_API_PATCH_VER;
  1061. #endif
  1062. ver << " (";
  1063. #ifdef _WIN32
  1064. if (sizeof(void*) == 8)
  1065. ver << "64-bit, ";
  1066. else
  1067. ver << "32-bit, ";
  1068. ver << "windows)";
  1069. #elif __APPLE__
  1070. ver << "mac)";
  1071. #elif __FreeBSD__
  1072. ver << "freebsd)";
  1073. #else /* assume linux for the time being */
  1074. ver << "linux)";
  1075. #endif
  1076. return ver.str();
  1077. }
  1078. bool OBSApp::IsPortableMode()
  1079. {
  1080. return portable_mode;
  1081. }
  1082. #ifdef __APPLE__
  1083. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1084. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1085. #elif _WIN32
  1086. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1087. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1088. #else
  1089. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1090. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1091. #endif
  1092. const char *OBSApp::InputAudioSource() const
  1093. {
  1094. return INPUT_AUDIO_SOURCE;
  1095. }
  1096. const char *OBSApp::OutputAudioSource() const
  1097. {
  1098. return OUTPUT_AUDIO_SOURCE;
  1099. }
  1100. const char *OBSApp::GetLastLog() const
  1101. {
  1102. return lastLogFile.c_str();
  1103. }
  1104. const char *OBSApp::GetCurrentLog() const
  1105. {
  1106. return currentLogFile.c_str();
  1107. }
  1108. const char *OBSApp::GetLastCrashLog() const
  1109. {
  1110. return lastCrashLogFile.c_str();
  1111. }
  1112. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1113. {
  1114. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1115. if (cb(lookupVal, out))
  1116. return true;
  1117. }
  1118. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1119. }
  1120. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1121. const char *disambiguation, int n) const
  1122. {
  1123. const char *out = nullptr;
  1124. if (!App()->TranslateString(sourceText, &out))
  1125. return QString(sourceText);
  1126. UNUSED_PARAMETER(context);
  1127. UNUSED_PARAMETER(disambiguation);
  1128. UNUSED_PARAMETER(n);
  1129. return QT_UTF8(out);
  1130. }
  1131. static bool get_token(lexer *lex, string &str, base_token_type type)
  1132. {
  1133. base_token token;
  1134. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1135. return false;
  1136. if (token.type != type)
  1137. return false;
  1138. str.assign(token.text.array, token.text.len);
  1139. return true;
  1140. }
  1141. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1142. {
  1143. base_token token;
  1144. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1145. return false;
  1146. if (token.type != type)
  1147. return false;
  1148. return strref_cmp(&token.text, str) == 0;
  1149. }
  1150. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1151. {
  1152. BaseLexer lex;
  1153. string year, month, day, hour, minute, second;
  1154. lexer_start(lex, name);
  1155. if (has_prefix) {
  1156. string temp;
  1157. if (!get_token(lex, temp, BASETOKEN_ALPHA)) return 0;
  1158. }
  1159. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  1160. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1161. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  1162. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1163. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  1164. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  1165. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1166. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  1167. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  1168. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  1169. stringstream timestring;
  1170. timestring << year << month << day << hour << minute << second;
  1171. return std::stoull(timestring.str());
  1172. }
  1173. static void delete_oldest_file(bool has_prefix, const char *location)
  1174. {
  1175. BPtr<char> logDir(GetConfigPathPtr(location));
  1176. string oldestLog;
  1177. uint64_t oldest_ts = (uint64_t)-1;
  1178. struct os_dirent *entry;
  1179. unsigned int maxLogs = (unsigned int)config_get_uint(
  1180. App()->GlobalConfig(), "General", "MaxLogs");
  1181. os_dir_t *dir = os_opendir(logDir);
  1182. if (dir) {
  1183. unsigned int count = 0;
  1184. while ((entry = os_readdir(dir)) != NULL) {
  1185. if (entry->directory || *entry->d_name == '.')
  1186. continue;
  1187. uint64_t ts = convert_log_name(has_prefix,
  1188. entry->d_name);
  1189. if (ts) {
  1190. if (ts < oldest_ts) {
  1191. oldestLog = entry->d_name;
  1192. oldest_ts = ts;
  1193. }
  1194. count++;
  1195. }
  1196. }
  1197. os_closedir(dir);
  1198. if (count > maxLogs) {
  1199. stringstream delPath;
  1200. delPath << logDir << "/" << oldestLog;
  1201. os_unlink(delPath.str().c_str());
  1202. }
  1203. }
  1204. }
  1205. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1206. std::string &last)
  1207. {
  1208. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1209. struct os_dirent *entry;
  1210. os_dir_t *dir = os_opendir(logDir);
  1211. uint64_t highest_ts = 0;
  1212. if (dir) {
  1213. while ((entry = os_readdir(dir)) != NULL) {
  1214. if (entry->directory || *entry->d_name == '.')
  1215. continue;
  1216. uint64_t ts = convert_log_name(has_prefix,
  1217. entry->d_name);
  1218. if (ts > highest_ts) {
  1219. last = entry->d_name;
  1220. highest_ts = ts;
  1221. }
  1222. }
  1223. os_closedir(dir);
  1224. }
  1225. }
  1226. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1227. {
  1228. time_t now = time(0);
  1229. char file[256] = {};
  1230. struct tm *cur_time;
  1231. cur_time = localtime(&now);
  1232. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1233. cur_time->tm_year+1900,
  1234. cur_time->tm_mon+1,
  1235. cur_time->tm_mday,
  1236. noSpace ? '_' : ' ',
  1237. cur_time->tm_hour,
  1238. cur_time->tm_min,
  1239. cur_time->tm_sec,
  1240. extension);
  1241. return string(file);
  1242. }
  1243. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1244. const char *format)
  1245. {
  1246. OBSBasic *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1247. bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux");
  1248. if ((strcmp(extension, "mp4") == 0) && autoRemux)
  1249. extension = "mkv";
  1250. BPtr<char> filename = os_generate_formatted_filename(extension,
  1251. !noSpace, format);
  1252. remuxFilename = string(filename);
  1253. remuxAfterRecord = autoRemux;
  1254. return string(filename);
  1255. }
  1256. vector<pair<string, string>> GetLocaleNames()
  1257. {
  1258. string path;
  1259. if (!GetDataFilePath("locale.ini", path))
  1260. throw "Could not find locale.ini path";
  1261. ConfigFile ini;
  1262. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1263. throw "Could not open locale.ini";
  1264. size_t sections = config_num_sections(ini);
  1265. vector<pair<string, string>> names;
  1266. names.reserve(sections);
  1267. for (size_t i = 0; i < sections; i++) {
  1268. const char *tag = config_get_section(ini, i);
  1269. const char *name = config_get_string(ini, tag, "Name");
  1270. names.emplace_back(tag, name);
  1271. }
  1272. return names;
  1273. }
  1274. static void create_log_file(fstream &logFile)
  1275. {
  1276. stringstream dst;
  1277. get_last_log(false, "obs-studio/logs", lastLogFile);
  1278. #ifdef _WIN32
  1279. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1280. #endif
  1281. currentLogFile = GenerateTimeDateFilename("txt");
  1282. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1283. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1284. #ifdef _WIN32
  1285. BPtr<wchar_t> wpath;
  1286. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1287. logFile.open(wpath,
  1288. ios_base::in | ios_base::out | ios_base::trunc);
  1289. #else
  1290. logFile.open(path,
  1291. ios_base::in | ios_base::out | ios_base::trunc);
  1292. #endif
  1293. if (logFile.is_open()) {
  1294. delete_oldest_file(false, "obs-studio/logs");
  1295. base_set_log_handler(do_log, &logFile);
  1296. } else {
  1297. blog(LOG_ERROR, "Failed to open log file");
  1298. }
  1299. }
  1300. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  1301. {
  1302. profiler_name_store_free(store);
  1303. };
  1304. using ProfilerNameStore =
  1305. std::unique_ptr<profiler_name_store_t,
  1306. decltype(ProfilerNameStoreRelease)>;
  1307. ProfilerNameStore CreateNameStore()
  1308. {
  1309. return ProfilerNameStore{profiler_name_store_create(),
  1310. ProfilerNameStoreRelease};
  1311. }
  1312. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  1313. {
  1314. profile_snapshot_free(snap);
  1315. };
  1316. using ProfilerSnapshot =
  1317. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1318. ProfilerSnapshot GetSnapshot()
  1319. {
  1320. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1321. }
  1322. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1323. {
  1324. if (currentLogFile.empty())
  1325. return;
  1326. auto pos = currentLogFile.rfind('.');
  1327. if (pos == currentLogFile.npos)
  1328. return;
  1329. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1330. ostringstream dst;
  1331. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1332. dst.write(currentLogFile.c_str(), pos);
  1333. dst.write(LITERAL_SIZE(".csv.gz"));
  1334. #undef LITERAL_SIZE
  1335. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1336. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1337. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1338. static_cast<const char*>(path));
  1339. }
  1340. static auto ProfilerFree = [](void *)
  1341. {
  1342. profiler_stop();
  1343. auto snap = GetSnapshot();
  1344. profiler_print(snap.get());
  1345. profiler_print_time_between_calls(snap.get());
  1346. SaveProfilerData(snap);
  1347. profiler_free();
  1348. };
  1349. static const char *run_program_init = "run_program_init";
  1350. static int run_program(fstream &logFile, int argc, char *argv[])
  1351. {
  1352. int ret = -1;
  1353. auto profilerNameStore = CreateNameStore();
  1354. std::unique_ptr<void, decltype(ProfilerFree)>
  1355. prof_release(static_cast<void*>(&ProfilerFree),
  1356. ProfilerFree);
  1357. profiler_start();
  1358. profile_register_root(run_program_init, 0);
  1359. ScopeProfiler prof{run_program_init};
  1360. #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  1361. QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  1362. #endif
  1363. QCoreApplication::addLibraryPath(".");
  1364. OBSApp program(argc, argv, profilerNameStore.get());
  1365. try {
  1366. bool created_log = false;
  1367. program.AppInit();
  1368. delete_oldest_file(false, "obs-studio/profiler_data");
  1369. OBSTranslator translator;
  1370. program.installTranslator(&translator);
  1371. #ifdef _WIN32
  1372. /* --------------------------------------- */
  1373. /* check and warn if already running */
  1374. bool cancel_launch = false;
  1375. bool already_running = false;
  1376. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1377. if (!already_running) {
  1378. goto run;
  1379. }
  1380. if (!multi) {
  1381. QMessageBox::StandardButtons buttons(
  1382. QMessageBox::Yes | QMessageBox::Cancel);
  1383. QMessageBox mb(QMessageBox::Question,
  1384. QTStr("AlreadyRunning.Title"),
  1385. QTStr("AlreadyRunning.Text"), buttons,
  1386. nullptr);
  1387. mb.setButtonText(QMessageBox::Yes,
  1388. QTStr("AlreadyRunning.LaunchAnyway"));
  1389. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1390. mb.setDefaultButton(QMessageBox::Cancel);
  1391. QMessageBox::StandardButton button;
  1392. button = (QMessageBox::StandardButton)mb.exec();
  1393. cancel_launch = button == QMessageBox::Cancel;
  1394. }
  1395. if (cancel_launch)
  1396. return 0;
  1397. if (!created_log) {
  1398. create_log_file(logFile);
  1399. created_log = true;
  1400. }
  1401. if (multi) {
  1402. blog(LOG_INFO, "User enabled --multi flag and is now "
  1403. "running multiple instances of OBS.");
  1404. } else {
  1405. blog(LOG_WARNING, "================================");
  1406. blog(LOG_WARNING, "Warning: OBS is already running!");
  1407. blog(LOG_WARNING, "================================");
  1408. blog(LOG_WARNING, "User is now running multiple "
  1409. "instances of OBS!");
  1410. }
  1411. /* --------------------------------------- */
  1412. run:
  1413. #endif
  1414. if (!created_log) {
  1415. create_log_file(logFile);
  1416. created_log = true;
  1417. }
  1418. if (argc > 1) {
  1419. stringstream stor;
  1420. stor << argv[1];
  1421. for (int i = 2; i < argc; ++i) {
  1422. stor << " " << argv[i];
  1423. }
  1424. blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str());
  1425. }
  1426. if (!program.OBSInit())
  1427. return 0;
  1428. prof.Stop();
  1429. return program.exec();
  1430. } catch (const char *error) {
  1431. blog(LOG_ERROR, "%s", error);
  1432. OBSErrorBox(nullptr, "%s", error);
  1433. }
  1434. return ret;
  1435. }
  1436. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1437. #ifdef _WIN32
  1438. #define CRASH_MESSAGE \
  1439. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1440. "to the clipboard? (Crash logs will still be saved to the " \
  1441. "%appdata%\\obs-studio\\crashes directory)"
  1442. static void main_crash_handler(const char *format, va_list args, void *param)
  1443. {
  1444. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1445. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1446. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1447. delete_oldest_file(true, "obs-studio/crashes");
  1448. string name = "obs-studio/crashes/Crash ";
  1449. name += GenerateTimeDateFilename("txt");
  1450. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1451. fstream file;
  1452. #ifdef _WIN32
  1453. BPtr<wchar_t> wpath;
  1454. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1455. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1456. ios_base::binary);
  1457. #else
  1458. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1459. ios_base::binary);
  1460. #endif
  1461. file << text;
  1462. file.close();
  1463. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1464. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1465. if (ret == IDYES) {
  1466. size_t len = strlen(text);
  1467. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1468. memcpy(GlobalLock(mem), text, len);
  1469. GlobalUnlock(mem);
  1470. OpenClipboard(0);
  1471. EmptyClipboard();
  1472. SetClipboardData(CF_TEXT, mem);
  1473. CloseClipboard();
  1474. }
  1475. exit(-1);
  1476. UNUSED_PARAMETER(param);
  1477. }
  1478. static void load_debug_privilege(void)
  1479. {
  1480. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1481. TOKEN_PRIVILEGES tp;
  1482. HANDLE token;
  1483. LUID val;
  1484. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1485. return;
  1486. }
  1487. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1488. tp.PrivilegeCount = 1;
  1489. tp.Privileges[0].Luid = val;
  1490. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1491. AdjustTokenPrivileges(token, false, &tp,
  1492. sizeof(tp), NULL, NULL);
  1493. }
  1494. CloseHandle(token);
  1495. }
  1496. #endif
  1497. #ifdef __APPLE__
  1498. #define BASE_PATH ".."
  1499. #else
  1500. #define BASE_PATH "../.."
  1501. #endif
  1502. #define CONFIG_PATH BASE_PATH "/config"
  1503. #ifndef OBS_UNIX_STRUCTURE
  1504. #define OBS_UNIX_STRUCTURE 0
  1505. #endif
  1506. int GetConfigPath(char *path, size_t size, const char *name)
  1507. {
  1508. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1509. if (name && *name) {
  1510. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1511. } else {
  1512. return snprintf(path, size, CONFIG_PATH);
  1513. }
  1514. } else {
  1515. return os_get_config_path(path, size, name);
  1516. }
  1517. }
  1518. char *GetConfigPathPtr(const char *name)
  1519. {
  1520. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1521. char path[512];
  1522. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1523. return bstrdup(path);
  1524. } else {
  1525. return NULL;
  1526. }
  1527. } else {
  1528. return os_get_config_path_ptr(name);
  1529. }
  1530. }
  1531. int GetProgramDataPath(char *path, size_t size, const char *name)
  1532. {
  1533. return os_get_program_data_path(path, size, name);
  1534. }
  1535. char *GetProgramDataPathPtr(const char *name)
  1536. {
  1537. return os_get_program_data_path_ptr(name);
  1538. }
  1539. bool GetFileSafeName(const char *name, std::string &file)
  1540. {
  1541. size_t base_len = strlen(name);
  1542. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1543. std::wstring wfile;
  1544. if (!len)
  1545. return false;
  1546. wfile.resize(len);
  1547. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1548. for (size_t i = wfile.size(); i > 0; i--) {
  1549. size_t im1 = i - 1;
  1550. if (iswspace(wfile[im1])) {
  1551. wfile[im1] = '_';
  1552. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1553. wfile.erase(im1, 1);
  1554. }
  1555. }
  1556. if (wfile.size() == 0)
  1557. wfile = L"characters_only";
  1558. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1559. if (!len)
  1560. return false;
  1561. file.resize(len);
  1562. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1563. return true;
  1564. }
  1565. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1566. {
  1567. size_t len = path.size();
  1568. if (extension) {
  1569. path += ".";
  1570. path += extension;
  1571. }
  1572. if (!os_file_exists(path.c_str()))
  1573. return true;
  1574. int index = 1;
  1575. do {
  1576. path.resize(len);
  1577. path += std::to_string(++index);
  1578. if (extension) {
  1579. path += ".";
  1580. path += extension;
  1581. }
  1582. } while (os_file_exists(path.c_str()));
  1583. return true;
  1584. }
  1585. bool WindowPositionValid(QRect rect)
  1586. {
  1587. for (QScreen* screen: QGuiApplication::screens()) {
  1588. if (screen->availableGeometry().intersects(rect))
  1589. return true;
  1590. }
  1591. return false;
  1592. }
  1593. static inline bool arg_is(const char *arg,
  1594. const char *long_form, const char *short_form)
  1595. {
  1596. return (long_form && strcmp(arg, long_form) == 0) ||
  1597. (short_form && strcmp(arg, short_form) == 0);
  1598. }
  1599. #if !defined(_WIN32) && !defined(__APPLE__)
  1600. #define IS_UNIX 1
  1601. #endif
  1602. /* if using XDG and was previously using an older build of OBS, move config
  1603. * files to XDG directory */
  1604. #if defined(USE_XDG) && defined(IS_UNIX)
  1605. static void move_to_xdg(void)
  1606. {
  1607. char old_path[512];
  1608. char new_path[512];
  1609. char *home = getenv("HOME");
  1610. if (!home)
  1611. return;
  1612. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1613. return;
  1614. /* make base xdg path if it doesn't already exist */
  1615. if (GetConfigPath(new_path, 512, "") <= 0)
  1616. return;
  1617. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1618. return;
  1619. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1620. return;
  1621. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1622. rename(old_path, new_path);
  1623. }
  1624. }
  1625. #endif
  1626. static bool update_ffmpeg_output(ConfigFile &config)
  1627. {
  1628. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1629. return false;
  1630. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1631. if (!url)
  1632. return false;
  1633. bool isActualURL = strstr(url, "://") != nullptr;
  1634. if (isActualURL)
  1635. return false;
  1636. string urlStr = url;
  1637. string extension;
  1638. for (size_t i = urlStr.length(); i > 0; i--) {
  1639. size_t idx = i - 1;
  1640. if (urlStr[idx] == '.') {
  1641. extension = &urlStr[i];
  1642. }
  1643. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1644. urlStr[idx] = 0;
  1645. break;
  1646. }
  1647. }
  1648. if (urlStr.empty() || extension.empty())
  1649. return false;
  1650. config_remove_value(config, "AdvOut", "FFURL");
  1651. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1652. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1653. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1654. return true;
  1655. }
  1656. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1657. {
  1658. bool changed = false;
  1659. if (config_has_user_value(config, sec, "Reconnect")) {
  1660. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1661. config_set_bool(config, "Output", "Reconnect", reconnect);
  1662. changed = true;
  1663. }
  1664. if (config_has_user_value(config, sec, "RetryDelay")) {
  1665. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1666. config_set_uint(config, "Output", "RetryDelay", delay);
  1667. changed = true;
  1668. }
  1669. if (config_has_user_value(config, sec, "MaxRetries")) {
  1670. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1671. config_set_uint(config, "Output", "MaxRetries", retries);
  1672. changed = true;
  1673. }
  1674. return changed;
  1675. }
  1676. static bool update_reconnect(ConfigFile &config)
  1677. {
  1678. if (!config_has_user_value(config, "Output", "Mode"))
  1679. return false;
  1680. const char *mode = config_get_string(config, "Output", "Mode");
  1681. if (!mode)
  1682. return false;
  1683. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1684. "AdvOut" : "SimpleOutput";
  1685. if (move_reconnect_settings(config, section)) {
  1686. config_remove_value(config, "SimpleOutput", "Reconnect");
  1687. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1688. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1689. config_remove_value(config, "AdvOut", "Reconnect");
  1690. config_remove_value(config, "AdvOut", "RetryDelay");
  1691. config_remove_value(config, "AdvOut", "MaxRetries");
  1692. return true;
  1693. }
  1694. return false;
  1695. }
  1696. static void convert_x264_settings(obs_data_t *data)
  1697. {
  1698. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1699. if (use_bufsize) {
  1700. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1701. if (buffer_size == 0)
  1702. obs_data_set_string(data, "rate_control", "CRF");
  1703. }
  1704. }
  1705. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1706. {
  1707. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1708. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1709. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1710. bool modified = false;
  1711. bool cbr = true;
  1712. if (cbr_item) {
  1713. cbr = obs_data_item_get_bool(cbr_item);
  1714. obs_data_item_unset_user_value(cbr_item);
  1715. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1716. modified = true;
  1717. }
  1718. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1719. if (!cbr_item)
  1720. obs_data_set_string(data, "rate_control", "CBR");
  1721. else if (!cbr)
  1722. convert_x264_settings(data);
  1723. modified = true;
  1724. }
  1725. if (modified)
  1726. obs_data_save_json_safe(data, file, "tmp", "bak");
  1727. obs_data_item_release(&rc_item);
  1728. obs_data_item_release(&cbr_item);
  1729. obs_data_release(data);
  1730. }
  1731. static void upgrade_settings(void)
  1732. {
  1733. char path[512];
  1734. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1735. if (pathlen <= 0)
  1736. return;
  1737. if (!os_file_exists(path))
  1738. return;
  1739. os_dir_t *dir = os_opendir(path);
  1740. if (!dir)
  1741. return;
  1742. struct os_dirent *ent = os_readdir(dir);
  1743. while (ent) {
  1744. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1745. strcmp(ent->d_name, "..") != 0) {
  1746. strcat(path, "/");
  1747. strcat(path, ent->d_name);
  1748. strcat(path, "/basic.ini");
  1749. ConfigFile config;
  1750. int ret;
  1751. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1752. if (ret == CONFIG_SUCCESS) {
  1753. if (update_ffmpeg_output(config) ||
  1754. update_reconnect(config)) {
  1755. config_save_safe(config, "tmp",
  1756. nullptr);
  1757. }
  1758. }
  1759. if (config) {
  1760. const char *sEnc = config_get_string(config,
  1761. "AdvOut", "Encoder");
  1762. const char *rEnc = config_get_string(config,
  1763. "AdvOut", "RecEncoder");
  1764. /* replace "cbr" option with "rate_control" for
  1765. * each profile's encoder data */
  1766. path[pathlen] = 0;
  1767. strcat(path, "/");
  1768. strcat(path, ent->d_name);
  1769. strcat(path, "/recordEncoder.json");
  1770. convert_14_2_encoder_setting(rEnc, path);
  1771. path[pathlen] = 0;
  1772. strcat(path, "/");
  1773. strcat(path, ent->d_name);
  1774. strcat(path, "/streamEncoder.json");
  1775. convert_14_2_encoder_setting(sEnc, path);
  1776. }
  1777. path[pathlen] = 0;
  1778. }
  1779. ent = os_readdir(dir);
  1780. }
  1781. os_closedir(dir);
  1782. }
  1783. int main(int argc, char *argv[])
  1784. {
  1785. #ifndef _WIN32
  1786. signal(SIGPIPE, SIG_IGN);
  1787. #endif
  1788. #ifdef _WIN32
  1789. obs_init_win32_crash_handler();
  1790. SetErrorMode(SEM_FAILCRITICALERRORS);
  1791. load_debug_privilege();
  1792. base_set_crash_handler(main_crash_handler, nullptr);
  1793. #endif
  1794. base_get_log_handler(&def_log_handler, nullptr);
  1795. #if defined(USE_XDG) && defined(IS_UNIX)
  1796. move_to_xdg();
  1797. #endif
  1798. obs_set_cmdline_args(argc, argv);
  1799. for (int i = 1; i < argc; i++) {
  1800. if (arg_is(argv[i], "--portable", "-p")) {
  1801. portable_mode = true;
  1802. } else if (arg_is(argv[i], "--multi", "-m")) {
  1803. multi = true;
  1804. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1805. log_verbose = true;
  1806. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  1807. opt_always_on_top = true;
  1808. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1809. unfiltered_log = true;
  1810. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1811. opt_start_streaming = true;
  1812. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1813. opt_start_recording = true;
  1814. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1815. opt_start_replaybuffer = true;
  1816. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1817. if (++i < argc) opt_starting_collection = argv[i];
  1818. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1819. if (++i < argc) opt_starting_profile = argv[i];
  1820. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1821. if (++i < argc) opt_starting_scene = argv[i];
  1822. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1823. opt_minimize_tray = true;
  1824. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1825. opt_studio_mode = true;
  1826. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  1827. opt_allow_opengl = true;
  1828. } else if (arg_is(argv[i], "--help", "-h")) {
  1829. std::cout <<
  1830. "--help, -h: Get list of available commands.\n\n" <<
  1831. "--startstreaming: Automatically start streaming.\n" <<
  1832. "--startrecording: Automatically start recording.\n" <<
  1833. "--startreplaybuffer: Start replay buffer.\n\n" <<
  1834. "--collection <string>: Use specific scene collection."
  1835. << "\n" <<
  1836. "--profile <string>: Use specific profile.\n" <<
  1837. "--scene <string>: Start with specific scene.\n\n" <<
  1838. "--studio-mode: Enable studio mode.\n" <<
  1839. "--minimize-to-tray: Minimize to system tray.\n" <<
  1840. "--portable, -p: Use portable mode.\n" <<
  1841. "--multi, -m: Don't warn when launching multiple instances.\n\n" <<
  1842. "--verbose: Make log more verbose.\n" <<
  1843. "--always-on-top: Start in 'always on top' mode.\n\n" <<
  1844. "--unfiltered_log: Make log unfiltered.\n\n" <<
  1845. "--allow-opengl: Allow OpenGL on Windows.\n\n" <<
  1846. "--version, -V: Get current version.\n";
  1847. exit(0);
  1848. } else if (arg_is(argv[i], "--version", "-V")) {
  1849. std::cout << "OBS Studio - " <<
  1850. App()->GetVersionString() << "\n";
  1851. exit(0);
  1852. }
  1853. }
  1854. #if !OBS_UNIX_STRUCTURE
  1855. if (!portable_mode) {
  1856. portable_mode =
  1857. os_file_exists(BASE_PATH "/portable_mode") ||
  1858. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1859. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1860. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1861. }
  1862. #endif
  1863. upgrade_settings();
  1864. fstream logFile;
  1865. curl_global_init(CURL_GLOBAL_ALL);
  1866. int ret = run_program(logFile, argc, argv);
  1867. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1868. base_set_log_handler(nullptr, nullptr);
  1869. return ret;
  1870. }