obs-app.cpp 54 KB

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