obs-app.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 <filesystem>
  23. #include <util/bmem.h>
  24. #include <util/dstr.hpp>
  25. #include <util/platform.h>
  26. #include <util/profiler.hpp>
  27. #include <util/cf-parser.h>
  28. #include <obs-config.h>
  29. #include <obs.hpp>
  30. #include <qt-wrappers.hpp>
  31. #include <slider-ignorewheel.hpp>
  32. #include <QDir>
  33. #include <QFile>
  34. #include <QGuiApplication>
  35. #include <QScreen>
  36. #include <QProcess>
  37. #include <QAccessible>
  38. #include "obs-app.hpp"
  39. #include "obs-proxy-style.hpp"
  40. #include "log-viewer.hpp"
  41. #include "volume-control.hpp"
  42. #include "window-basic-main.hpp"
  43. #ifdef __APPLE__
  44. #include "window-permissions.hpp"
  45. #endif
  46. #include "window-basic-settings.hpp"
  47. #include "platform.hpp"
  48. #include <fstream>
  49. #include <curl/curl.h>
  50. #ifdef _WIN32
  51. #include <windows.h>
  52. #include <filesystem>
  53. #include <util/windows/win-version.h>
  54. #else
  55. #include <signal.h>
  56. #include <pthread.h>
  57. #include <sys/types.h>
  58. #include <sys/socket.h>
  59. #include <unistd.h>
  60. #endif
  61. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  62. #include "update/models/branches.hpp"
  63. #endif
  64. #if !defined(_WIN32) && !defined(__APPLE__)
  65. #include <obs-nix-platform.h>
  66. #include <qpa/qplatformnativeinterface.h>
  67. #endif
  68. #include <iostream>
  69. #include "ui-config.h"
  70. using namespace std;
  71. static log_handler_t def_log_handler;
  72. static string currentLogFile;
  73. static string lastLogFile;
  74. static string lastCrashLogFile;
  75. bool portable_mode = false;
  76. bool steam = false;
  77. bool safe_mode = false;
  78. bool disable_3p_plugins = false;
  79. bool unclean_shutdown = false;
  80. bool disable_shutdown_check = false;
  81. static bool multi = false;
  82. static bool log_verbose = false;
  83. static bool unfiltered_log = false;
  84. bool opt_start_streaming = false;
  85. bool opt_start_recording = false;
  86. bool opt_studio_mode = false;
  87. bool opt_start_replaybuffer = false;
  88. bool opt_start_virtualcam = false;
  89. bool opt_minimize_tray = false;
  90. bool opt_allow_opengl = false;
  91. bool opt_always_on_top = false;
  92. bool opt_disable_updater = false;
  93. bool opt_disable_missing_files_check = false;
  94. string opt_starting_collection;
  95. string opt_starting_profile;
  96. string opt_starting_scene;
  97. bool restart = false;
  98. bool restart_safe = false;
  99. QStringList arguments;
  100. QPointer<OBSLogViewer> obsLogViewer;
  101. #ifndef _WIN32
  102. int OBSApp::sigintFd[2];
  103. #endif
  104. // GPU hint exports for AMD/NVIDIA laptops
  105. #ifdef _MSC_VER
  106. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  107. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  108. #endif
  109. QObject *CreateShortcutFilter()
  110. {
  111. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  112. auto mouse_event = [](QMouseEvent &event) {
  113. if (!App()->HotkeysEnabledInFocus() && event.button() != Qt::LeftButton)
  114. return true;
  115. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  116. bool pressed = event.type() == QEvent::MouseButtonPress;
  117. switch (event.button()) {
  118. case Qt::NoButton:
  119. case Qt::LeftButton:
  120. case Qt::RightButton:
  121. case Qt::AllButtons:
  122. case Qt::MouseButtonMask:
  123. return false;
  124. case Qt::MiddleButton:
  125. hotkey.key = OBS_KEY_MOUSE3;
  126. break;
  127. #define MAP_BUTTON(i, j) \
  128. case Qt::ExtraButton##i: \
  129. hotkey.key = OBS_KEY_MOUSE##j; \
  130. break;
  131. MAP_BUTTON(1, 4);
  132. MAP_BUTTON(2, 5);
  133. MAP_BUTTON(3, 6);
  134. MAP_BUTTON(4, 7);
  135. MAP_BUTTON(5, 8);
  136. MAP_BUTTON(6, 9);
  137. MAP_BUTTON(7, 10);
  138. MAP_BUTTON(8, 11);
  139. MAP_BUTTON(9, 12);
  140. MAP_BUTTON(10, 13);
  141. MAP_BUTTON(11, 14);
  142. MAP_BUTTON(12, 15);
  143. MAP_BUTTON(13, 16);
  144. MAP_BUTTON(14, 17);
  145. MAP_BUTTON(15, 18);
  146. MAP_BUTTON(16, 19);
  147. MAP_BUTTON(17, 20);
  148. MAP_BUTTON(18, 21);
  149. MAP_BUTTON(19, 22);
  150. MAP_BUTTON(20, 23);
  151. MAP_BUTTON(21, 24);
  152. MAP_BUTTON(22, 25);
  153. MAP_BUTTON(23, 26);
  154. MAP_BUTTON(24, 27);
  155. #undef MAP_BUTTON
  156. }
  157. hotkey.modifiers = TranslateQtKeyboardEventModifiers(event.modifiers());
  158. obs_hotkey_inject_event(hotkey, pressed);
  159. return true;
  160. };
  161. auto key_event = [&](QKeyEvent *event) {
  162. int key = event->key();
  163. bool enabledInFocus = App()->HotkeysEnabledInFocus();
  164. if (key != Qt::Key_Enter && key != Qt::Key_Escape && key != Qt::Key_Return && !enabledInFocus)
  165. return true;
  166. QDialog *dialog = qobject_cast<QDialog *>(obj);
  167. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  168. bool pressed = event->type() == QEvent::KeyPress;
  169. switch (key) {
  170. case Qt::Key_Shift:
  171. case Qt::Key_Control:
  172. case Qt::Key_Alt:
  173. case Qt::Key_Meta:
  174. break;
  175. #ifdef __APPLE__
  176. case Qt::Key_CapsLock:
  177. // kVK_CapsLock == 57
  178. hotkey.key = obs_key_from_virtual_key(57);
  179. pressed = true;
  180. break;
  181. #endif
  182. case Qt::Key_Enter:
  183. case Qt::Key_Escape:
  184. case Qt::Key_Return:
  185. if (dialog && pressed)
  186. return false;
  187. if (!enabledInFocus)
  188. return true;
  189. /* Falls through. */
  190. default:
  191. hotkey.key = obs_key_from_virtual_key(event->nativeVirtualKey());
  192. }
  193. if (event->isAutoRepeat())
  194. return true;
  195. hotkey.modifiers = TranslateQtKeyboardEventModifiers(event->modifiers());
  196. obs_hotkey_inject_event(hotkey, pressed);
  197. return true;
  198. };
  199. switch (event->type()) {
  200. case QEvent::MouseButtonPress:
  201. case QEvent::MouseButtonRelease:
  202. return mouse_event(*static_cast<QMouseEvent *>(event));
  203. /*case QEvent::MouseButtonDblClick:
  204. case QEvent::Wheel:*/
  205. case QEvent::KeyPress:
  206. case QEvent::KeyRelease:
  207. return key_event(static_cast<QKeyEvent *>(event));
  208. default:
  209. return false;
  210. }
  211. });
  212. }
  213. string CurrentTimeString()
  214. {
  215. using namespace std::chrono;
  216. struct tm tstruct;
  217. char buf[80];
  218. auto tp = system_clock::now();
  219. auto now = system_clock::to_time_t(tp);
  220. tstruct = *localtime(&now);
  221. size_t written = strftime(buf, sizeof(buf), "%T", &tstruct);
  222. if (ratio_less<system_clock::period, seconds::period>::value && written && (sizeof(buf) - written) > 5) {
  223. auto tp_secs = time_point_cast<seconds>(tp);
  224. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  225. snprintf(buf + written, sizeof(buf) - written, ".%03u", static_cast<unsigned>(millis));
  226. }
  227. return buf;
  228. }
  229. string CurrentDateTimeString()
  230. {
  231. time_t now = time(0);
  232. struct tm tstruct;
  233. char buf[80];
  234. tstruct = *localtime(&now);
  235. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  236. return buf;
  237. }
  238. static void LogString(fstream &logFile, const char *timeString, char *str, int log_level)
  239. {
  240. static mutex logfile_mutex;
  241. string msg;
  242. msg += timeString;
  243. msg += str;
  244. logfile_mutex.lock();
  245. logFile << msg << endl;
  246. logfile_mutex.unlock();
  247. if (!!obsLogViewer)
  248. QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine", Qt::QueuedConnection, Q_ARG(int, log_level),
  249. Q_ARG(QString, QString(msg.c_str())));
  250. }
  251. static inline void LogStringChunk(fstream &logFile, char *str, int log_level)
  252. {
  253. char *nextLine = str;
  254. string timeString = CurrentTimeString();
  255. timeString += ": ";
  256. while (*nextLine) {
  257. char *nextLine = strchr(str, '\n');
  258. if (!nextLine)
  259. break;
  260. if (nextLine != str && nextLine[-1] == '\r') {
  261. nextLine[-1] = 0;
  262. } else {
  263. nextLine[0] = 0;
  264. }
  265. LogString(logFile, timeString.c_str(), str, log_level);
  266. nextLine++;
  267. str = nextLine;
  268. }
  269. LogString(logFile, timeString.c_str(), str, log_level);
  270. }
  271. #define MAX_REPEATED_LINES 30
  272. #define MAX_CHAR_VARIATION (255 * 3)
  273. static inline int sum_chars(const char *str)
  274. {
  275. int val = 0;
  276. for (; *str != 0; str++)
  277. val += *str;
  278. return val;
  279. }
  280. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg, const char *output_str)
  281. {
  282. static mutex log_mutex;
  283. static const char *last_msg_ptr = nullptr;
  284. static int last_char_sum = 0;
  285. static int rep_count = 0;
  286. int new_sum = sum_chars(output_str);
  287. lock_guard<mutex> guard(log_mutex);
  288. if (unfiltered_log) {
  289. return false;
  290. }
  291. if (last_msg_ptr == msg) {
  292. int diff = std::abs(new_sum - last_char_sum);
  293. if (diff < MAX_CHAR_VARIATION) {
  294. return (rep_count++ >= MAX_REPEATED_LINES);
  295. }
  296. }
  297. if (rep_count > MAX_REPEATED_LINES) {
  298. logFile << CurrentTimeString() << ": Last log entry repeated for "
  299. << to_string(rep_count - MAX_REPEATED_LINES) << " more lines" << endl;
  300. }
  301. last_msg_ptr = msg;
  302. last_char_sum = new_sum;
  303. rep_count = 0;
  304. return false;
  305. }
  306. static void do_log(int log_level, const char *msg, va_list args, void *param)
  307. {
  308. fstream &logFile = *static_cast<fstream *>(param);
  309. char str[8192];
  310. #ifndef _WIN32
  311. va_list args2;
  312. va_copy(args2, args);
  313. #endif
  314. vsnprintf(str, sizeof(str), msg, args);
  315. #ifdef _WIN32
  316. if (IsDebuggerPresent()) {
  317. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  318. if (wNum > 1) {
  319. static wstring wide_buf;
  320. static mutex wide_mutex;
  321. lock_guard<mutex> lock(wide_mutex);
  322. wide_buf.reserve(wNum + 1);
  323. wide_buf.resize(wNum - 1);
  324. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0], wNum);
  325. wide_buf.push_back('\n');
  326. OutputDebugStringW(wide_buf.c_str());
  327. }
  328. }
  329. #endif
  330. #if !defined(_WIN32) && defined(_DEBUG)
  331. def_log_handler(log_level, msg, args2, nullptr);
  332. #endif
  333. if (log_level <= LOG_INFO || log_verbose) {
  334. #if !defined(_WIN32) && !defined(_DEBUG)
  335. def_log_handler(log_level, msg, args2, nullptr);
  336. #endif
  337. if (!too_many_repeated_entries(logFile, msg, str))
  338. LogStringChunk(logFile, str, log_level);
  339. }
  340. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  341. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  342. __debugbreak();
  343. #endif
  344. #ifndef _WIN32
  345. va_end(args2);
  346. #endif
  347. }
  348. #define DEFAULT_LANG "en-US"
  349. bool OBSApp::InitGlobalConfigDefaults()
  350. {
  351. config_set_default_uint(appConfig, "General", "MaxLogs", 10);
  352. config_set_default_int(appConfig, "General", "InfoIncrement", -1);
  353. config_set_default_string(appConfig, "General", "ProcessPriority", "Normal");
  354. config_set_default_bool(appConfig, "General", "EnableAutoUpdates", true);
  355. #if _WIN32
  356. config_set_default_string(appConfig, "Video", "Renderer", "Direct3D 11");
  357. #else
  358. config_set_default_string(appConfig, "Video", "Renderer", "OpenGL");
  359. #endif
  360. #ifdef _WIN32
  361. config_set_default_bool(appConfig, "Audio", "DisableAudioDucking", true);
  362. config_set_default_bool(appConfig, "General", "BrowserHWAccel", true);
  363. #endif
  364. #ifdef __APPLE__
  365. config_set_default_bool(appConfig, "General", "BrowserHWAccel", true);
  366. config_set_default_bool(appConfig, "Video", "DisableOSXVSync", true);
  367. config_set_default_bool(appConfig, "Video", "ResetOSXVSyncOnExit", true);
  368. #endif
  369. return true;
  370. }
  371. bool OBSApp::InitGlobalLocationDefaults()
  372. {
  373. char path[512];
  374. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  375. if (len <= 0) {
  376. OBSErrorBox(NULL, "Unable to get global configuration path.");
  377. return false;
  378. }
  379. config_set_default_string(appConfig, "Locations", "Configuration", path);
  380. config_set_default_string(appConfig, "Locations", "SceneCollections", path);
  381. config_set_default_string(appConfig, "Locations", "Profiles", path);
  382. return true;
  383. }
  384. void OBSApp::InitUserConfigDefaults()
  385. {
  386. config_set_default_bool(userConfig, "General", "ConfirmOnExit", true);
  387. config_set_default_string(userConfig, "General", "HotkeyFocusType", "NeverDisableHotkeys");
  388. config_set_default_bool(userConfig, "BasicWindow", "PreviewEnabled", true);
  389. config_set_default_bool(userConfig, "BasicWindow", "PreviewProgramMode", false);
  390. config_set_default_bool(userConfig, "BasicWindow", "SceneDuplicationMode", true);
  391. config_set_default_bool(userConfig, "BasicWindow", "SwapScenesMode", true);
  392. config_set_default_bool(userConfig, "BasicWindow", "SnappingEnabled", true);
  393. config_set_default_bool(userConfig, "BasicWindow", "ScreenSnapping", true);
  394. config_set_default_bool(userConfig, "BasicWindow", "SourceSnapping", true);
  395. config_set_default_bool(userConfig, "BasicWindow", "CenterSnapping", false);
  396. config_set_default_double(userConfig, "BasicWindow", "SnapDistance", 10.0);
  397. config_set_default_bool(userConfig, "BasicWindow", "SpacingHelpersEnabled", true);
  398. config_set_default_bool(userConfig, "BasicWindow", "RecordWhenStreaming", false);
  399. config_set_default_bool(userConfig, "BasicWindow", "KeepRecordingWhenStreamStops", false);
  400. config_set_default_bool(userConfig, "BasicWindow", "SysTrayEnabled", true);
  401. config_set_default_bool(userConfig, "BasicWindow", "SysTrayWhenStarted", false);
  402. config_set_default_bool(userConfig, "BasicWindow", "SaveProjectors", false);
  403. config_set_default_bool(userConfig, "BasicWindow", "ShowTransitions", true);
  404. config_set_default_bool(userConfig, "BasicWindow", "ShowListboxToolbars", true);
  405. config_set_default_bool(userConfig, "BasicWindow", "ShowStatusBar", true);
  406. config_set_default_bool(userConfig, "BasicWindow", "ShowSourceIcons", true);
  407. config_set_default_bool(userConfig, "BasicWindow", "ShowContextToolbars", true);
  408. config_set_default_bool(userConfig, "BasicWindow", "StudioModeLabels", true);
  409. config_set_default_bool(userConfig, "BasicWindow", "VerticalVolControl", false);
  410. config_set_default_bool(userConfig, "BasicWindow", "MultiviewMouseSwitch", true);
  411. config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawNames", true);
  412. config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawAreas", true);
  413. config_set_default_bool(userConfig, "BasicWindow", "MediaControlsCountdownTimer", true);
  414. }
  415. static bool do_mkdir(const char *path)
  416. {
  417. if (os_mkdirs(path) == MKDIR_ERROR) {
  418. OBSErrorBox(NULL, "Failed to create directory %s", path);
  419. return false;
  420. }
  421. return true;
  422. }
  423. static bool MakeUserDirs()
  424. {
  425. char path[512];
  426. if (GetAppConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  427. return false;
  428. if (!do_mkdir(path))
  429. return false;
  430. if (GetAppConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  431. return false;
  432. if (!do_mkdir(path))
  433. return false;
  434. if (GetAppConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  435. return false;
  436. if (!do_mkdir(path))
  437. return false;
  438. #ifdef _WIN32
  439. if (GetAppConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  440. return false;
  441. if (!do_mkdir(path))
  442. return false;
  443. #endif
  444. #ifdef WHATSNEW_ENABLED
  445. if (GetAppConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  446. return false;
  447. if (!do_mkdir(path))
  448. return false;
  449. #endif
  450. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  451. return false;
  452. if (!do_mkdir(path))
  453. return false;
  454. return true;
  455. }
  456. constexpr std::string_view OBSProfileSubDirectory = "obs-studio/basic/profiles";
  457. constexpr std::string_view OBSScenesSubDirectory = "obs-studio/basic/scenes";
  458. static bool MakeUserProfileDirs()
  459. {
  460. const std::filesystem::path userProfilePath =
  461. App()->userProfilesLocation / std::filesystem::u8path(OBSProfileSubDirectory);
  462. const std::filesystem::path userScenesPath =
  463. App()->userScenesLocation / std::filesystem::u8path(OBSScenesSubDirectory);
  464. if (!std::filesystem::exists(userProfilePath)) {
  465. try {
  466. std::filesystem::create_directories(userProfilePath);
  467. } catch (const std::filesystem::filesystem_error &error) {
  468. blog(LOG_ERROR, "Failed to create user profile directory '%s'\n%s",
  469. userProfilePath.u8string().c_str(), error.what());
  470. return false;
  471. }
  472. }
  473. if (!std::filesystem::exists(userScenesPath)) {
  474. try {
  475. std::filesystem::create_directories(userScenesPath);
  476. } catch (const std::filesystem::filesystem_error &error) {
  477. blog(LOG_ERROR, "Failed to create user scene collection directory '%s'\n%s",
  478. userScenesPath.u8string().c_str(), error.what());
  479. return false;
  480. }
  481. }
  482. return true;
  483. }
  484. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  485. {
  486. if (!layout)
  487. return false;
  488. if (astrcmpi(layout, "horizontaltop") == 0) {
  489. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  490. static_cast<int>(MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  491. return true;
  492. }
  493. if (astrcmpi(layout, "horizontalbottom") == 0) {
  494. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  495. static_cast<int>(MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  496. return true;
  497. }
  498. if (astrcmpi(layout, "verticalleft") == 0) {
  499. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  500. static_cast<int>(MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  501. return true;
  502. }
  503. if (astrcmpi(layout, "verticalright") == 0) {
  504. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  505. static_cast<int>(MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  506. return true;
  507. }
  508. return false;
  509. }
  510. bool OBSApp::InitGlobalConfig()
  511. {
  512. char path[512];
  513. int len = GetAppConfigPath(path, sizeof(path), "obs-studio/global.ini");
  514. if (len <= 0) {
  515. return false;
  516. }
  517. int errorcode = appConfig.Open(path, CONFIG_OPEN_ALWAYS);
  518. if (errorcode != CONFIG_SUCCESS) {
  519. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  520. return false;
  521. }
  522. uint32_t lastVersion = config_get_int(appConfig, "General", "LastVersion");
  523. if (lastVersion < MAKE_SEMANTIC_VERSION(31, 0, 0)) {
  524. bool migratedUserSettings = config_get_bool(appConfig, "General", "Pre31Migrated");
  525. if (!migratedUserSettings) {
  526. bool migrated = MigrateGlobalSettings();
  527. config_set_bool(appConfig, "General", "Pre31Migrated", migrated);
  528. config_save_safe(appConfig, "tmp", nullptr);
  529. }
  530. }
  531. InitGlobalConfigDefaults();
  532. InitGlobalLocationDefaults();
  533. if (IsPortableMode()) {
  534. userConfigLocation =
  535. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Configuration"));
  536. userScenesLocation =
  537. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "SceneCollections"));
  538. userProfilesLocation =
  539. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Profiles"));
  540. } else {
  541. userConfigLocation =
  542. std::filesystem::u8path(config_get_string(appConfig, "Locations", "Configuration"));
  543. userScenesLocation =
  544. std::filesystem::u8path(config_get_string(appConfig, "Locations", "SceneCollections"));
  545. userProfilesLocation = std::filesystem::u8path(config_get_string(appConfig, "Locations", "Profiles"));
  546. }
  547. bool userConfigResult = InitUserConfig(userConfigLocation, lastVersion);
  548. return userConfigResult;
  549. }
  550. bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation, uint32_t lastVersion)
  551. {
  552. bool hasChanges = false;
  553. const std::string userConfigFile = userConfigLocation.u8string() + "/obs-studio/user.ini";
  554. int errorCode = userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS);
  555. if (errorCode != CONFIG_SUCCESS) {
  556. OBSErrorBox(nullptr, "Failed to open user.ini: %d", errorCode);
  557. return false;
  558. }
  559. hasChanges = MigrateLegacySettings(lastVersion);
  560. if (!opt_starting_collection.empty()) {
  561. const OBSBasic *basic = reinterpret_cast<OBSBasic *>(GetMainWindow());
  562. const std::optional<OBSSceneCollection> foundCollection =
  563. basic->GetSceneCollectionByName(opt_starting_collection);
  564. if (foundCollection) {
  565. config_set_string(userConfig, "Basic", "SceneCollection", foundCollection.value().name.c_str());
  566. config_set_string(userConfig, "Basic", "SceneCollectionFile",
  567. foundCollection.value().fileName.c_str());
  568. hasChanges = true;
  569. }
  570. }
  571. if (!opt_starting_profile.empty()) {
  572. const OBSBasic *basic = reinterpret_cast<OBSBasic *>(GetMainWindow());
  573. const std::optional<OBSProfile> foundProfile = basic->GetProfileByName(opt_starting_profile);
  574. if (foundProfile) {
  575. config_set_string(userConfig, "Basic", "Profile", foundProfile.value().name.c_str());
  576. config_set_string(userConfig, "Basic", "ProfileDir",
  577. foundProfile.value().directoryName.c_str());
  578. hasChanges = true;
  579. }
  580. }
  581. if (hasChanges) {
  582. config_save_safe(userConfig, "tmp", nullptr);
  583. }
  584. InitUserConfigDefaults();
  585. return true;
  586. }
  587. bool OBSApp::MigrateLegacySettings(const uint32_t lastVersion)
  588. {
  589. bool hasChanges = false;
  590. const uint32_t v19 = MAKE_SEMANTIC_VERSION(19, 0, 0);
  591. const uint32_t v21 = MAKE_SEMANTIC_VERSION(21, 0, 0);
  592. const uint32_t v23 = MAKE_SEMANTIC_VERSION(23, 0, 0);
  593. const uint32_t v24 = MAKE_SEMANTIC_VERSION(24, 0, 0);
  594. const uint32_t v24_1 = MAKE_SEMANTIC_VERSION(24, 1, 0);
  595. const map<uint32_t, string> defaultsMap{
  596. {{v19, "Pre19Defaults"}, {v21, "Pre21Defaults"}, {v23, "Pre23Defaults"}, {v24_1, "Pre24.1Defaults"}}};
  597. for (auto &[version, configKey] : defaultsMap) {
  598. if (!config_has_user_value(userConfig, "General", configKey.c_str())) {
  599. bool useOldDefaults = lastVersion && lastVersion < version;
  600. config_set_bool(userConfig, "General", configKey.c_str(), useOldDefaults);
  601. hasChanges = true;
  602. }
  603. }
  604. if (config_has_user_value(userConfig, "BasicWindow", "MultiviewLayout")) {
  605. const char *layout = config_get_string(userConfig, "BasicWindow", "MultiviewLayout");
  606. bool layoutUpdated = UpdatePre22MultiviewLayout(layout);
  607. hasChanges = hasChanges | layoutUpdated;
  608. }
  609. if (lastVersion && lastVersion < v24) {
  610. bool disableHotkeysInFocus = config_get_bool(userConfig, "General", "DisableHotkeysInFocus");
  611. if (disableHotkeysInFocus) {
  612. config_set_string(userConfig, "General", "HotkeyFocusType", "DisableHotkeysInFocus");
  613. }
  614. hasChanges = true;
  615. }
  616. return hasChanges;
  617. }
  618. static constexpr string_view OBSGlobalIniPath = "/obs-studio/global.ini";
  619. static constexpr string_view OBSUserIniPath = "/obs-studio/user.ini";
  620. bool OBSApp::MigrateGlobalSettings()
  621. {
  622. char path[512];
  623. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  624. if (len <= 0) {
  625. OBSErrorBox(nullptr, "Unable to get global configuration path.");
  626. return false;
  627. }
  628. std::string legacyConfigFileString;
  629. legacyConfigFileString.reserve(strlen(path) + OBSGlobalIniPath.size());
  630. legacyConfigFileString.append(path).append(OBSGlobalIniPath);
  631. const std::filesystem::path legacyGlobalConfigFile = std::filesystem::u8path(legacyConfigFileString);
  632. std::string configFileString;
  633. configFileString.reserve(strlen(path) + OBSUserIniPath.size());
  634. configFileString.append(path).append(OBSUserIniPath);
  635. const std::filesystem::path userConfigFile = std::filesystem::u8path(configFileString);
  636. if (std::filesystem::exists(userConfigFile)) {
  637. OBSErrorBox(nullptr,
  638. "Unable to migrate global configuration - user configuration file already exists.");
  639. return false;
  640. }
  641. std::filesystem::copy(legacyGlobalConfigFile, userConfigFile);
  642. return true;
  643. }
  644. bool OBSApp::InitLocale()
  645. {
  646. ProfileScope("OBSApp::InitLocale");
  647. const char *lang = config_get_string(userConfig, "General", "Language");
  648. bool userLocale = config_has_user_value(userConfig, "General", "Language");
  649. if (!userLocale || !lang || lang[0] == '\0')
  650. lang = DEFAULT_LANG;
  651. locale = lang;
  652. // set basic default application locale
  653. if (!locale.empty())
  654. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  655. string englishPath;
  656. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  657. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  658. return false;
  659. }
  660. textLookup = text_lookup_create(englishPath.c_str());
  661. if (!textLookup) {
  662. OBSErrorBox(NULL, "Failed to create locale from file '%s'", englishPath.c_str());
  663. return false;
  664. }
  665. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  666. if (userLocale && defaultLang)
  667. return true;
  668. if (!userLocale && defaultLang) {
  669. for (auto &locale_ : GetPreferredLocales()) {
  670. if (locale_ == lang)
  671. return true;
  672. stringstream file;
  673. file << "locale/" << locale_ << ".ini";
  674. string path;
  675. if (!GetDataFilePath(file.str().c_str(), path))
  676. continue;
  677. if (!text_lookup_add(textLookup, path.c_str()))
  678. continue;
  679. blog(LOG_INFO, "Using preferred locale '%s'", locale_.c_str());
  680. locale = locale_;
  681. // set application default locale to the new choosen one
  682. if (!locale.empty())
  683. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  684. return true;
  685. }
  686. return true;
  687. }
  688. stringstream file;
  689. file << "locale/" << lang << ".ini";
  690. string path;
  691. if (GetDataFilePath(file.str().c_str(), path)) {
  692. if (!text_lookup_add(textLookup, path.c_str()))
  693. blog(LOG_ERROR, "Failed to add locale file '%s'", path.c_str());
  694. } else {
  695. blog(LOG_ERROR, "Could not find locale file '%s'", file.str().c_str());
  696. }
  697. return true;
  698. }
  699. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  700. void ParseBranchesJson(const std::string &jsonString, vector<UpdateBranch> &out, std::string &error)
  701. {
  702. JsonBranches branches;
  703. try {
  704. nlohmann::json json = nlohmann::json::parse(jsonString);
  705. branches = json.get<JsonBranches>();
  706. } catch (nlohmann::json::exception &e) {
  707. error = e.what();
  708. return;
  709. }
  710. for (const JsonBranch &json_branch : branches) {
  711. #ifdef _WIN32
  712. if (!json_branch.windows)
  713. continue;
  714. #elif defined(__APPLE__)
  715. if (!json_branch.macos)
  716. continue;
  717. #endif
  718. UpdateBranch branch = {
  719. QString::fromStdString(json_branch.name),
  720. QString::fromStdString(json_branch.display_name),
  721. QString::fromStdString(json_branch.description),
  722. json_branch.enabled,
  723. json_branch.visible,
  724. };
  725. out.push_back(branch);
  726. }
  727. }
  728. bool LoadBranchesFile(vector<UpdateBranch> &out)
  729. {
  730. string error;
  731. string branchesText;
  732. BPtr<char> branchesFilePath = GetAppConfigPathPtr("obs-studio/updates/branches.json");
  733. QFile branchesFile(branchesFilePath.Get());
  734. if (!branchesFile.open(QIODevice::ReadOnly)) {
  735. error = "Opening file failed.";
  736. goto fail;
  737. }
  738. branchesText = branchesFile.readAll();
  739. if (branchesText.empty()) {
  740. error = "File empty.";
  741. goto fail;
  742. }
  743. ParseBranchesJson(branchesText, out, error);
  744. if (error.empty())
  745. return !out.empty();
  746. fail:
  747. blog(LOG_WARNING, "Loading branches from file failed: %s", error.c_str());
  748. return false;
  749. }
  750. #endif
  751. void OBSApp::SetBranchData(const string &data)
  752. {
  753. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  754. string error;
  755. vector<UpdateBranch> result;
  756. ParseBranchesJson(data, result, error);
  757. if (!error.empty()) {
  758. blog(LOG_WARNING, "Reading branches JSON response failed: %s", error.c_str());
  759. return;
  760. }
  761. if (!result.empty())
  762. updateBranches = result;
  763. branches_loaded = true;
  764. #else
  765. UNUSED_PARAMETER(data);
  766. #endif
  767. }
  768. std::vector<UpdateBranch> OBSApp::GetBranches()
  769. {
  770. vector<UpdateBranch> out;
  771. /* Always ensure the default branch exists */
  772. out.push_back(UpdateBranch{"stable", "", "", true, true});
  773. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  774. if (!branches_loaded) {
  775. vector<UpdateBranch> result;
  776. if (LoadBranchesFile(result))
  777. updateBranches = result;
  778. branches_loaded = true;
  779. }
  780. #endif
  781. /* Copy additional branches to result (if any) */
  782. if (!updateBranches.empty())
  783. out.insert(out.end(), updateBranches.begin(), updateBranches.end());
  784. return out;
  785. }
  786. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  787. : QApplication(argc, argv),
  788. profilerNameStore(store)
  789. {
  790. /* fix float handling */
  791. #if defined(Q_OS_UNIX)
  792. if (!setlocale(LC_NUMERIC, "C"))
  793. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  794. #endif
  795. #ifndef _WIN32
  796. /* Handle SIGINT properly */
  797. socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd);
  798. snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
  799. connect(snInt, &QSocketNotifier::activated, this, &OBSApp::ProcessSigInt);
  800. #else
  801. connect(qApp, &QGuiApplication::commitDataRequest, this, &OBSApp::commitData);
  802. #endif
  803. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  804. #ifndef __APPLE__
  805. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  806. #endif
  807. setDesktopFileName("com.obsproject.Studio");
  808. }
  809. OBSApp::~OBSApp()
  810. {
  811. #ifdef _WIN32
  812. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  813. if (disableAudioDucking)
  814. DisableAudioDucking(false);
  815. #else
  816. delete snInt;
  817. close(sigintFd[0]);
  818. close(sigintFd[1]);
  819. #endif
  820. #ifdef __APPLE__
  821. bool vsyncDisabled = config_get_bool(appConfig, "Video", "DisableOSXVSync");
  822. bool resetVSync = config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit");
  823. if (vsyncDisabled && resetVSync)
  824. EnableOSXVSync(true);
  825. #endif
  826. os_inhibit_sleep_set_active(sleepInhibitor, false);
  827. os_inhibit_sleep_destroy(sleepInhibitor);
  828. if (libobs_initialized)
  829. obs_shutdown();
  830. }
  831. static void move_basic_to_profiles(void)
  832. {
  833. char path[512];
  834. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  835. return;
  836. }
  837. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  838. if (!std::filesystem::exists(basicPath)) {
  839. return;
  840. }
  841. const std::filesystem::path profilesPath =
  842. App()->userProfilesLocation / std::filesystem::u8path("obs-studio/basic/profiles");
  843. if (std::filesystem::exists(profilesPath)) {
  844. return;
  845. }
  846. try {
  847. std::filesystem::create_directories(profilesPath);
  848. } catch (const std::filesystem::filesystem_error &error) {
  849. blog(LOG_ERROR, "Failed to create profiles directory for migration from basic profile\n%s",
  850. error.what());
  851. return;
  852. }
  853. const std::filesystem::path newProfilePath = profilesPath / std::filesystem::u8path(Str("Untitled"));
  854. for (auto &entry : std::filesystem::directory_iterator(basicPath)) {
  855. if (entry.is_directory()) {
  856. continue;
  857. }
  858. if (entry.path().filename().u8string() == "scenes.json") {
  859. continue;
  860. }
  861. if (!std::filesystem::exists(newProfilePath)) {
  862. try {
  863. std::filesystem::create_directory(newProfilePath);
  864. } catch (const std::filesystem::filesystem_error &error) {
  865. blog(LOG_ERROR, "Failed to create profile directory for 'Untitled'\n%s", error.what());
  866. return;
  867. }
  868. }
  869. const filesystem::path destinationFile = newProfilePath / entry.path().filename();
  870. const auto copyOptions = std::filesystem::copy_options::overwrite_existing;
  871. try {
  872. std::filesystem::copy(entry.path(), destinationFile, copyOptions);
  873. } catch (const std::filesystem::filesystem_error &error) {
  874. blog(LOG_ERROR, "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s",
  875. entry.path().filename().u8string().c_str(), error.what());
  876. return;
  877. }
  878. }
  879. }
  880. static void move_basic_to_scene_collections(void)
  881. {
  882. char path[512];
  883. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  884. return;
  885. }
  886. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  887. if (!std::filesystem::exists(basicPath)) {
  888. return;
  889. }
  890. const std::filesystem::path sceneCollectionPath =
  891. App()->userScenesLocation / std::filesystem::u8path("obs-studio/basic/scenes");
  892. if (std::filesystem::exists(sceneCollectionPath)) {
  893. return;
  894. }
  895. try {
  896. std::filesystem::create_directories(sceneCollectionPath);
  897. } catch (const std::filesystem::filesystem_error &error) {
  898. blog(LOG_ERROR,
  899. "Failed to create scene collection directory for migration from basic scene collection\n%s",
  900. error.what());
  901. return;
  902. }
  903. const std::filesystem::path sourceFile = basicPath / std::filesystem::u8path("scenes.json");
  904. const std::filesystem::path destinationFile =
  905. (sceneCollectionPath / std::filesystem::u8path(Str("Untitled"))).replace_extension(".json");
  906. try {
  907. std::filesystem::rename(sourceFile, destinationFile);
  908. } catch (const std::filesystem::filesystem_error &error) {
  909. blog(LOG_ERROR, "Failed to rename basic scene collection file:\n%s", error.what());
  910. return;
  911. }
  912. }
  913. void OBSApp::AppInit()
  914. {
  915. ProfileScope("OBSApp::AppInit");
  916. if (!MakeUserDirs())
  917. throw "Failed to create required user directories";
  918. if (!InitGlobalConfig())
  919. throw "Failed to initialize global config";
  920. if (!InitLocale())
  921. throw "Failed to load locale";
  922. if (!InitTheme())
  923. throw "Failed to load theme";
  924. config_set_default_string(userConfig, "Basic", "Profile", Str("Untitled"));
  925. config_set_default_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  926. config_set_default_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  927. config_set_default_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  928. config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile", true);
  929. if (!config_has_user_value(userConfig, "Basic", "Profile")) {
  930. config_set_string(userConfig, "Basic", "Profile", Str("Untitled"));
  931. config_set_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  932. }
  933. if (!config_has_user_value(userConfig, "Basic", "SceneCollection")) {
  934. config_set_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  935. config_set_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  936. }
  937. #ifdef _WIN32
  938. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  939. if (disableAudioDucking)
  940. DisableAudioDucking(true);
  941. #endif
  942. #ifdef __APPLE__
  943. if (config_get_bool(appConfig, "Video", "DisableOSXVSync"))
  944. EnableOSXVSync(false);
  945. #endif
  946. UpdateHotkeyFocusSetting(false);
  947. move_basic_to_profiles();
  948. move_basic_to_scene_collections();
  949. if (!MakeUserProfileDirs())
  950. throw "Failed to create profile directories";
  951. }
  952. const char *OBSApp::GetRenderModule() const
  953. {
  954. const char *renderer = config_get_string(appConfig, "Video", "Renderer");
  955. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  956. }
  957. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  958. {
  959. char path[512];
  960. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  961. return false;
  962. return obs_startup(locale, path, store);
  963. }
  964. inline void OBSApp::ResetHotkeyState(bool inFocus)
  965. {
  966. obs_hotkey_enable_background_press((inFocus && enableHotkeysInFocus) || (!inFocus && enableHotkeysOutOfFocus));
  967. }
  968. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  969. {
  970. enableHotkeysInFocus = true;
  971. enableHotkeysOutOfFocus = true;
  972. const char *hotkeyFocusType = config_get_string(userConfig, "General", "HotkeyFocusType");
  973. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  974. enableHotkeysInFocus = false;
  975. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  976. enableHotkeysOutOfFocus = false;
  977. }
  978. if (resetState)
  979. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  980. }
  981. void OBSApp::DisableHotkeys()
  982. {
  983. enableHotkeysInFocus = false;
  984. enableHotkeysOutOfFocus = false;
  985. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  986. }
  987. Q_DECLARE_METATYPE(VoidFunc)
  988. void OBSApp::Exec(VoidFunc func)
  989. {
  990. func();
  991. }
  992. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  993. {
  994. auto doTask = [=]() {
  995. /* to get clang-format to behave */
  996. task(param);
  997. };
  998. QMetaObject::invokeMethod(App(), "Exec", wait ? WaitConnection() : Qt::AutoConnection, Q_ARG(VoidFunc, doTask));
  999. }
  1000. bool OBSApp::OBSInit()
  1001. {
  1002. ProfileScope("OBSApp::OBSInit");
  1003. qRegisterMetaType<VoidFunc>("VoidFunc");
  1004. #if !defined(_WIN32) && !defined(__APPLE__)
  1005. if (QApplication::platformName() == "xcb") {
  1006. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  1007. blog(LOG_INFO, "Using EGL/X11");
  1008. }
  1009. #ifdef ENABLE_WAYLAND
  1010. if (QApplication::platformName().contains("wayland")) {
  1011. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  1012. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1013. blog(LOG_INFO, "Platform: Wayland");
  1014. }
  1015. #endif
  1016. QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();
  1017. obs_set_nix_platform_display(native->nativeResourceForIntegration("display"));
  1018. #endif
  1019. #ifdef __APPLE__
  1020. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1021. #endif
  1022. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1023. return false;
  1024. libobs_initialized = true;
  1025. obs_set_ui_task_handler(ui_task_handler);
  1026. #if defined(_WIN32) || defined(__APPLE__)
  1027. bool browserHWAccel = config_get_bool(userConfig, "General", "BrowserHWAccel");
  1028. OBSDataAutoRelease settings = obs_data_create();
  1029. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1030. obs_apply_private_data(settings);
  1031. blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str());
  1032. blog(LOG_INFO, "Browser Hardware Acceleration: %s", browserHWAccel ? "true" : "false");
  1033. #endif
  1034. #ifdef _WIN32
  1035. bool hideFromCapture = config_get_bool(userConfig, "BasicWindow", "HideOBSWindowsFromCapture");
  1036. blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hideFromCapture ? "true" : "false");
  1037. #endif
  1038. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(), QT_VERSION_STR);
  1039. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1040. if (safe_mode) {
  1041. blog(LOG_WARNING, "Safe Mode enabled.");
  1042. } else if (disable_3p_plugins) {
  1043. blog(LOG_WARNING, "Third-party plugins disabled.");
  1044. }
  1045. setQuitOnLastWindowClosed(false);
  1046. mainWindow = new OBSBasic();
  1047. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1048. connect(mainWindow, &OBSBasic::destroyed, this, &OBSApp::quit);
  1049. mainWindow->OBSInit();
  1050. connect(this, &QGuiApplication::applicationStateChanged,
  1051. [this](Qt::ApplicationState state) { ResetHotkeyState(state == Qt::ApplicationActive); });
  1052. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1053. return true;
  1054. }
  1055. string OBSApp::GetVersionString(bool platform) const
  1056. {
  1057. stringstream ver;
  1058. #ifdef HAVE_OBSCONFIG_H
  1059. ver << obs_get_version_string();
  1060. #else
  1061. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "." << LIBOBS_API_PATCH_VER;
  1062. #endif
  1063. if (platform) {
  1064. ver << " (";
  1065. #ifdef _WIN32
  1066. if (sizeof(void *) == 8)
  1067. ver << "64-bit, ";
  1068. else
  1069. ver << "32-bit, ";
  1070. ver << "windows)";
  1071. #elif __APPLE__
  1072. ver << "mac)";
  1073. #elif __OpenBSD__
  1074. ver << "openbsd)";
  1075. #elif __FreeBSD__
  1076. ver << "freebsd)";
  1077. #else /* assume linux for the time being */
  1078. ver << "linux)";
  1079. #endif
  1080. }
  1081. return ver.str();
  1082. }
  1083. bool OBSApp::IsPortableMode()
  1084. {
  1085. return portable_mode;
  1086. }
  1087. bool OBSApp::IsUpdaterDisabled()
  1088. {
  1089. return opt_disable_updater;
  1090. }
  1091. bool OBSApp::IsMissingFilesCheckDisabled()
  1092. {
  1093. return opt_disable_missing_files_check;
  1094. }
  1095. #ifdef __APPLE__
  1096. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1097. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1098. #elif _WIN32
  1099. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1100. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1101. #else
  1102. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1103. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1104. #endif
  1105. const char *OBSApp::InputAudioSource() const
  1106. {
  1107. return INPUT_AUDIO_SOURCE;
  1108. }
  1109. const char *OBSApp::OutputAudioSource() const
  1110. {
  1111. return OUTPUT_AUDIO_SOURCE;
  1112. }
  1113. const char *OBSApp::GetLastLog() const
  1114. {
  1115. return lastLogFile.c_str();
  1116. }
  1117. const char *OBSApp::GetCurrentLog() const
  1118. {
  1119. return currentLogFile.c_str();
  1120. }
  1121. const char *OBSApp::GetLastCrashLog() const
  1122. {
  1123. return lastCrashLogFile.c_str();
  1124. }
  1125. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1126. {
  1127. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1128. if (cb(lookupVal, out))
  1129. return true;
  1130. }
  1131. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1132. }
  1133. // Global handler to receive all QEvent::Show events so we can apply
  1134. // display affinity on any newly created windows and dialogs without
  1135. // caring where they are coming from (e.g. plugins).
  1136. bool OBSApp::notify(QObject *receiver, QEvent *e)
  1137. {
  1138. QWidget *w;
  1139. QWindow *window;
  1140. int windowType;
  1141. if (!receiver->isWidgetType())
  1142. goto skip;
  1143. if (e->type() != QEvent::Show)
  1144. goto skip;
  1145. w = qobject_cast<QWidget *>(receiver);
  1146. if (!w->isWindow())
  1147. goto skip;
  1148. window = w->windowHandle();
  1149. if (!window)
  1150. goto skip;
  1151. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  1152. if (windowType == Qt::WindowType::Dialog || windowType == Qt::WindowType::Window ||
  1153. windowType == Qt::WindowType::Tool) {
  1154. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1155. if (main)
  1156. main->SetDisplayAffinity(window);
  1157. }
  1158. skip:
  1159. return QApplication::notify(receiver, e);
  1160. }
  1161. QString OBSTranslator::translate(const char *, const char *sourceText, const char *, int) const
  1162. {
  1163. const char *out = nullptr;
  1164. QString str(sourceText);
  1165. str.replace(" ", "");
  1166. if (!App()->TranslateString(QT_TO_UTF8(str), &out))
  1167. return QString(sourceText);
  1168. return QT_UTF8(out);
  1169. }
  1170. static bool get_token(lexer *lex, string &str, base_token_type type)
  1171. {
  1172. base_token token;
  1173. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1174. return false;
  1175. if (token.type != type)
  1176. return false;
  1177. str.assign(token.text.array, token.text.len);
  1178. return true;
  1179. }
  1180. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1181. {
  1182. base_token token;
  1183. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1184. return false;
  1185. if (token.type != type)
  1186. return false;
  1187. return strref_cmp(&token.text, str) == 0;
  1188. }
  1189. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1190. {
  1191. BaseLexer lex;
  1192. string year, month, day, hour, minute, second;
  1193. lexer_start(lex, name);
  1194. if (has_prefix) {
  1195. string temp;
  1196. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1197. return 0;
  1198. }
  1199. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1200. return 0;
  1201. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1202. return 0;
  1203. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1204. return 0;
  1205. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1206. return 0;
  1207. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1208. return 0;
  1209. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1210. return 0;
  1211. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1212. return 0;
  1213. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1214. return 0;
  1215. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1216. return 0;
  1217. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1218. return 0;
  1219. stringstream timestring;
  1220. timestring << year << month << day << hour << minute << second;
  1221. return std::stoull(timestring.str());
  1222. }
  1223. static void delete_oldest_file(bool has_prefix, const char *location)
  1224. {
  1225. BPtr<char> logDir(GetAppConfigPathPtr(location));
  1226. string oldestLog;
  1227. uint64_t oldest_ts = (uint64_t)-1;
  1228. struct os_dirent *entry;
  1229. unsigned int maxLogs = (unsigned int)config_get_uint(App()->GetUserConfig(), "General", "MaxLogs");
  1230. os_dir_t *dir = os_opendir(logDir);
  1231. if (dir) {
  1232. unsigned int count = 0;
  1233. while ((entry = os_readdir(dir)) != NULL) {
  1234. if (entry->directory || *entry->d_name == '.')
  1235. continue;
  1236. uint64_t ts = convert_log_name(has_prefix, entry->d_name);
  1237. if (ts) {
  1238. if (ts < oldest_ts) {
  1239. oldestLog = entry->d_name;
  1240. oldest_ts = ts;
  1241. }
  1242. count++;
  1243. }
  1244. }
  1245. os_closedir(dir);
  1246. if (count > maxLogs) {
  1247. stringstream delPath;
  1248. delPath << logDir << "/" << oldestLog;
  1249. os_unlink(delPath.str().c_str());
  1250. }
  1251. }
  1252. }
  1253. static void get_last_log(bool has_prefix, const char *subdir_to_use, std::string &last)
  1254. {
  1255. BPtr<char> logDir(GetAppConfigPathPtr(subdir_to_use));
  1256. struct os_dirent *entry;
  1257. os_dir_t *dir = os_opendir(logDir);
  1258. uint64_t highest_ts = 0;
  1259. if (dir) {
  1260. while ((entry = os_readdir(dir)) != NULL) {
  1261. if (entry->directory || *entry->d_name == '.')
  1262. continue;
  1263. uint64_t ts = convert_log_name(has_prefix, entry->d_name);
  1264. if (ts > highest_ts) {
  1265. last = entry->d_name;
  1266. highest_ts = ts;
  1267. }
  1268. }
  1269. os_closedir(dir);
  1270. }
  1271. }
  1272. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1273. {
  1274. time_t now = time(0);
  1275. char file[256] = {};
  1276. struct tm *cur_time;
  1277. cur_time = localtime(&now);
  1278. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s", cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1279. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour, cur_time->tm_min, cur_time->tm_sec,
  1280. extension);
  1281. return string(file);
  1282. }
  1283. string GenerateSpecifiedFilename(const char *extension, bool noSpace, const char *format)
  1284. {
  1285. BPtr<char> filename = os_generate_formatted_filename(extension, !noSpace, format);
  1286. return string(filename);
  1287. }
  1288. static void FindBestFilename(string &strPath, bool noSpace)
  1289. {
  1290. int num = 2;
  1291. if (!os_file_exists(strPath.c_str()))
  1292. return;
  1293. const char *ext = strrchr(strPath.c_str(), '.');
  1294. if (!ext)
  1295. return;
  1296. int extStart = int(ext - strPath.c_str());
  1297. for (;;) {
  1298. string testPath = strPath;
  1299. string numStr;
  1300. numStr = noSpace ? "_" : " (";
  1301. numStr += to_string(num++);
  1302. if (!noSpace)
  1303. numStr += ")";
  1304. testPath.insert(extStart, numStr);
  1305. if (!os_file_exists(testPath.c_str())) {
  1306. strPath = testPath;
  1307. break;
  1308. }
  1309. }
  1310. }
  1311. static void ensure_directory_exists(string &path)
  1312. {
  1313. replace(path.begin(), path.end(), '\\', '/');
  1314. size_t last = path.rfind('/');
  1315. if (last == string::npos)
  1316. return;
  1317. string directory = path.substr(0, last);
  1318. os_mkdirs(directory.c_str());
  1319. }
  1320. static void remove_reserved_file_characters(string &s)
  1321. {
  1322. replace(s.begin(), s.end(), '\\', '/');
  1323. replace(s.begin(), s.end(), '*', '_');
  1324. replace(s.begin(), s.end(), '?', '_');
  1325. replace(s.begin(), s.end(), '"', '_');
  1326. replace(s.begin(), s.end(), '|', '_');
  1327. replace(s.begin(), s.end(), ':', '_');
  1328. replace(s.begin(), s.end(), '>', '_');
  1329. replace(s.begin(), s.end(), '<', '_');
  1330. }
  1331. string GetFormatString(const char *format, const char *prefix, const char *suffix)
  1332. {
  1333. string f;
  1334. f = format;
  1335. if (prefix && *prefix) {
  1336. string str_prefix = prefix;
  1337. if (str_prefix.back() != ' ')
  1338. str_prefix += " ";
  1339. size_t insert_pos = 0;
  1340. size_t tmp;
  1341. tmp = f.find_last_of('/');
  1342. if (tmp != string::npos && tmp > insert_pos)
  1343. insert_pos = tmp + 1;
  1344. tmp = f.find_last_of('\\');
  1345. if (tmp != string::npos && tmp > insert_pos)
  1346. insert_pos = tmp + 1;
  1347. f.insert(insert_pos, str_prefix);
  1348. }
  1349. if (suffix && *suffix) {
  1350. if (*suffix != ' ')
  1351. f += " ";
  1352. f += suffix;
  1353. }
  1354. remove_reserved_file_characters(f);
  1355. return f;
  1356. }
  1357. string GetFormatExt(const char *container)
  1358. {
  1359. string ext = container;
  1360. if (ext == "fragmented_mp4")
  1361. ext = "mp4";
  1362. if (ext == "hybrid_mp4")
  1363. ext = "mp4";
  1364. else if (ext == "fragmented_mov")
  1365. ext = "mov";
  1366. else if (ext == "hls")
  1367. ext = "m3u8";
  1368. else if (ext == "mpegts")
  1369. ext = "ts";
  1370. return ext;
  1371. }
  1372. string GetOutputFilename(const char *path, const char *container, bool noSpace, bool overwrite, const char *format)
  1373. {
  1374. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1375. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1376. if (!dir) {
  1377. if (main->isVisible())
  1378. OBSMessageBox::warning(main, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text"));
  1379. else
  1380. main->SysTrayNotify(QTStr("Output.BadPath.Text"), QSystemTrayIcon::Warning);
  1381. return "";
  1382. }
  1383. os_closedir(dir);
  1384. string strPath;
  1385. strPath += path;
  1386. char lastChar = strPath.back();
  1387. if (lastChar != '/' && lastChar != '\\')
  1388. strPath += "/";
  1389. string ext = GetFormatExt(container);
  1390. strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format);
  1391. ensure_directory_exists(strPath);
  1392. if (!overwrite)
  1393. FindBestFilename(strPath, noSpace);
  1394. return strPath;
  1395. }
  1396. vector<pair<string, string>> GetLocaleNames()
  1397. {
  1398. string path;
  1399. if (!GetDataFilePath("locale.ini", path))
  1400. throw "Could not find locale.ini path";
  1401. ConfigFile ini;
  1402. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1403. throw "Could not open locale.ini";
  1404. size_t sections = config_num_sections(ini);
  1405. vector<pair<string, string>> names;
  1406. names.reserve(sections);
  1407. for (size_t i = 0; i < sections; i++) {
  1408. const char *tag = config_get_section(ini, i);
  1409. const char *name = config_get_string(ini, tag, "Name");
  1410. names.emplace_back(tag, name);
  1411. }
  1412. return names;
  1413. }
  1414. static void create_log_file(fstream &logFile)
  1415. {
  1416. stringstream dst;
  1417. get_last_log(false, "obs-studio/logs", lastLogFile);
  1418. #ifdef _WIN32
  1419. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1420. #endif
  1421. currentLogFile = GenerateTimeDateFilename("txt");
  1422. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1423. BPtr<char> path(GetAppConfigPathPtr(dst.str().c_str()));
  1424. #ifdef _WIN32
  1425. BPtr<wchar_t> wpath;
  1426. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1427. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1428. #else
  1429. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1430. #endif
  1431. if (logFile.is_open()) {
  1432. delete_oldest_file(false, "obs-studio/logs");
  1433. base_set_log_handler(do_log, &logFile);
  1434. } else {
  1435. blog(LOG_ERROR, "Failed to open log file");
  1436. }
  1437. }
  1438. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1439. profiler_name_store_free(store);
  1440. };
  1441. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t, decltype(ProfilerNameStoreRelease)>;
  1442. ProfilerNameStore CreateNameStore()
  1443. {
  1444. return ProfilerNameStore{profiler_name_store_create(), ProfilerNameStoreRelease};
  1445. }
  1446. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1447. profile_snapshot_free(snap);
  1448. };
  1449. using ProfilerSnapshot = std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1450. ProfilerSnapshot GetSnapshot()
  1451. {
  1452. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1453. }
  1454. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1455. {
  1456. if (currentLogFile.empty())
  1457. return;
  1458. auto pos = currentLogFile.rfind('.');
  1459. if (pos == currentLogFile.npos)
  1460. return;
  1461. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1462. ostringstream dst;
  1463. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1464. dst.write(currentLogFile.c_str(), pos);
  1465. dst.write(LITERAL_SIZE(".csv.gz"));
  1466. #undef LITERAL_SIZE
  1467. BPtr<char> path = GetAppConfigPathPtr(dst.str().c_str());
  1468. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1469. blog(LOG_WARNING, "Could not save profiler data to '%s'", static_cast<const char *>(path));
  1470. }
  1471. static auto ProfilerFree = [](void *) {
  1472. profiler_stop();
  1473. auto snap = GetSnapshot();
  1474. profiler_print(snap.get());
  1475. profiler_print_time_between_calls(snap.get());
  1476. SaveProfilerData(snap);
  1477. profiler_free();
  1478. };
  1479. QAccessibleInterface *accessibleFactory(const QString &classname, QObject *object)
  1480. {
  1481. if (classname == QLatin1String("VolumeSlider") && object && object->isWidgetType())
  1482. return new VolumeAccessibleInterface(static_cast<QWidget *>(object));
  1483. return nullptr;
  1484. }
  1485. static const char *run_program_init = "run_program_init";
  1486. static int run_program(fstream &logFile, int argc, char *argv[])
  1487. {
  1488. int ret = -1;
  1489. auto profilerNameStore = CreateNameStore();
  1490. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(static_cast<void *>(&ProfilerFree), ProfilerFree);
  1491. profiler_start();
  1492. profile_register_root(run_program_init, 0);
  1493. ScopeProfiler prof{run_program_init};
  1494. #ifdef _WIN32
  1495. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1496. #endif
  1497. QCoreApplication::addLibraryPath(".");
  1498. #if __APPLE__
  1499. InstallNSApplicationSubclass();
  1500. InstallNSThreadLocks();
  1501. if (!isInBundle()) {
  1502. blog(LOG_ERROR,
  1503. "OBS cannot be run as a standalone binary on macOS. Run the Application bundle instead.");
  1504. return ret;
  1505. }
  1506. #endif
  1507. #if !defined(_WIN32) && !defined(__APPLE__)
  1508. /* NOTE: Users blindly set this, but this theme is incompatble with Qt6 and
  1509. * crashes loading saved geometry. Just turn off this theme and let users complain OBS
  1510. * looks ugly instead of crashing. */
  1511. const char *platform_theme = getenv("QT_QPA_PLATFORMTHEME");
  1512. if (platform_theme && strcmp(platform_theme, "qt5ct") == 0)
  1513. unsetenv("QT_QPA_PLATFORMTHEME");
  1514. #endif
  1515. /* NOTE: This disables an optimisation in Qt that attempts to determine if
  1516. * any "siblings" intersect with a widget when determining the approximate
  1517. * visible/unobscured area. However, by Qt's own admission this is slow
  1518. * and in the case of OBS it significantly slows down lists with many
  1519. * elements (e.g. Hotkeys) and it is actually faster to disable it. */
  1520. qputenv("QT_NO_SUBTRACTOPAQUESIBLINGS", "1");
  1521. OBSApp program(argc, argv, profilerNameStore.get());
  1522. try {
  1523. QAccessible::installFactory(accessibleFactory);
  1524. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Regular.ttf");
  1525. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Bold.ttf");
  1526. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Italic.ttf");
  1527. bool created_log = false;
  1528. program.AppInit();
  1529. delete_oldest_file(false, "obs-studio/profiler_data");
  1530. OBSTranslator translator;
  1531. program.installTranslator(&translator);
  1532. /* --------------------------------------- */
  1533. /* check and warn if already running */
  1534. bool cancel_launch = false;
  1535. bool already_running = false;
  1536. #ifdef _WIN32
  1537. RunOnceMutex rom =
  1538. #endif
  1539. CheckIfAlreadyRunning(already_running);
  1540. if (!already_running) {
  1541. goto run;
  1542. }
  1543. if (!multi) {
  1544. QMessageBox mb(QMessageBox::Question, QTStr("AlreadyRunning.Title"),
  1545. QTStr("AlreadyRunning.Text"));
  1546. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::YesRole);
  1547. QPushButton *cancelButton = mb.addButton(QTStr("Cancel"), QMessageBox::NoRole);
  1548. mb.setDefaultButton(cancelButton);
  1549. mb.exec();
  1550. cancel_launch = mb.clickedButton() == cancelButton;
  1551. }
  1552. if (cancel_launch)
  1553. return 0;
  1554. if (!created_log) {
  1555. create_log_file(logFile);
  1556. created_log = true;
  1557. }
  1558. if (multi) {
  1559. blog(LOG_INFO, "User enabled --multi flag and is now "
  1560. "running multiple instances of OBS.");
  1561. } else {
  1562. blog(LOG_WARNING, "================================");
  1563. blog(LOG_WARNING, "Warning: OBS is already running!");
  1564. blog(LOG_WARNING, "================================");
  1565. blog(LOG_WARNING, "User is now running multiple "
  1566. "instances of OBS!");
  1567. /* Clear unclean_shutdown flag as multiple instances
  1568. * running from the same config will lead to a
  1569. * false-positive detection.*/
  1570. unclean_shutdown = false;
  1571. }
  1572. /* --------------------------------------- */
  1573. run:
  1574. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1575. // Mounted by termina during chromeOS linux container startup
  1576. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1577. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1578. if (crosDir) {
  1579. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1580. QMessageBox mb(QMessageBox::Critical, QTStr("ChromeOS.Title"), QTStr("ChromeOS.Text"), buttons,
  1581. nullptr);
  1582. mb.exec();
  1583. return 0;
  1584. }
  1585. #endif
  1586. if (!created_log)
  1587. create_log_file(logFile);
  1588. if (unclean_shutdown) {
  1589. blog(LOG_WARNING, "[Safe Mode] Unclean shutdown detected!");
  1590. }
  1591. if (unclean_shutdown && !safe_mode) {
  1592. QMessageBox mb(QMessageBox::Warning, QTStr("AutoSafeMode.Title"), QTStr("AutoSafeMode.Text"));
  1593. QPushButton *launchSafeButton =
  1594. mb.addButton(QTStr("AutoSafeMode.LaunchSafe"), QMessageBox::AcceptRole);
  1595. QPushButton *launchNormalButton =
  1596. mb.addButton(QTStr("AutoSafeMode.LaunchNormal"), QMessageBox::RejectRole);
  1597. mb.setDefaultButton(launchNormalButton);
  1598. mb.exec();
  1599. safe_mode = mb.clickedButton() == launchSafeButton;
  1600. if (safe_mode) {
  1601. blog(LOG_INFO, "[Safe Mode] User has launched in Safe Mode.");
  1602. } else {
  1603. blog(LOG_WARNING, "[Safe Mode] User elected to launch normally.");
  1604. }
  1605. }
  1606. qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &, const QString &message) {
  1607. switch (type) {
  1608. #ifdef _DEBUG
  1609. case QtDebugMsg:
  1610. blog(LOG_DEBUG, "%s", QT_TO_UTF8(message));
  1611. break;
  1612. case QtInfoMsg:
  1613. blog(LOG_INFO, "%s", QT_TO_UTF8(message));
  1614. break;
  1615. #else
  1616. case QtDebugMsg:
  1617. case QtInfoMsg:
  1618. break;
  1619. #endif
  1620. case QtWarningMsg:
  1621. blog(LOG_WARNING, "%s", QT_TO_UTF8(message));
  1622. break;
  1623. case QtCriticalMsg:
  1624. case QtFatalMsg:
  1625. blog(LOG_ERROR, "%s", QT_TO_UTF8(message));
  1626. break;
  1627. }
  1628. });
  1629. #ifdef __APPLE__
  1630. MacPermissionStatus audio_permission = CheckPermission(kAudioDeviceAccess);
  1631. MacPermissionStatus video_permission = CheckPermission(kVideoDeviceAccess);
  1632. MacPermissionStatus accessibility_permission = CheckPermission(kAccessibility);
  1633. MacPermissionStatus screen_permission = CheckPermission(kScreenCapture);
  1634. int permissionsDialogLastShown =
  1635. config_get_int(App()->GetAppConfig(), "General", "MacOSPermissionsDialogLastShown");
  1636. if (permissionsDialogLastShown < MACOS_PERMISSIONS_DIALOG_VERSION) {
  1637. OBSPermissions check(nullptr, screen_permission, video_permission, audio_permission,
  1638. accessibility_permission);
  1639. check.exec();
  1640. }
  1641. #endif
  1642. #ifdef _WIN32
  1643. if (IsRunningOnWine()) {
  1644. QMessageBox mb(QMessageBox::Question, QTStr("Wine.Title"), QTStr("Wine.Text"));
  1645. mb.setTextFormat(Qt::RichText);
  1646. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::AcceptRole);
  1647. QPushButton *closeButton = mb.addButton(QMessageBox::Close);
  1648. mb.setDefaultButton(closeButton);
  1649. mb.exec();
  1650. if (mb.clickedButton() == closeButton)
  1651. return 0;
  1652. }
  1653. #endif
  1654. if (argc > 1) {
  1655. stringstream stor;
  1656. stor << argv[1];
  1657. for (int i = 2; i < argc; ++i) {
  1658. stor << " " << argv[i];
  1659. }
  1660. blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str());
  1661. }
  1662. if (!program.OBSInit())
  1663. return 0;
  1664. prof.Stop();
  1665. ret = program.exec();
  1666. } catch (const char *error) {
  1667. blog(LOG_ERROR, "%s", error);
  1668. OBSErrorBox(nullptr, "%s", error);
  1669. }
  1670. if (restart || restart_safe) {
  1671. arguments = qApp->arguments();
  1672. if (restart_safe) {
  1673. arguments.append("--safe-mode");
  1674. } else {
  1675. arguments.removeAll("--safe-mode");
  1676. }
  1677. }
  1678. return ret;
  1679. }
  1680. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1681. #ifdef _WIN32
  1682. #define CRASH_MESSAGE \
  1683. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1684. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1685. static void main_crash_handler(const char *format, va_list args, void * /* param */)
  1686. {
  1687. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1688. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1689. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1690. string crashFilePath = "obs-studio/crashes";
  1691. delete_oldest_file(true, crashFilePath.c_str());
  1692. string name = crashFilePath + "/";
  1693. name += "Crash " + GenerateTimeDateFilename("txt");
  1694. BPtr<char> path(GetAppConfigPathPtr(name.c_str()));
  1695. fstream file;
  1696. #ifdef _WIN32
  1697. BPtr<wchar_t> wpath;
  1698. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1699. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
  1700. #else
  1701. file.open(path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
  1702. #endif
  1703. file << text;
  1704. file.close();
  1705. string pathString(path.Get());
  1706. #ifdef _WIN32
  1707. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1708. #endif
  1709. string absolutePath = canonical(filesystem::path(pathString)).u8string();
  1710. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1711. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1712. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE, absolutePath.c_str());
  1713. string finalMessage = string(message_buffer.get(), message_buffer.get() + size);
  1714. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!", MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1715. if (ret == IDYES) {
  1716. size_t len = strlen(text);
  1717. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1718. memcpy(GlobalLock(mem), text, len);
  1719. GlobalUnlock(mem);
  1720. OpenClipboard(0);
  1721. EmptyClipboard();
  1722. SetClipboardData(CF_TEXT, mem);
  1723. CloseClipboard();
  1724. }
  1725. exit(-1);
  1726. }
  1727. static void load_debug_privilege(void)
  1728. {
  1729. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1730. TOKEN_PRIVILEGES tp;
  1731. HANDLE token;
  1732. LUID val;
  1733. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1734. return;
  1735. }
  1736. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1737. tp.PrivilegeCount = 1;
  1738. tp.Privileges[0].Luid = val;
  1739. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1740. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL);
  1741. }
  1742. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1743. tp.PrivilegeCount = 1;
  1744. tp.Privileges[0].Luid = val;
  1745. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1746. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL)) {
  1747. blog(LOG_INFO, "Could not set privilege to "
  1748. "increase GPU priority");
  1749. }
  1750. }
  1751. CloseHandle(token);
  1752. }
  1753. #endif
  1754. #ifdef __APPLE__
  1755. #define BASE_PATH ".."
  1756. #else
  1757. #define BASE_PATH "../.."
  1758. #endif
  1759. #define CONFIG_PATH BASE_PATH "/config"
  1760. #if defined(ENABLE_PORTABLE_CONFIG) || defined(_WIN32)
  1761. #define ALLOW_PORTABLE_MODE 1
  1762. #else
  1763. #define ALLOW_PORTABLE_MODE 0
  1764. #endif
  1765. int GetAppConfigPath(char *path, size_t size, const char *name)
  1766. {
  1767. #if ALLOW_PORTABLE_MODE
  1768. if (portable_mode) {
  1769. if (name && *name) {
  1770. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1771. } else {
  1772. return snprintf(path, size, CONFIG_PATH);
  1773. }
  1774. } else {
  1775. return os_get_config_path(path, size, name);
  1776. }
  1777. #else
  1778. return os_get_config_path(path, size, name);
  1779. #endif
  1780. }
  1781. char *GetAppConfigPathPtr(const char *name)
  1782. {
  1783. #if ALLOW_PORTABLE_MODE
  1784. if (portable_mode) {
  1785. char path[512];
  1786. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1787. return bstrdup(path);
  1788. } else {
  1789. return NULL;
  1790. }
  1791. } else {
  1792. return os_get_config_path_ptr(name);
  1793. }
  1794. #else
  1795. return os_get_config_path_ptr(name);
  1796. #endif
  1797. }
  1798. int GetProgramDataPath(char *path, size_t size, const char *name)
  1799. {
  1800. return os_get_program_data_path(path, size, name);
  1801. }
  1802. char *GetProgramDataPathPtr(const char *name)
  1803. {
  1804. return os_get_program_data_path_ptr(name);
  1805. }
  1806. bool GetFileSafeName(const char *name, std::string &file)
  1807. {
  1808. size_t base_len = strlen(name);
  1809. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1810. std::wstring wfile;
  1811. if (!len)
  1812. return false;
  1813. wfile.resize(len);
  1814. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1815. for (size_t i = wfile.size(); i > 0; i--) {
  1816. size_t im1 = i - 1;
  1817. if (iswspace(wfile[im1])) {
  1818. wfile[im1] = '_';
  1819. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1820. wfile.erase(im1, 1);
  1821. }
  1822. }
  1823. if (wfile.size() == 0)
  1824. wfile = L"characters_only";
  1825. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1826. if (!len)
  1827. return false;
  1828. file.resize(len);
  1829. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1830. return true;
  1831. }
  1832. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1833. {
  1834. size_t len = path.size();
  1835. if (extension) {
  1836. path += ".";
  1837. path += extension;
  1838. }
  1839. if (!os_file_exists(path.c_str()))
  1840. return true;
  1841. int index = 1;
  1842. do {
  1843. path.resize(len);
  1844. path += std::to_string(++index);
  1845. if (extension) {
  1846. path += ".";
  1847. path += extension;
  1848. }
  1849. } while (os_file_exists(path.c_str()));
  1850. return true;
  1851. }
  1852. bool WindowPositionValid(QRect rect)
  1853. {
  1854. for (QScreen *screen : QGuiApplication::screens()) {
  1855. if (screen->availableGeometry().intersects(rect))
  1856. return true;
  1857. }
  1858. return false;
  1859. }
  1860. static inline bool arg_is(const char *arg, const char *long_form, const char *short_form)
  1861. {
  1862. return (long_form && strcmp(arg, long_form) == 0) || (short_form && strcmp(arg, short_form) == 0);
  1863. }
  1864. static void check_safe_mode_sentinel(void)
  1865. {
  1866. #ifndef NDEBUG
  1867. /* Safe Mode detection is disabled in Debug builds to keep developers
  1868. * somewhat sane. */
  1869. return;
  1870. #else
  1871. if (disable_shutdown_check)
  1872. return;
  1873. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  1874. if (os_file_exists(sentinelPath)) {
  1875. unclean_shutdown = true;
  1876. return;
  1877. }
  1878. os_quick_write_utf8_file(sentinelPath, nullptr, 0, false);
  1879. #endif
  1880. }
  1881. static void delete_safe_mode_sentinel(void)
  1882. {
  1883. #ifndef NDEBUG
  1884. return;
  1885. #else
  1886. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  1887. os_unlink(sentinelPath);
  1888. #endif
  1889. }
  1890. #ifndef _WIN32
  1891. void OBSApp::SigIntSignalHandler(int s)
  1892. {
  1893. /* Handles SIGINT and writes to a socket. Qt will read
  1894. * from the socket in the main thread event loop and trigger
  1895. * a call to the ProcessSigInt slot, where we can safely run
  1896. * shutdown code without signal safety issues. */
  1897. UNUSED_PARAMETER(s);
  1898. char a = 1;
  1899. send(sigintFd[0], &a, sizeof(a), 0);
  1900. }
  1901. #endif
  1902. void OBSApp::ProcessSigInt(void)
  1903. {
  1904. /* This looks weird, but we can't ifdef a Qt slot function so
  1905. * the SIGINT handler simply does nothing on Windows. */
  1906. #ifndef _WIN32
  1907. char tmp;
  1908. recv(sigintFd[1], &tmp, sizeof(tmp), 0);
  1909. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1910. if (main)
  1911. main->close();
  1912. #endif
  1913. }
  1914. #ifdef _WIN32
  1915. void OBSApp::commitData(QSessionManager &manager)
  1916. {
  1917. if (auto main = App()->GetMainWindow()) {
  1918. QMetaObject::invokeMethod(main, "close", Qt::QueuedConnection);
  1919. manager.cancel();
  1920. }
  1921. }
  1922. #endif
  1923. #ifdef _WIN32
  1924. static constexpr char vcRunErrorTitle[] = "Outdated Visual C++ Runtime";
  1925. static constexpr char vcRunErrorMsg[] = "OBS Studio requires a newer version of the Microsoft Visual C++ "
  1926. "Redistributables.\n\nYou will now be directed to the download page.";
  1927. static constexpr char vcRunInstallerUrl[] = "https://obsproject.com/visual-studio-2022-runtimes";
  1928. static bool vc_runtime_outdated()
  1929. {
  1930. win_version_info ver;
  1931. if (!get_dll_ver(L"msvcp140.dll", &ver))
  1932. return true;
  1933. /* Major is always 14 (hence 140.dll), so we only care about minor. */
  1934. if (ver.minor >= 40)
  1935. return false;
  1936. int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle, MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL);
  1937. if (choice == IDOK) {
  1938. /* Open the URL in the default browser. */
  1939. ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL, SW_SHOWNORMAL);
  1940. }
  1941. return true;
  1942. }
  1943. #endif
  1944. int main(int argc, char *argv[])
  1945. {
  1946. #ifndef _WIN32
  1947. signal(SIGPIPE, SIG_IGN);
  1948. struct sigaction sig_handler;
  1949. sig_handler.sa_handler = OBSApp::SigIntSignalHandler;
  1950. sigemptyset(&sig_handler.sa_mask);
  1951. sig_handler.sa_flags = 0;
  1952. sigaction(SIGINT, &sig_handler, NULL);
  1953. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  1954. a closed pipe. */
  1955. sigset_t sigpipe_mask;
  1956. sigemptyset(&sigpipe_mask);
  1957. sigaddset(&sigpipe_mask, SIGPIPE);
  1958. sigset_t saved_mask;
  1959. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  1960. perror("pthread_sigmask");
  1961. exit(1);
  1962. }
  1963. #endif
  1964. #ifdef _WIN32
  1965. // Abort as early as possible if MSVC runtime is outdated
  1966. if (vc_runtime_outdated())
  1967. return 1;
  1968. // Try to keep this as early as possible
  1969. install_dll_blocklist_hook();
  1970. obs_init_win32_crash_handler();
  1971. SetErrorMode(SEM_FAILCRITICALERRORS);
  1972. load_debug_privilege();
  1973. base_set_crash_handler(main_crash_handler, nullptr);
  1974. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  1975. if (hRtwq) {
  1976. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  1977. PFN_RtwqStartup func = (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  1978. func();
  1979. }
  1980. #endif
  1981. base_get_log_handler(&def_log_handler, nullptr);
  1982. obs_set_cmdline_args(argc, argv);
  1983. for (int i = 1; i < argc; i++) {
  1984. if (arg_is(argv[i], "--multi", "-m")) {
  1985. multi = true;
  1986. disable_shutdown_check = true;
  1987. #if ALLOW_PORTABLE_MODE
  1988. } else if (arg_is(argv[i], "--portable", "-p")) {
  1989. portable_mode = true;
  1990. #endif
  1991. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1992. log_verbose = true;
  1993. } else if (arg_is(argv[i], "--safe-mode", nullptr)) {
  1994. safe_mode = true;
  1995. } else if (arg_is(argv[i], "--only-bundled-plugins", nullptr)) {
  1996. disable_3p_plugins = true;
  1997. } else if (arg_is(argv[i], "--disable-shutdown-check", nullptr)) {
  1998. /* This exists mostly to bypass the dialog during development. */
  1999. disable_shutdown_check = true;
  2000. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2001. opt_always_on_top = true;
  2002. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2003. unfiltered_log = true;
  2004. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2005. opt_start_streaming = true;
  2006. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2007. opt_start_recording = true;
  2008. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2009. opt_start_replaybuffer = true;
  2010. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2011. opt_start_virtualcam = true;
  2012. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2013. if (++i < argc)
  2014. opt_starting_collection = argv[i];
  2015. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2016. if (++i < argc)
  2017. opt_starting_profile = argv[i];
  2018. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2019. if (++i < argc)
  2020. opt_starting_scene = argv[i];
  2021. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2022. opt_minimize_tray = true;
  2023. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2024. opt_studio_mode = true;
  2025. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2026. opt_allow_opengl = true;
  2027. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2028. opt_disable_updater = true;
  2029. } else if (arg_is(argv[i], "--disable-missing-files-check", nullptr)) {
  2030. opt_disable_missing_files_check = true;
  2031. } else if (arg_is(argv[i], "--steam", nullptr)) {
  2032. steam = true;
  2033. } else if (arg_is(argv[i], "--help", "-h")) {
  2034. std::string help =
  2035. "--help, -h: Get list of available commands.\n\n"
  2036. "--startstreaming: Automatically start streaming.\n"
  2037. "--startrecording: Automatically start recording.\n"
  2038. "--startreplaybuffer: Start replay buffer.\n"
  2039. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2040. "--collection <string>: Use specific scene collection."
  2041. "\n"
  2042. "--profile <string>: Use specific profile.\n"
  2043. "--scene <string>: Start with specific scene.\n\n"
  2044. "--studio-mode: Enable studio mode.\n"
  2045. "--minimize-to-tray: Minimize to system tray.\n"
  2046. #if ALLOW_PORTABLE_MODE
  2047. "--portable, -p: Use portable mode.\n"
  2048. #endif
  2049. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2050. "--safe-mode: Run in Safe Mode (disables third-party plugins, scripting, and WebSockets).\n"
  2051. "--only-bundled-plugins: Only load included (first-party) plugins\n"
  2052. "--disable-shutdown-check: Disable unclean shutdown detection.\n"
  2053. "--verbose: Make log more verbose.\n"
  2054. "--always-on-top: Start in 'always on top' mode.\n\n"
  2055. "--unfiltered_log: Make log unfiltered.\n\n"
  2056. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2057. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n";
  2058. #ifdef _WIN32
  2059. MessageBoxA(NULL, help.c_str(), "Help", MB_OK | MB_ICONASTERISK);
  2060. #else
  2061. std::cout << help << "--version, -V: Get current version.\n";
  2062. #endif
  2063. exit(0);
  2064. } else if (arg_is(argv[i], "--version", "-V")) {
  2065. std::cout << "OBS Studio - " << App()->GetVersionString(false) << "\n";
  2066. exit(0);
  2067. }
  2068. }
  2069. #if ALLOW_PORTABLE_MODE
  2070. if (!portable_mode) {
  2071. portable_mode = os_file_exists(BASE_PATH "/portable_mode") ||
  2072. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2073. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2074. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2075. }
  2076. if (!opt_disable_updater) {
  2077. opt_disable_updater = os_file_exists(BASE_PATH "/disable_updater") ||
  2078. os_file_exists(BASE_PATH "/disable_updater.txt");
  2079. }
  2080. if (!opt_disable_missing_files_check) {
  2081. opt_disable_missing_files_check = os_file_exists(BASE_PATH "/disable_missing_files_check") ||
  2082. os_file_exists(BASE_PATH "/disable_missing_files_check.txt");
  2083. }
  2084. #endif
  2085. check_safe_mode_sentinel();
  2086. fstream logFile;
  2087. curl_global_init(CURL_GLOBAL_ALL);
  2088. int ret = run_program(logFile, argc, argv);
  2089. #ifdef _WIN32
  2090. if (hRtwq) {
  2091. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  2092. PFN_RtwqShutdown func = (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  2093. func();
  2094. FreeLibrary(hRtwq);
  2095. }
  2096. log_blocked_dlls();
  2097. #endif
  2098. delete_safe_mode_sentinel();
  2099. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2100. base_set_log_handler(nullptr, nullptr);
  2101. if (restart || restart_safe) {
  2102. auto executable = arguments.takeFirst();
  2103. QProcess::startDetached(executable, arguments);
  2104. }
  2105. return ret;
  2106. }