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