obs-app.cpp 64 KB

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