obs-app.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  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. #ifdef __APPLE__
  921. setWindowIcon(
  922. QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png")));
  923. #else
  924. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  925. #endif
  926. }
  927. OBSApp::~OBSApp()
  928. {
  929. #ifdef _WIN32
  930. bool disableAudioDucking =
  931. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  932. if (disableAudioDucking)
  933. DisableAudioDucking(false);
  934. #endif
  935. #ifdef __APPLE__
  936. bool vsyncDiabled =
  937. config_get_bool(globalConfig, "Video", "DisableOSXVSync");
  938. bool resetVSync =
  939. config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
  940. if (vsyncDiabled && resetVSync)
  941. EnableOSXVSync(true);
  942. #endif
  943. os_inhibit_sleep_set_active(sleepInhibitor, false);
  944. os_inhibit_sleep_destroy(sleepInhibitor);
  945. if (libobs_initialized)
  946. obs_shutdown();
  947. }
  948. static void move_basic_to_profiles(void)
  949. {
  950. char path[512];
  951. char new_path[512];
  952. os_glob_t *glob;
  953. /* if not first time use */
  954. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  955. return;
  956. if (!os_file_exists(path))
  957. return;
  958. /* if the profiles directory doesn't already exist */
  959. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  960. return;
  961. if (os_file_exists(new_path))
  962. return;
  963. if (os_mkdir(new_path) == MKDIR_ERROR)
  964. return;
  965. strcat(new_path, "/");
  966. strcat(new_path, Str("Untitled"));
  967. if (os_mkdir(new_path) == MKDIR_ERROR)
  968. return;
  969. strcat(path, "/*.*");
  970. if (os_glob(path, 0, &glob) != 0)
  971. return;
  972. strcpy(path, new_path);
  973. for (size_t i = 0; i < glob->gl_pathc; i++) {
  974. struct os_globent ent = glob->gl_pathv[i];
  975. char *file;
  976. if (ent.directory)
  977. continue;
  978. file = strrchr(ent.path, '/');
  979. if (!file++)
  980. continue;
  981. if (astrcmpi(file, "scenes.json") == 0)
  982. continue;
  983. strcpy(new_path, path);
  984. strcat(new_path, "/");
  985. strcat(new_path, file);
  986. os_rename(ent.path, new_path);
  987. }
  988. os_globfree(glob);
  989. }
  990. static void move_basic_to_scene_collections(void)
  991. {
  992. char path[512];
  993. char new_path[512];
  994. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  995. return;
  996. if (!os_file_exists(path))
  997. return;
  998. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  999. return;
  1000. if (os_file_exists(new_path))
  1001. return;
  1002. if (os_mkdir(new_path) == MKDIR_ERROR)
  1003. return;
  1004. strcat(path, "/scenes.json");
  1005. strcat(new_path, "/");
  1006. strcat(new_path, Str("Untitled"));
  1007. strcat(new_path, ".json");
  1008. os_rename(path, new_path);
  1009. }
  1010. void OBSApp::AppInit()
  1011. {
  1012. ProfileScope("OBSApp::AppInit");
  1013. if (!InitApplicationBundle())
  1014. throw "Failed to initialize application bundle";
  1015. if (!MakeUserDirs())
  1016. throw "Failed to create required user directories";
  1017. if (!InitGlobalConfig())
  1018. throw "Failed to initialize global config";
  1019. if (!InitLocale())
  1020. throw "Failed to load locale";
  1021. if (!InitTheme())
  1022. throw "Failed to load theme";
  1023. config_set_default_string(globalConfig, "Basic", "Profile",
  1024. Str("Untitled"));
  1025. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  1026. Str("Untitled"));
  1027. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  1028. Str("Untitled"));
  1029. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  1030. Str("Untitled"));
  1031. config_set_default_bool(globalConfig, "Basic", "ConfigOnNewProfile",
  1032. true);
  1033. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  1034. config_set_string(globalConfig, "Basic", "Profile",
  1035. Str("Untitled"));
  1036. config_set_string(globalConfig, "Basic", "ProfileDir",
  1037. Str("Untitled"));
  1038. }
  1039. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  1040. config_set_string(globalConfig, "Basic", "SceneCollection",
  1041. Str("Untitled"));
  1042. config_set_string(globalConfig, "Basic", "SceneCollectionFile",
  1043. Str("Untitled"));
  1044. }
  1045. #ifdef _WIN32
  1046. bool disableAudioDucking =
  1047. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  1048. if (disableAudioDucking)
  1049. DisableAudioDucking(true);
  1050. #endif
  1051. #ifdef __APPLE__
  1052. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  1053. EnableOSXVSync(false);
  1054. #endif
  1055. UpdateHotkeyFocusSetting(false);
  1056. move_basic_to_profiles();
  1057. move_basic_to_scene_collections();
  1058. if (!MakeUserProfileDirs())
  1059. throw "Failed to create profile directories";
  1060. }
  1061. const char *OBSApp::GetRenderModule() const
  1062. {
  1063. const char *renderer =
  1064. config_get_string(globalConfig, "Video", "Renderer");
  1065. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1066. }
  1067. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1068. {
  1069. char path[512];
  1070. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1071. return false;
  1072. return obs_startup(locale, path, store);
  1073. }
  1074. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1075. {
  1076. obs_hotkey_enable_background_press(
  1077. (inFocus && enableHotkeysInFocus) ||
  1078. (!inFocus && enableHotkeysOutOfFocus));
  1079. }
  1080. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1081. {
  1082. enableHotkeysInFocus = true;
  1083. enableHotkeysOutOfFocus = true;
  1084. const char *hotkeyFocusType =
  1085. config_get_string(globalConfig, "General", "HotkeyFocusType");
  1086. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1087. enableHotkeysInFocus = false;
  1088. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1089. enableHotkeysOutOfFocus = false;
  1090. }
  1091. if (resetState)
  1092. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1093. }
  1094. void OBSApp::DisableHotkeys()
  1095. {
  1096. enableHotkeysInFocus = false;
  1097. enableHotkeysOutOfFocus = false;
  1098. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1099. }
  1100. Q_DECLARE_METATYPE(VoidFunc)
  1101. void OBSApp::Exec(VoidFunc func)
  1102. {
  1103. func();
  1104. }
  1105. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  1106. {
  1107. auto doTask = [=]() {
  1108. /* to get clang-format to behave */
  1109. task(param);
  1110. };
  1111. QMetaObject::invokeMethod(App(), "Exec",
  1112. wait ? WaitConnection() : Qt::AutoConnection,
  1113. Q_ARG(VoidFunc, doTask));
  1114. }
  1115. bool OBSApp::OBSInit()
  1116. {
  1117. ProfileScope("OBSApp::OBSInit");
  1118. setAttribute(Qt::AA_UseHighDpiPixmaps);
  1119. qRegisterMetaType<VoidFunc>();
  1120. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1121. return false;
  1122. libobs_initialized = true;
  1123. obs_set_ui_task_handler(ui_task_handler);
  1124. #ifdef _WIN32
  1125. bool browserHWAccel =
  1126. config_get_bool(globalConfig, "General", "BrowserHWAccel");
  1127. obs_data_t *settings = obs_data_create();
  1128. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1129. obs_apply_private_data(settings);
  1130. obs_data_release(settings);
  1131. blog(LOG_INFO, "Current Date/Time: %s",
  1132. CurrentDateTimeString().c_str());
  1133. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1134. browserHWAccel ? "true" : "false");
  1135. #endif
  1136. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1137. setQuitOnLastWindowClosed(false);
  1138. mainWindow = new OBSBasic();
  1139. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1140. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1141. mainWindow->OBSInit();
  1142. connect(this, &QGuiApplication::applicationStateChanged,
  1143. [this](Qt::ApplicationState state) {
  1144. ResetHotkeyState(state == Qt::ApplicationActive);
  1145. });
  1146. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1147. return true;
  1148. }
  1149. string OBSApp::GetVersionString() const
  1150. {
  1151. stringstream ver;
  1152. #ifdef HAVE_OBSCONFIG_H
  1153. ver << OBS_VERSION;
  1154. #else
  1155. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1156. << LIBOBS_API_PATCH_VER;
  1157. #endif
  1158. ver << " (";
  1159. #ifdef _WIN32
  1160. if (sizeof(void *) == 8)
  1161. ver << "64-bit, ";
  1162. else
  1163. ver << "32-bit, ";
  1164. ver << "windows)";
  1165. #elif __APPLE__
  1166. ver << "mac)";
  1167. #elif __OpenBSD__
  1168. ver << "openbsd)";
  1169. #elif __FreeBSD__
  1170. ver << "freebsd)";
  1171. #else /* assume linux for the time being */
  1172. ver << "linux)";
  1173. #endif
  1174. return ver.str();
  1175. }
  1176. bool OBSApp::IsPortableMode()
  1177. {
  1178. return portable_mode;
  1179. }
  1180. bool OBSApp::IsUpdaterDisabled()
  1181. {
  1182. return opt_disable_updater;
  1183. }
  1184. #ifdef __APPLE__
  1185. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1186. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1187. #elif _WIN32
  1188. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1189. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1190. #else
  1191. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1192. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1193. #endif
  1194. const char *OBSApp::InputAudioSource() const
  1195. {
  1196. return INPUT_AUDIO_SOURCE;
  1197. }
  1198. const char *OBSApp::OutputAudioSource() const
  1199. {
  1200. return OUTPUT_AUDIO_SOURCE;
  1201. }
  1202. const char *OBSApp::GetLastLog() const
  1203. {
  1204. return lastLogFile.c_str();
  1205. }
  1206. const char *OBSApp::GetCurrentLog() const
  1207. {
  1208. return currentLogFile.c_str();
  1209. }
  1210. const char *OBSApp::GetLastCrashLog() const
  1211. {
  1212. return lastCrashLogFile.c_str();
  1213. }
  1214. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1215. {
  1216. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1217. if (cb(lookupVal, out))
  1218. return true;
  1219. }
  1220. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1221. }
  1222. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1223. const char *disambiguation, int n) const
  1224. {
  1225. const char *out = nullptr;
  1226. if (!App()->TranslateString(sourceText, &out))
  1227. return QString(sourceText);
  1228. UNUSED_PARAMETER(context);
  1229. UNUSED_PARAMETER(disambiguation);
  1230. UNUSED_PARAMETER(n);
  1231. return QT_UTF8(out);
  1232. }
  1233. static bool get_token(lexer *lex, string &str, base_token_type type)
  1234. {
  1235. base_token token;
  1236. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1237. return false;
  1238. if (token.type != type)
  1239. return false;
  1240. str.assign(token.text.array, token.text.len);
  1241. return true;
  1242. }
  1243. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1244. {
  1245. base_token token;
  1246. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1247. return false;
  1248. if (token.type != type)
  1249. return false;
  1250. return strref_cmp(&token.text, str) == 0;
  1251. }
  1252. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1253. {
  1254. BaseLexer lex;
  1255. string year, month, day, hour, minute, second;
  1256. lexer_start(lex, name);
  1257. if (has_prefix) {
  1258. string temp;
  1259. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1260. return 0;
  1261. }
  1262. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1263. return 0;
  1264. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1265. return 0;
  1266. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1267. return 0;
  1268. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1269. return 0;
  1270. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1271. return 0;
  1272. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1273. return 0;
  1274. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1275. return 0;
  1276. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1277. return 0;
  1278. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1279. return 0;
  1280. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1281. return 0;
  1282. stringstream timestring;
  1283. timestring << year << month << day << hour << minute << second;
  1284. return std::stoull(timestring.str());
  1285. }
  1286. static void delete_oldest_file(bool has_prefix, const char *location)
  1287. {
  1288. BPtr<char> logDir(GetConfigPathPtr(location));
  1289. string oldestLog;
  1290. uint64_t oldest_ts = (uint64_t)-1;
  1291. struct os_dirent *entry;
  1292. unsigned int maxLogs = (unsigned int)config_get_uint(
  1293. App()->GlobalConfig(), "General", "MaxLogs");
  1294. os_dir_t *dir = os_opendir(logDir);
  1295. if (dir) {
  1296. unsigned int count = 0;
  1297. while ((entry = os_readdir(dir)) != NULL) {
  1298. if (entry->directory || *entry->d_name == '.')
  1299. continue;
  1300. uint64_t ts =
  1301. convert_log_name(has_prefix, entry->d_name);
  1302. if (ts) {
  1303. if (ts < oldest_ts) {
  1304. oldestLog = entry->d_name;
  1305. oldest_ts = ts;
  1306. }
  1307. count++;
  1308. }
  1309. }
  1310. os_closedir(dir);
  1311. if (count > maxLogs) {
  1312. stringstream delPath;
  1313. delPath << logDir << "/" << oldestLog;
  1314. os_unlink(delPath.str().c_str());
  1315. }
  1316. }
  1317. }
  1318. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1319. std::string &last)
  1320. {
  1321. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1322. struct os_dirent *entry;
  1323. os_dir_t *dir = os_opendir(logDir);
  1324. uint64_t highest_ts = 0;
  1325. if (dir) {
  1326. while ((entry = os_readdir(dir)) != NULL) {
  1327. if (entry->directory || *entry->d_name == '.')
  1328. continue;
  1329. uint64_t ts =
  1330. convert_log_name(has_prefix, entry->d_name);
  1331. if (ts > highest_ts) {
  1332. last = entry->d_name;
  1333. highest_ts = ts;
  1334. }
  1335. }
  1336. os_closedir(dir);
  1337. }
  1338. }
  1339. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1340. {
  1341. time_t now = time(0);
  1342. char file[256] = {};
  1343. struct tm *cur_time;
  1344. cur_time = localtime(&now);
  1345. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1346. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1347. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1348. cur_time->tm_min, cur_time->tm_sec, extension);
  1349. return string(file);
  1350. }
  1351. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1352. const char *format)
  1353. {
  1354. BPtr<char> filename =
  1355. os_generate_formatted_filename(extension, !noSpace, format);
  1356. return string(filename);
  1357. }
  1358. static void FindBestFilename(string &strPath, bool noSpace)
  1359. {
  1360. int num = 2;
  1361. if (!os_file_exists(strPath.c_str()))
  1362. return;
  1363. const char *ext = strrchr(strPath.c_str(), '.');
  1364. if (!ext)
  1365. return;
  1366. int extStart = int(ext - strPath.c_str());
  1367. for (;;) {
  1368. string testPath = strPath;
  1369. string numStr;
  1370. numStr = noSpace ? "_" : " (";
  1371. numStr += to_string(num++);
  1372. if (!noSpace)
  1373. numStr += ")";
  1374. testPath.insert(extStart, numStr);
  1375. if (!os_file_exists(testPath.c_str())) {
  1376. strPath = testPath;
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. static void ensure_directory_exists(string &path)
  1382. {
  1383. replace(path.begin(), path.end(), '\\', '/');
  1384. size_t last = path.rfind('/');
  1385. if (last == string::npos)
  1386. return;
  1387. string directory = path.substr(0, last);
  1388. os_mkdirs(directory.c_str());
  1389. }
  1390. static void remove_reserved_file_characters(string &s)
  1391. {
  1392. replace(s.begin(), s.end(), '\\', '/');
  1393. replace(s.begin(), s.end(), '*', '_');
  1394. replace(s.begin(), s.end(), '?', '_');
  1395. replace(s.begin(), s.end(), '"', '_');
  1396. replace(s.begin(), s.end(), '|', '_');
  1397. replace(s.begin(), s.end(), ':', '_');
  1398. replace(s.begin(), s.end(), '>', '_');
  1399. replace(s.begin(), s.end(), '<', '_');
  1400. }
  1401. string GetFormatString(const char *format, const char *prefix,
  1402. const char *suffix)
  1403. {
  1404. string f;
  1405. if (prefix && *prefix) {
  1406. f += prefix;
  1407. if (f.back() != ' ')
  1408. f += " ";
  1409. }
  1410. f += format;
  1411. if (suffix && *suffix) {
  1412. if (*suffix != ' ')
  1413. f += " ";
  1414. f += suffix;
  1415. }
  1416. remove_reserved_file_characters(f);
  1417. return f;
  1418. }
  1419. string GetOutputFilename(const char *path, const char *ext, bool noSpace,
  1420. bool overwrite, const char *format)
  1421. {
  1422. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1423. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1424. if (!dir) {
  1425. if (main->isVisible())
  1426. OBSMessageBox::warning(main,
  1427. QTStr("Output.BadPath.Title"),
  1428. QTStr("Output.BadPath.Text"));
  1429. else
  1430. main->SysTrayNotify(QTStr("Output.BadPath.Text"),
  1431. QSystemTrayIcon::Warning);
  1432. return "";
  1433. }
  1434. os_closedir(dir);
  1435. string strPath;
  1436. strPath += path;
  1437. char lastChar = strPath.back();
  1438. if (lastChar != '/' && lastChar != '\\')
  1439. strPath += "/";
  1440. strPath += GenerateSpecifiedFilename(ext, noSpace, format);
  1441. ensure_directory_exists(strPath);
  1442. if (!overwrite)
  1443. FindBestFilename(strPath, noSpace);
  1444. return strPath;
  1445. }
  1446. vector<pair<string, string>> GetLocaleNames()
  1447. {
  1448. string path;
  1449. if (!GetDataFilePath("locale.ini", path))
  1450. throw "Could not find locale.ini path";
  1451. ConfigFile ini;
  1452. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1453. throw "Could not open locale.ini";
  1454. size_t sections = config_num_sections(ini);
  1455. vector<pair<string, string>> names;
  1456. names.reserve(sections);
  1457. for (size_t i = 0; i < sections; i++) {
  1458. const char *tag = config_get_section(ini, i);
  1459. const char *name = config_get_string(ini, tag, "Name");
  1460. names.emplace_back(tag, name);
  1461. }
  1462. return names;
  1463. }
  1464. static void create_log_file(fstream &logFile)
  1465. {
  1466. stringstream dst;
  1467. get_last_log(false, "obs-studio/logs", lastLogFile);
  1468. #ifdef _WIN32
  1469. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1470. #endif
  1471. currentLogFile = GenerateTimeDateFilename("txt");
  1472. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1473. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1474. #ifdef _WIN32
  1475. BPtr<wchar_t> wpath;
  1476. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1477. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1478. #else
  1479. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1480. #endif
  1481. if (logFile.is_open()) {
  1482. delete_oldest_file(false, "obs-studio/logs");
  1483. base_set_log_handler(do_log, &logFile);
  1484. } else {
  1485. blog(LOG_ERROR, "Failed to open log file");
  1486. }
  1487. }
  1488. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1489. profiler_name_store_free(store);
  1490. };
  1491. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1492. decltype(ProfilerNameStoreRelease)>;
  1493. ProfilerNameStore CreateNameStore()
  1494. {
  1495. return ProfilerNameStore{profiler_name_store_create(),
  1496. ProfilerNameStoreRelease};
  1497. }
  1498. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1499. profile_snapshot_free(snap);
  1500. };
  1501. using ProfilerSnapshot =
  1502. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1503. ProfilerSnapshot GetSnapshot()
  1504. {
  1505. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1506. }
  1507. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1508. {
  1509. if (currentLogFile.empty())
  1510. return;
  1511. auto pos = currentLogFile.rfind('.');
  1512. if (pos == currentLogFile.npos)
  1513. return;
  1514. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1515. ostringstream dst;
  1516. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1517. dst.write(currentLogFile.c_str(), pos);
  1518. dst.write(LITERAL_SIZE(".csv.gz"));
  1519. #undef LITERAL_SIZE
  1520. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1521. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1522. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1523. static_cast<const char *>(path));
  1524. }
  1525. static auto ProfilerFree = [](void *) {
  1526. profiler_stop();
  1527. auto snap = GetSnapshot();
  1528. profiler_print(snap.get());
  1529. profiler_print_time_between_calls(snap.get());
  1530. SaveProfilerData(snap);
  1531. profiler_free();
  1532. };
  1533. static const char *run_program_init = "run_program_init";
  1534. static int run_program(fstream &logFile, int argc, char *argv[])
  1535. {
  1536. int ret = -1;
  1537. auto profilerNameStore = CreateNameStore();
  1538. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1539. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1540. profiler_start();
  1541. profile_register_root(run_program_init, 0);
  1542. ScopeProfiler prof{run_program_init};
  1543. #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  1544. QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  1545. #endif
  1546. #if !defined(_WIN32) && !defined(__APPLE__) && BROWSER_AVAILABLE
  1547. setenv("QT_NO_GLIB", "1", true);
  1548. #endif
  1549. QCoreApplication::addLibraryPath(".");
  1550. #if __APPLE__
  1551. InstallNSApplicationSubclass();
  1552. #endif
  1553. OBSApp program(argc, argv, profilerNameStore.get());
  1554. try {
  1555. bool created_log = false;
  1556. program.AppInit();
  1557. delete_oldest_file(false, "obs-studio/profiler_data");
  1558. OBSTranslator translator;
  1559. program.installTranslator(&translator);
  1560. /* --------------------------------------- */
  1561. /* check and warn if already running */
  1562. bool cancel_launch = false;
  1563. bool already_running = false;
  1564. #if defined(_WIN32)
  1565. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1566. #elif defined(__APPLE__)
  1567. CheckAppWithSameBundleID(already_running);
  1568. #elif defined(__linux__)
  1569. RunningInstanceCheck(already_running);
  1570. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  1571. PIDFileCheck(already_running);
  1572. #endif
  1573. if (!already_running) {
  1574. goto run;
  1575. }
  1576. if (!multi) {
  1577. QMessageBox::StandardButtons buttons(
  1578. QMessageBox::Yes | QMessageBox::Cancel);
  1579. QMessageBox mb(QMessageBox::Question,
  1580. QTStr("AlreadyRunning.Title"),
  1581. QTStr("AlreadyRunning.Text"), buttons,
  1582. nullptr);
  1583. mb.setButtonText(QMessageBox::Yes,
  1584. QTStr("AlreadyRunning.LaunchAnyway"));
  1585. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1586. mb.setDefaultButton(QMessageBox::Cancel);
  1587. QMessageBox::StandardButton button;
  1588. button = (QMessageBox::StandardButton)mb.exec();
  1589. cancel_launch = button == QMessageBox::Cancel;
  1590. }
  1591. if (cancel_launch)
  1592. return 0;
  1593. if (!created_log) {
  1594. create_log_file(logFile);
  1595. created_log = true;
  1596. }
  1597. if (multi) {
  1598. blog(LOG_INFO, "User enabled --multi flag and is now "
  1599. "running multiple instances of OBS.");
  1600. } else {
  1601. blog(LOG_WARNING, "================================");
  1602. blog(LOG_WARNING, "Warning: OBS is already running!");
  1603. blog(LOG_WARNING, "================================");
  1604. blog(LOG_WARNING, "User is now running multiple "
  1605. "instances of OBS!");
  1606. }
  1607. /* --------------------------------------- */
  1608. run:
  1609. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1610. // Mounted by termina during chromeOS linux container startup
  1611. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1612. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1613. if (crosDir) {
  1614. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1615. QMessageBox mb(QMessageBox::Critical,
  1616. QTStr("ChromeOS.Title"),
  1617. QTStr("ChromeOS.Text"), buttons,
  1618. nullptr);
  1619. mb.exec();
  1620. return 0;
  1621. }
  1622. #endif
  1623. if (!created_log) {
  1624. create_log_file(logFile);
  1625. created_log = true;
  1626. }
  1627. if (argc > 1) {
  1628. stringstream stor;
  1629. stor << argv[1];
  1630. for (int i = 2; i < argc; ++i) {
  1631. stor << " " << argv[i];
  1632. }
  1633. blog(LOG_INFO, "Command Line Arguments: %s",
  1634. stor.str().c_str());
  1635. }
  1636. if (!program.OBSInit())
  1637. return 0;
  1638. prof.Stop();
  1639. ret = program.exec();
  1640. } catch (const char *error) {
  1641. blog(LOG_ERROR, "%s", error);
  1642. OBSErrorBox(nullptr, "%s", error);
  1643. }
  1644. if (restart)
  1645. QProcess::startDetached(qApp->arguments()[0],
  1646. qApp->arguments());
  1647. return ret;
  1648. }
  1649. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1650. #ifdef _WIN32
  1651. #define CRASH_MESSAGE \
  1652. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1653. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1654. static void main_crash_handler(const char *format, va_list args, void *param)
  1655. {
  1656. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1657. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1658. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1659. string crashFilePath = "obs-studio/crashes";
  1660. delete_oldest_file(true, crashFilePath.c_str());
  1661. string name = crashFilePath + "/";
  1662. name += "Crash " + GenerateTimeDateFilename("txt");
  1663. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1664. fstream file;
  1665. #ifdef _WIN32
  1666. BPtr<wchar_t> wpath;
  1667. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1668. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1669. ios_base::binary);
  1670. #else
  1671. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1672. ios_base::binary);
  1673. #endif
  1674. file << text;
  1675. file.close();
  1676. string pathString(path.Get());
  1677. #ifdef _WIN32
  1678. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1679. #endif
  1680. string absolutePath =
  1681. canonical(filesystem::path(pathString)).u8string();
  1682. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1683. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1684. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
  1685. absolutePath.c_str());
  1686. string finalMessage =
  1687. string(message_buffer.get(), message_buffer.get() + size);
  1688. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
  1689. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1690. if (ret == IDYES) {
  1691. size_t len = strlen(text);
  1692. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1693. memcpy(GlobalLock(mem), text, len);
  1694. GlobalUnlock(mem);
  1695. OpenClipboard(0);
  1696. EmptyClipboard();
  1697. SetClipboardData(CF_TEXT, mem);
  1698. CloseClipboard();
  1699. }
  1700. exit(-1);
  1701. UNUSED_PARAMETER(param);
  1702. }
  1703. static void load_debug_privilege(void)
  1704. {
  1705. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1706. TOKEN_PRIVILEGES tp;
  1707. HANDLE token;
  1708. LUID val;
  1709. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1710. return;
  1711. }
  1712. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1713. tp.PrivilegeCount = 1;
  1714. tp.Privileges[0].Luid = val;
  1715. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1716. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1717. NULL);
  1718. }
  1719. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1720. tp.PrivilegeCount = 1;
  1721. tp.Privileges[0].Luid = val;
  1722. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1723. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1724. NULL)) {
  1725. blog(LOG_INFO, "Could not set privilege to "
  1726. "increase GPU priority");
  1727. }
  1728. }
  1729. CloseHandle(token);
  1730. }
  1731. #endif
  1732. #ifdef __APPLE__
  1733. #define BASE_PATH ".."
  1734. #else
  1735. #define BASE_PATH "../.."
  1736. #endif
  1737. #define CONFIG_PATH BASE_PATH "/config"
  1738. #ifndef OBS_UNIX_STRUCTURE
  1739. #define OBS_UNIX_STRUCTURE 0
  1740. #endif
  1741. int GetConfigPath(char *path, size_t size, const char *name)
  1742. {
  1743. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1744. if (name && *name) {
  1745. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1746. } else {
  1747. return snprintf(path, size, CONFIG_PATH);
  1748. }
  1749. } else {
  1750. return os_get_config_path(path, size, name);
  1751. }
  1752. }
  1753. char *GetConfigPathPtr(const char *name)
  1754. {
  1755. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1756. char path[512];
  1757. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1758. return bstrdup(path);
  1759. } else {
  1760. return NULL;
  1761. }
  1762. } else {
  1763. return os_get_config_path_ptr(name);
  1764. }
  1765. }
  1766. int GetProgramDataPath(char *path, size_t size, const char *name)
  1767. {
  1768. return os_get_program_data_path(path, size, name);
  1769. }
  1770. char *GetProgramDataPathPtr(const char *name)
  1771. {
  1772. return os_get_program_data_path_ptr(name);
  1773. }
  1774. bool GetFileSafeName(const char *name, std::string &file)
  1775. {
  1776. size_t base_len = strlen(name);
  1777. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1778. std::wstring wfile;
  1779. if (!len)
  1780. return false;
  1781. wfile.resize(len);
  1782. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1783. for (size_t i = wfile.size(); i > 0; i--) {
  1784. size_t im1 = i - 1;
  1785. if (iswspace(wfile[im1])) {
  1786. wfile[im1] = '_';
  1787. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1788. wfile.erase(im1, 1);
  1789. }
  1790. }
  1791. if (wfile.size() == 0)
  1792. wfile = L"characters_only";
  1793. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1794. if (!len)
  1795. return false;
  1796. file.resize(len);
  1797. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1798. return true;
  1799. }
  1800. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1801. {
  1802. size_t len = path.size();
  1803. if (extension) {
  1804. path += ".";
  1805. path += extension;
  1806. }
  1807. if (!os_file_exists(path.c_str()))
  1808. return true;
  1809. int index = 1;
  1810. do {
  1811. path.resize(len);
  1812. path += std::to_string(++index);
  1813. if (extension) {
  1814. path += ".";
  1815. path += extension;
  1816. }
  1817. } while (os_file_exists(path.c_str()));
  1818. return true;
  1819. }
  1820. bool WindowPositionValid(QRect rect)
  1821. {
  1822. for (QScreen *screen : QGuiApplication::screens()) {
  1823. if (screen->availableGeometry().intersects(rect))
  1824. return true;
  1825. }
  1826. return false;
  1827. }
  1828. static inline bool arg_is(const char *arg, const char *long_form,
  1829. const char *short_form)
  1830. {
  1831. return (long_form && strcmp(arg, long_form) == 0) ||
  1832. (short_form && strcmp(arg, short_form) == 0);
  1833. }
  1834. #if !defined(_WIN32) && !defined(__APPLE__)
  1835. #define IS_UNIX 1
  1836. #endif
  1837. /* if using XDG and was previously using an older build of OBS, move config
  1838. * files to XDG directory */
  1839. #if defined(USE_XDG) && defined(IS_UNIX)
  1840. static void move_to_xdg(void)
  1841. {
  1842. char old_path[512];
  1843. char new_path[512];
  1844. char *home = getenv("HOME");
  1845. if (!home)
  1846. return;
  1847. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1848. return;
  1849. /* make base xdg path if it doesn't already exist */
  1850. if (GetConfigPath(new_path, 512, "") <= 0)
  1851. return;
  1852. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1853. return;
  1854. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1855. return;
  1856. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1857. rename(old_path, new_path);
  1858. }
  1859. }
  1860. #endif
  1861. static bool update_ffmpeg_output(ConfigFile &config)
  1862. {
  1863. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1864. return false;
  1865. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1866. if (!url)
  1867. return false;
  1868. bool isActualURL = strstr(url, "://") != nullptr;
  1869. if (isActualURL)
  1870. return false;
  1871. string urlStr = url;
  1872. string extension;
  1873. for (size_t i = urlStr.length(); i > 0; i--) {
  1874. size_t idx = i - 1;
  1875. if (urlStr[idx] == '.') {
  1876. extension = &urlStr[i];
  1877. }
  1878. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1879. urlStr[idx] = 0;
  1880. break;
  1881. }
  1882. }
  1883. if (urlStr.empty() || extension.empty())
  1884. return false;
  1885. config_remove_value(config, "AdvOut", "FFURL");
  1886. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1887. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1888. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1889. return true;
  1890. }
  1891. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1892. {
  1893. bool changed = false;
  1894. if (config_has_user_value(config, sec, "Reconnect")) {
  1895. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1896. config_set_bool(config, "Output", "Reconnect", reconnect);
  1897. changed = true;
  1898. }
  1899. if (config_has_user_value(config, sec, "RetryDelay")) {
  1900. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1901. config_set_uint(config, "Output", "RetryDelay", delay);
  1902. changed = true;
  1903. }
  1904. if (config_has_user_value(config, sec, "MaxRetries")) {
  1905. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1906. config_set_uint(config, "Output", "MaxRetries", retries);
  1907. changed = true;
  1908. }
  1909. return changed;
  1910. }
  1911. static bool update_reconnect(ConfigFile &config)
  1912. {
  1913. if (!config_has_user_value(config, "Output", "Mode"))
  1914. return false;
  1915. const char *mode = config_get_string(config, "Output", "Mode");
  1916. if (!mode)
  1917. return false;
  1918. const char *section = (strcmp(mode, "Advanced") == 0) ? "AdvOut"
  1919. : "SimpleOutput";
  1920. if (move_reconnect_settings(config, section)) {
  1921. config_remove_value(config, "SimpleOutput", "Reconnect");
  1922. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1923. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1924. config_remove_value(config, "AdvOut", "Reconnect");
  1925. config_remove_value(config, "AdvOut", "RetryDelay");
  1926. config_remove_value(config, "AdvOut", "MaxRetries");
  1927. return true;
  1928. }
  1929. return false;
  1930. }
  1931. static void convert_x264_settings(obs_data_t *data)
  1932. {
  1933. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1934. if (use_bufsize) {
  1935. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1936. if (buffer_size == 0)
  1937. obs_data_set_string(data, "rate_control", "CRF");
  1938. }
  1939. }
  1940. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1941. {
  1942. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1943. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1944. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1945. bool modified = false;
  1946. bool cbr = true;
  1947. if (cbr_item) {
  1948. cbr = obs_data_item_get_bool(cbr_item);
  1949. obs_data_item_unset_user_value(cbr_item);
  1950. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1951. modified = true;
  1952. }
  1953. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1954. if (!cbr_item)
  1955. obs_data_set_string(data, "rate_control", "CBR");
  1956. else if (!cbr)
  1957. convert_x264_settings(data);
  1958. modified = true;
  1959. }
  1960. if (modified)
  1961. obs_data_save_json_safe(data, file, "tmp", "bak");
  1962. obs_data_item_release(&rc_item);
  1963. obs_data_item_release(&cbr_item);
  1964. obs_data_release(data);
  1965. }
  1966. static void upgrade_settings(void)
  1967. {
  1968. char path[512];
  1969. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1970. if (pathlen <= 0)
  1971. return;
  1972. if (!os_file_exists(path))
  1973. return;
  1974. os_dir_t *dir = os_opendir(path);
  1975. if (!dir)
  1976. return;
  1977. struct os_dirent *ent = os_readdir(dir);
  1978. while (ent) {
  1979. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1980. strcmp(ent->d_name, "..") != 0) {
  1981. strcat(path, "/");
  1982. strcat(path, ent->d_name);
  1983. strcat(path, "/basic.ini");
  1984. ConfigFile config;
  1985. int ret;
  1986. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1987. if (ret == CONFIG_SUCCESS) {
  1988. if (update_ffmpeg_output(config) ||
  1989. update_reconnect(config)) {
  1990. config_save_safe(config, "tmp",
  1991. nullptr);
  1992. }
  1993. }
  1994. if (config) {
  1995. const char *sEnc = config_get_string(
  1996. config, "AdvOut", "Encoder");
  1997. const char *rEnc = config_get_string(
  1998. config, "AdvOut", "RecEncoder");
  1999. /* replace "cbr" option with "rate_control" for
  2000. * each profile's encoder data */
  2001. path[pathlen] = 0;
  2002. strcat(path, "/");
  2003. strcat(path, ent->d_name);
  2004. strcat(path, "/recordEncoder.json");
  2005. convert_14_2_encoder_setting(rEnc, path);
  2006. path[pathlen] = 0;
  2007. strcat(path, "/");
  2008. strcat(path, ent->d_name);
  2009. strcat(path, "/streamEncoder.json");
  2010. convert_14_2_encoder_setting(sEnc, path);
  2011. }
  2012. path[pathlen] = 0;
  2013. }
  2014. ent = os_readdir(dir);
  2015. }
  2016. os_closedir(dir);
  2017. }
  2018. void ctrlc_handler(int s)
  2019. {
  2020. UNUSED_PARAMETER(s);
  2021. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  2022. main->close();
  2023. }
  2024. int main(int argc, char *argv[])
  2025. {
  2026. #ifndef _WIN32
  2027. signal(SIGPIPE, SIG_IGN);
  2028. struct sigaction sig_handler;
  2029. sig_handler.sa_handler = ctrlc_handler;
  2030. sigemptyset(&sig_handler.sa_mask);
  2031. sig_handler.sa_flags = 0;
  2032. sigaction(SIGINT, &sig_handler, NULL);
  2033. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  2034. a closed pipe. */
  2035. sigset_t sigpipe_mask;
  2036. sigemptyset(&sigpipe_mask);
  2037. sigaddset(&sigpipe_mask, SIGPIPE);
  2038. sigset_t saved_mask;
  2039. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  2040. perror("pthread_sigmask");
  2041. exit(1);
  2042. }
  2043. #endif
  2044. #ifdef _WIN32
  2045. obs_init_win32_crash_handler();
  2046. SetErrorMode(SEM_FAILCRITICALERRORS);
  2047. load_debug_privilege();
  2048. base_set_crash_handler(main_crash_handler, nullptr);
  2049. #endif
  2050. base_get_log_handler(&def_log_handler, nullptr);
  2051. #if defined(USE_XDG) && defined(IS_UNIX)
  2052. move_to_xdg();
  2053. #endif
  2054. obs_set_cmdline_args(argc, argv);
  2055. for (int i = 1; i < argc; i++) {
  2056. if (arg_is(argv[i], "--portable", "-p")) {
  2057. portable_mode = true;
  2058. } else if (arg_is(argv[i], "--multi", "-m")) {
  2059. multi = true;
  2060. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2061. log_verbose = true;
  2062. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2063. opt_always_on_top = true;
  2064. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2065. unfiltered_log = true;
  2066. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2067. opt_start_streaming = true;
  2068. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2069. opt_start_recording = true;
  2070. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2071. opt_start_replaybuffer = true;
  2072. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2073. opt_start_virtualcam = true;
  2074. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2075. if (++i < argc)
  2076. opt_starting_collection = argv[i];
  2077. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2078. if (++i < argc)
  2079. opt_starting_profile = argv[i];
  2080. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2081. if (++i < argc)
  2082. opt_starting_scene = argv[i];
  2083. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2084. opt_minimize_tray = true;
  2085. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2086. opt_studio_mode = true;
  2087. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2088. opt_allow_opengl = true;
  2089. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2090. opt_disable_updater = true;
  2091. } else if (arg_is(argv[i], "--help", "-h")) {
  2092. std::string help =
  2093. "--help, -h: Get list of available commands.\n\n"
  2094. "--startstreaming: Automatically start streaming.\n"
  2095. "--startrecording: Automatically start recording.\n"
  2096. "--startreplaybuffer: Start replay buffer.\n"
  2097. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2098. "--collection <string>: Use specific scene collection."
  2099. "\n"
  2100. "--profile <string>: Use specific profile.\n"
  2101. "--scene <string>: Start with specific scene.\n\n"
  2102. "--studio-mode: Enable studio mode.\n"
  2103. "--minimize-to-tray: Minimize to system tray.\n"
  2104. "--portable, -p: Use portable mode.\n"
  2105. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2106. "--verbose: Make log more verbose.\n"
  2107. "--always-on-top: Start in 'always on top' mode.\n\n"
  2108. "--unfiltered_log: Make log unfiltered.\n\n"
  2109. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n";
  2110. #ifdef _WIN32
  2111. MessageBoxA(NULL, help.c_str(), "Help",
  2112. MB_OK | MB_ICONASTERISK);
  2113. #else
  2114. std::cout << help
  2115. << "--version, -V: Get current version.\n";
  2116. #endif
  2117. exit(0);
  2118. } else if (arg_is(argv[i], "--version", "-V")) {
  2119. std::cout << "OBS Studio - "
  2120. << App()->GetVersionString() << "\n";
  2121. exit(0);
  2122. }
  2123. }
  2124. #if !OBS_UNIX_STRUCTURE
  2125. if (!portable_mode) {
  2126. portable_mode =
  2127. os_file_exists(BASE_PATH "/portable_mode") ||
  2128. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2129. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2130. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2131. }
  2132. if (!opt_disable_updater) {
  2133. opt_disable_updater =
  2134. os_file_exists(BASE_PATH "/disable_updater") ||
  2135. os_file_exists(BASE_PATH "/disable_updater.txt");
  2136. }
  2137. #endif
  2138. upgrade_settings();
  2139. fstream logFile;
  2140. curl_global_init(CURL_GLOBAL_ALL);
  2141. int ret = run_program(logFile, argc, argv);
  2142. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2143. base_set_log_handler(nullptr, nullptr);
  2144. return ret;
  2145. }