obs-app.cpp 63 KB

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