obs-app.cpp 54 KB

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