obs-app.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <lain@obsproject.com>
  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. const std::string userConfigFile = userConfigLocation.u8string() + "/obs-studio/user.ini";
  553. int errorCode = userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS);
  554. if (errorCode != CONFIG_SUCCESS) {
  555. OBSErrorBox(nullptr, "Failed to open user.ini: %d", errorCode);
  556. return false;
  557. }
  558. MigrateLegacySettings(lastVersion);
  559. InitUserConfigDefaults();
  560. return true;
  561. }
  562. void OBSApp::MigrateLegacySettings(const uint32_t lastVersion)
  563. {
  564. bool hasChanges = false;
  565. const uint32_t v19 = MAKE_SEMANTIC_VERSION(19, 0, 0);
  566. const uint32_t v21 = MAKE_SEMANTIC_VERSION(21, 0, 0);
  567. const uint32_t v23 = MAKE_SEMANTIC_VERSION(23, 0, 0);
  568. const uint32_t v24 = MAKE_SEMANTIC_VERSION(24, 0, 0);
  569. const uint32_t v24_1 = MAKE_SEMANTIC_VERSION(24, 1, 0);
  570. const map<uint32_t, string> defaultsMap{
  571. {{v19, "Pre19Defaults"}, {v21, "Pre21Defaults"}, {v23, "Pre23Defaults"}, {v24_1, "Pre24.1Defaults"}}};
  572. for (auto &[version, configKey] : defaultsMap) {
  573. if (!config_has_user_value(userConfig, "General", configKey.c_str())) {
  574. bool useOldDefaults = lastVersion && lastVersion < version;
  575. config_set_bool(userConfig, "General", configKey.c_str(), useOldDefaults);
  576. hasChanges = true;
  577. }
  578. }
  579. if (config_has_user_value(userConfig, "BasicWindow", "MultiviewLayout")) {
  580. const char *layout = config_get_string(userConfig, "BasicWindow", "MultiviewLayout");
  581. bool layoutUpdated = UpdatePre22MultiviewLayout(layout);
  582. hasChanges = hasChanges | layoutUpdated;
  583. }
  584. if (lastVersion && lastVersion < v24) {
  585. bool disableHotkeysInFocus = config_get_bool(userConfig, "General", "DisableHotkeysInFocus");
  586. if (disableHotkeysInFocus) {
  587. config_set_string(userConfig, "General", "HotkeyFocusType", "DisableHotkeysInFocus");
  588. }
  589. hasChanges = true;
  590. }
  591. if (hasChanges) {
  592. userConfig.SaveSafe("tmp");
  593. }
  594. }
  595. static constexpr string_view OBSGlobalIniPath = "/obs-studio/global.ini";
  596. static constexpr string_view OBSUserIniPath = "/obs-studio/user.ini";
  597. bool OBSApp::MigrateGlobalSettings()
  598. {
  599. char path[512];
  600. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  601. if (len <= 0) {
  602. OBSErrorBox(nullptr, "Unable to get global configuration path.");
  603. return false;
  604. }
  605. std::string legacyConfigFileString;
  606. legacyConfigFileString.reserve(strlen(path) + OBSGlobalIniPath.size());
  607. legacyConfigFileString.append(path).append(OBSGlobalIniPath);
  608. const std::filesystem::path legacyGlobalConfigFile = std::filesystem::u8path(legacyConfigFileString);
  609. std::string configFileString;
  610. configFileString.reserve(strlen(path) + OBSUserIniPath.size());
  611. configFileString.append(path).append(OBSUserIniPath);
  612. const std::filesystem::path userConfigFile = std::filesystem::u8path(configFileString);
  613. if (std::filesystem::exists(userConfigFile)) {
  614. OBSErrorBox(nullptr,
  615. "Unable to migrate global configuration - user configuration file already exists.");
  616. return false;
  617. }
  618. try {
  619. std::filesystem::copy(legacyGlobalConfigFile, userConfigFile);
  620. } catch (const std::filesystem::filesystem_error &) {
  621. OBSErrorBox(nullptr, "Unable to migrate global configuration - copy failed.");
  622. return false;
  623. }
  624. return true;
  625. }
  626. bool OBSApp::InitLocale()
  627. {
  628. ProfileScope("OBSApp::InitLocale");
  629. const char *lang = config_get_string(userConfig, "General", "Language");
  630. bool userLocale = config_has_user_value(userConfig, "General", "Language");
  631. if (!userLocale || !lang || lang[0] == '\0')
  632. lang = DEFAULT_LANG;
  633. locale = lang;
  634. // set basic default application locale
  635. if (!locale.empty())
  636. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  637. string englishPath;
  638. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  639. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  640. return false;
  641. }
  642. textLookup = text_lookup_create(englishPath.c_str());
  643. if (!textLookup) {
  644. OBSErrorBox(NULL, "Failed to create locale from file '%s'", englishPath.c_str());
  645. return false;
  646. }
  647. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  648. if (userLocale && defaultLang)
  649. return true;
  650. if (!userLocale && defaultLang) {
  651. for (auto &locale_ : GetPreferredLocales()) {
  652. if (locale_ == lang)
  653. return true;
  654. stringstream file;
  655. file << "locale/" << locale_ << ".ini";
  656. string path;
  657. if (!GetDataFilePath(file.str().c_str(), path))
  658. continue;
  659. if (!text_lookup_add(textLookup, path.c_str()))
  660. continue;
  661. blog(LOG_INFO, "Using preferred locale '%s'", locale_.c_str());
  662. locale = locale_;
  663. // set application default locale to the new choosen one
  664. if (!locale.empty())
  665. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  666. return true;
  667. }
  668. return true;
  669. }
  670. stringstream file;
  671. file << "locale/" << lang << ".ini";
  672. string path;
  673. if (GetDataFilePath(file.str().c_str(), path)) {
  674. if (!text_lookup_add(textLookup, path.c_str()))
  675. blog(LOG_ERROR, "Failed to add locale file '%s'", path.c_str());
  676. } else {
  677. blog(LOG_ERROR, "Could not find locale file '%s'", file.str().c_str());
  678. }
  679. return true;
  680. }
  681. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  682. void ParseBranchesJson(const std::string &jsonString, vector<UpdateBranch> &out, std::string &error)
  683. {
  684. JsonBranches branches;
  685. try {
  686. nlohmann::json json = nlohmann::json::parse(jsonString);
  687. branches = json.get<JsonBranches>();
  688. } catch (nlohmann::json::exception &e) {
  689. error = e.what();
  690. return;
  691. }
  692. for (const JsonBranch &json_branch : branches) {
  693. #ifdef _WIN32
  694. if (!json_branch.windows)
  695. continue;
  696. #elif defined(__APPLE__)
  697. if (!json_branch.macos)
  698. continue;
  699. #endif
  700. UpdateBranch branch = {
  701. QString::fromStdString(json_branch.name),
  702. QString::fromStdString(json_branch.display_name),
  703. QString::fromStdString(json_branch.description),
  704. json_branch.enabled,
  705. json_branch.visible,
  706. };
  707. out.push_back(branch);
  708. }
  709. }
  710. bool LoadBranchesFile(vector<UpdateBranch> &out)
  711. {
  712. string error;
  713. string branchesText;
  714. BPtr<char> branchesFilePath = GetAppConfigPathPtr("obs-studio/updates/branches.json");
  715. QFile branchesFile(branchesFilePath.Get());
  716. if (!branchesFile.open(QIODevice::ReadOnly)) {
  717. error = "Opening file failed.";
  718. goto fail;
  719. }
  720. branchesText = branchesFile.readAll();
  721. if (branchesText.empty()) {
  722. error = "File empty.";
  723. goto fail;
  724. }
  725. ParseBranchesJson(branchesText, out, error);
  726. if (error.empty())
  727. return !out.empty();
  728. fail:
  729. blog(LOG_WARNING, "Loading branches from file failed: %s", error.c_str());
  730. return false;
  731. }
  732. #endif
  733. void OBSApp::SetBranchData(const string &data)
  734. {
  735. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  736. string error;
  737. vector<UpdateBranch> result;
  738. ParseBranchesJson(data, result, error);
  739. if (!error.empty()) {
  740. blog(LOG_WARNING, "Reading branches JSON response failed: %s", error.c_str());
  741. return;
  742. }
  743. if (!result.empty())
  744. updateBranches = result;
  745. branches_loaded = true;
  746. #else
  747. UNUSED_PARAMETER(data);
  748. #endif
  749. }
  750. std::vector<UpdateBranch> OBSApp::GetBranches()
  751. {
  752. vector<UpdateBranch> out;
  753. /* Always ensure the default branch exists */
  754. out.push_back(UpdateBranch{"stable", "", "", true, true});
  755. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  756. if (!branches_loaded) {
  757. vector<UpdateBranch> result;
  758. if (LoadBranchesFile(result))
  759. updateBranches = result;
  760. branches_loaded = true;
  761. }
  762. #endif
  763. /* Copy additional branches to result (if any) */
  764. if (!updateBranches.empty())
  765. out.insert(out.end(), updateBranches.begin(), updateBranches.end());
  766. return out;
  767. }
  768. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  769. : QApplication(argc, argv),
  770. profilerNameStore(store)
  771. {
  772. /* fix float handling */
  773. #if defined(Q_OS_UNIX)
  774. if (!setlocale(LC_NUMERIC, "C"))
  775. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  776. #endif
  777. #ifndef _WIN32
  778. /* Handle SIGINT properly */
  779. socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd);
  780. snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
  781. connect(snInt, &QSocketNotifier::activated, this, &OBSApp::ProcessSigInt);
  782. #else
  783. connect(qApp, &QGuiApplication::commitDataRequest, this, &OBSApp::commitData);
  784. #endif
  785. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  786. #ifndef __APPLE__
  787. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  788. #endif
  789. setDesktopFileName("com.obsproject.Studio");
  790. }
  791. OBSApp::~OBSApp()
  792. {
  793. #ifdef _WIN32
  794. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  795. if (disableAudioDucking)
  796. DisableAudioDucking(false);
  797. #else
  798. delete snInt;
  799. close(sigintFd[0]);
  800. close(sigintFd[1]);
  801. #endif
  802. #ifdef __APPLE__
  803. bool vsyncDisabled = config_get_bool(appConfig, "Video", "DisableOSXVSync");
  804. bool resetVSync = config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit");
  805. if (vsyncDisabled && resetVSync)
  806. EnableOSXVSync(true);
  807. #endif
  808. os_inhibit_sleep_set_active(sleepInhibitor, false);
  809. os_inhibit_sleep_destroy(sleepInhibitor);
  810. if (libobs_initialized)
  811. obs_shutdown();
  812. }
  813. static void move_basic_to_profiles(void)
  814. {
  815. char path[512];
  816. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  817. return;
  818. }
  819. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  820. if (!std::filesystem::exists(basicPath)) {
  821. return;
  822. }
  823. const std::filesystem::path profilesPath =
  824. App()->userProfilesLocation / std::filesystem::u8path("obs-studio/basic/profiles");
  825. if (std::filesystem::exists(profilesPath)) {
  826. return;
  827. }
  828. try {
  829. std::filesystem::create_directories(profilesPath);
  830. } catch (const std::filesystem::filesystem_error &error) {
  831. blog(LOG_ERROR, "Failed to create profiles directory for migration from basic profile\n%s",
  832. error.what());
  833. return;
  834. }
  835. const std::filesystem::path newProfilePath = profilesPath / std::filesystem::u8path(Str("Untitled"));
  836. for (auto &entry : std::filesystem::directory_iterator(basicPath)) {
  837. if (entry.is_directory()) {
  838. continue;
  839. }
  840. if (entry.path().filename().u8string() == "scenes.json") {
  841. continue;
  842. }
  843. if (!std::filesystem::exists(newProfilePath)) {
  844. try {
  845. std::filesystem::create_directory(newProfilePath);
  846. } catch (const std::filesystem::filesystem_error &error) {
  847. blog(LOG_ERROR, "Failed to create profile directory for 'Untitled'\n%s", error.what());
  848. return;
  849. }
  850. }
  851. const filesystem::path destinationFile = newProfilePath / entry.path().filename();
  852. const auto copyOptions = std::filesystem::copy_options::overwrite_existing;
  853. try {
  854. std::filesystem::copy(entry.path(), destinationFile, copyOptions);
  855. } catch (const std::filesystem::filesystem_error &error) {
  856. blog(LOG_ERROR, "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s",
  857. entry.path().filename().u8string().c_str(), error.what());
  858. return;
  859. }
  860. }
  861. }
  862. static void move_basic_to_scene_collections(void)
  863. {
  864. char path[512];
  865. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  866. return;
  867. }
  868. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  869. if (!std::filesystem::exists(basicPath)) {
  870. return;
  871. }
  872. const std::filesystem::path sceneCollectionPath =
  873. App()->userScenesLocation / std::filesystem::u8path("obs-studio/basic/scenes");
  874. if (std::filesystem::exists(sceneCollectionPath)) {
  875. return;
  876. }
  877. try {
  878. std::filesystem::create_directories(sceneCollectionPath);
  879. } catch (const std::filesystem::filesystem_error &error) {
  880. blog(LOG_ERROR,
  881. "Failed to create scene collection directory for migration from basic scene collection\n%s",
  882. error.what());
  883. return;
  884. }
  885. const std::filesystem::path sourceFile = basicPath / std::filesystem::u8path("scenes.json");
  886. const std::filesystem::path destinationFile =
  887. (sceneCollectionPath / std::filesystem::u8path(Str("Untitled"))).replace_extension(".json");
  888. try {
  889. std::filesystem::rename(sourceFile, destinationFile);
  890. } catch (const std::filesystem::filesystem_error &error) {
  891. blog(LOG_ERROR, "Failed to rename basic scene collection file:\n%s", error.what());
  892. return;
  893. }
  894. }
  895. void OBSApp::AppInit()
  896. {
  897. ProfileScope("OBSApp::AppInit");
  898. if (!MakeUserDirs())
  899. throw "Failed to create required user directories";
  900. if (!InitGlobalConfig())
  901. throw "Failed to initialize global config";
  902. if (!InitLocale())
  903. throw "Failed to load locale";
  904. if (!InitTheme())
  905. throw "Failed to load theme";
  906. config_set_default_string(userConfig, "Basic", "Profile", Str("Untitled"));
  907. config_set_default_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  908. config_set_default_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  909. config_set_default_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  910. config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile", true);
  911. if (!config_has_user_value(userConfig, "Basic", "Profile")) {
  912. config_set_string(userConfig, "Basic", "Profile", Str("Untitled"));
  913. config_set_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  914. }
  915. if (!config_has_user_value(userConfig, "Basic", "SceneCollection")) {
  916. config_set_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  917. config_set_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  918. }
  919. #ifdef _WIN32
  920. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  921. if (disableAudioDucking)
  922. DisableAudioDucking(true);
  923. #endif
  924. #ifdef __APPLE__
  925. if (config_get_bool(appConfig, "Video", "DisableOSXVSync"))
  926. EnableOSXVSync(false);
  927. #endif
  928. UpdateHotkeyFocusSetting(false);
  929. move_basic_to_profiles();
  930. move_basic_to_scene_collections();
  931. if (!MakeUserProfileDirs())
  932. throw "Failed to create profile directories";
  933. }
  934. const char *OBSApp::GetRenderModule() const
  935. {
  936. const char *renderer = config_get_string(appConfig, "Video", "Renderer");
  937. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  938. }
  939. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  940. {
  941. char path[512];
  942. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  943. return false;
  944. return obs_startup(locale, path, store);
  945. }
  946. inline void OBSApp::ResetHotkeyState(bool inFocus)
  947. {
  948. obs_hotkey_enable_background_press((inFocus && enableHotkeysInFocus) || (!inFocus && enableHotkeysOutOfFocus));
  949. }
  950. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  951. {
  952. enableHotkeysInFocus = true;
  953. enableHotkeysOutOfFocus = true;
  954. const char *hotkeyFocusType = config_get_string(userConfig, "General", "HotkeyFocusType");
  955. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  956. enableHotkeysInFocus = false;
  957. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  958. enableHotkeysOutOfFocus = false;
  959. }
  960. if (resetState)
  961. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  962. }
  963. void OBSApp::DisableHotkeys()
  964. {
  965. enableHotkeysInFocus = false;
  966. enableHotkeysOutOfFocus = false;
  967. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  968. }
  969. Q_DECLARE_METATYPE(VoidFunc)
  970. void OBSApp::Exec(VoidFunc func)
  971. {
  972. func();
  973. }
  974. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  975. {
  976. auto doTask = [=]() {
  977. /* to get clang-format to behave */
  978. task(param);
  979. };
  980. QMetaObject::invokeMethod(App(), "Exec", wait ? WaitConnection() : Qt::AutoConnection, Q_ARG(VoidFunc, doTask));
  981. }
  982. bool OBSApp::OBSInit()
  983. {
  984. ProfileScope("OBSApp::OBSInit");
  985. qRegisterMetaType<VoidFunc>("VoidFunc");
  986. #if !defined(_WIN32) && !defined(__APPLE__)
  987. if (QApplication::platformName() == "xcb") {
  988. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  989. blog(LOG_INFO, "Using EGL/X11");
  990. }
  991. #ifdef ENABLE_WAYLAND
  992. if (QApplication::platformName().contains("wayland")) {
  993. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  994. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  995. blog(LOG_INFO, "Platform: Wayland");
  996. }
  997. #endif
  998. QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();
  999. obs_set_nix_platform_display(native->nativeResourceForIntegration("display"));
  1000. #endif
  1001. #ifdef __APPLE__
  1002. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1003. #endif
  1004. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1005. return false;
  1006. libobs_initialized = true;
  1007. obs_set_ui_task_handler(ui_task_handler);
  1008. #if defined(_WIN32) || defined(__APPLE__)
  1009. bool browserHWAccel = config_get_bool(appConfig, "General", "BrowserHWAccel");
  1010. OBSDataAutoRelease settings = obs_data_create();
  1011. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1012. obs_apply_private_data(settings);
  1013. blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str());
  1014. blog(LOG_INFO, "Browser Hardware Acceleration: %s", browserHWAccel ? "true" : "false");
  1015. #endif
  1016. #ifdef _WIN32
  1017. bool hideFromCapture = config_get_bool(userConfig, "BasicWindow", "HideOBSWindowsFromCapture");
  1018. blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hideFromCapture ? "true" : "false");
  1019. #endif
  1020. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(), QT_VERSION_STR);
  1021. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1022. if (safe_mode) {
  1023. blog(LOG_WARNING, "Safe Mode enabled.");
  1024. } else if (disable_3p_plugins) {
  1025. blog(LOG_WARNING, "Third-party plugins disabled.");
  1026. }
  1027. setQuitOnLastWindowClosed(false);
  1028. mainWindow = new OBSBasic();
  1029. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1030. connect(mainWindow, &OBSBasic::destroyed, this, &OBSApp::quit);
  1031. mainWindow->OBSInit();
  1032. connect(this, &QGuiApplication::applicationStateChanged,
  1033. [this](Qt::ApplicationState state) { ResetHotkeyState(state == Qt::ApplicationActive); });
  1034. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1035. return true;
  1036. }
  1037. string OBSApp::GetVersionString(bool platform) const
  1038. {
  1039. stringstream ver;
  1040. #ifdef HAVE_OBSCONFIG_H
  1041. ver << obs_get_version_string();
  1042. #else
  1043. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "." << LIBOBS_API_PATCH_VER;
  1044. #endif
  1045. if (platform) {
  1046. ver << " (";
  1047. #ifdef _WIN32
  1048. if (sizeof(void *) == 8)
  1049. ver << "64-bit, ";
  1050. else
  1051. ver << "32-bit, ";
  1052. ver << "windows)";
  1053. #elif __APPLE__
  1054. ver << "mac)";
  1055. #elif __OpenBSD__
  1056. ver << "openbsd)";
  1057. #elif __FreeBSD__
  1058. ver << "freebsd)";
  1059. #else /* assume linux for the time being */
  1060. ver << "linux)";
  1061. #endif
  1062. }
  1063. return ver.str();
  1064. }
  1065. bool OBSApp::IsPortableMode()
  1066. {
  1067. return portable_mode;
  1068. }
  1069. bool OBSApp::IsUpdaterDisabled()
  1070. {
  1071. return opt_disable_updater;
  1072. }
  1073. bool OBSApp::IsMissingFilesCheckDisabled()
  1074. {
  1075. return opt_disable_missing_files_check;
  1076. }
  1077. #ifdef __APPLE__
  1078. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1079. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1080. #elif _WIN32
  1081. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1082. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1083. #else
  1084. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1085. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1086. #endif
  1087. const char *OBSApp::InputAudioSource() const
  1088. {
  1089. return INPUT_AUDIO_SOURCE;
  1090. }
  1091. const char *OBSApp::OutputAudioSource() const
  1092. {
  1093. return OUTPUT_AUDIO_SOURCE;
  1094. }
  1095. const char *OBSApp::GetLastLog() const
  1096. {
  1097. return lastLogFile.c_str();
  1098. }
  1099. const char *OBSApp::GetCurrentLog() const
  1100. {
  1101. return currentLogFile.c_str();
  1102. }
  1103. const char *OBSApp::GetLastCrashLog() const
  1104. {
  1105. return lastCrashLogFile.c_str();
  1106. }
  1107. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1108. {
  1109. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1110. if (cb(lookupVal, out))
  1111. return true;
  1112. }
  1113. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1114. }
  1115. // Global handler to receive all QEvent::Show events so we can apply
  1116. // display affinity on any newly created windows and dialogs without
  1117. // caring where they are coming from (e.g. plugins).
  1118. bool OBSApp::notify(QObject *receiver, QEvent *e)
  1119. {
  1120. QWidget *w;
  1121. QWindow *window;
  1122. int windowType;
  1123. if (!receiver->isWidgetType())
  1124. goto skip;
  1125. if (e->type() != QEvent::Show)
  1126. goto skip;
  1127. w = qobject_cast<QWidget *>(receiver);
  1128. if (!w->isWindow())
  1129. goto skip;
  1130. window = w->windowHandle();
  1131. if (!window)
  1132. goto skip;
  1133. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  1134. if (windowType == Qt::WindowType::Dialog || windowType == Qt::WindowType::Window ||
  1135. windowType == Qt::WindowType::Tool) {
  1136. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1137. if (main)
  1138. main->SetDisplayAffinity(window);
  1139. }
  1140. skip:
  1141. return QApplication::notify(receiver, e);
  1142. }
  1143. QString OBSTranslator::translate(const char *, const char *sourceText, const char *, int) const
  1144. {
  1145. const char *out = nullptr;
  1146. QString str(sourceText);
  1147. str.replace(" ", "");
  1148. if (!App()->TranslateString(QT_TO_UTF8(str), &out))
  1149. return QString(sourceText);
  1150. return QT_UTF8(out);
  1151. }
  1152. static bool get_token(lexer *lex, string &str, base_token_type type)
  1153. {
  1154. base_token token;
  1155. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1156. return false;
  1157. if (token.type != type)
  1158. return false;
  1159. str.assign(token.text.array, token.text.len);
  1160. return true;
  1161. }
  1162. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1163. {
  1164. base_token token;
  1165. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1166. return false;
  1167. if (token.type != type)
  1168. return false;
  1169. return strref_cmp(&token.text, str) == 0;
  1170. }
  1171. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1172. {
  1173. BaseLexer lex;
  1174. string year, month, day, hour, minute, second;
  1175. lexer_start(lex, name);
  1176. if (has_prefix) {
  1177. string temp;
  1178. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1179. return 0;
  1180. }
  1181. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1182. return 0;
  1183. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1184. return 0;
  1185. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1186. return 0;
  1187. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1188. return 0;
  1189. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1190. return 0;
  1191. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1192. return 0;
  1193. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1194. return 0;
  1195. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1196. return 0;
  1197. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1198. return 0;
  1199. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1200. return 0;
  1201. stringstream timestring;
  1202. timestring << year << month << day << hour << minute << second;
  1203. return std::stoull(timestring.str());
  1204. }
  1205. /* If upgrading from an older (non-XDG) build of OBS, move config files to XDG directory. */
  1206. /* TODO: Remove after version 32.0. */
  1207. #if defined(__FreeBSD__)
  1208. static void move_to_xdg(void)
  1209. {
  1210. char old_path[512];
  1211. char new_path[512];
  1212. char *home = getenv("HOME");
  1213. if (!home)
  1214. return;
  1215. if (snprintf(old_path, sizeof(old_path), "%s/.obs-studio", home) <= 0)
  1216. return;
  1217. /* make base xdg path if it doesn't already exist */
  1218. if (GetAppConfigPath(new_path, sizeof(new_path), "") <= 0)
  1219. return;
  1220. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1221. return;
  1222. if (GetAppConfigPath(new_path, sizeof(new_path), "obs-studio") <= 0)
  1223. return;
  1224. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1225. rename(old_path, new_path);
  1226. }
  1227. }
  1228. #endif
  1229. static void delete_oldest_file(bool has_prefix, const char *location)
  1230. {
  1231. BPtr<char> logDir(GetAppConfigPathPtr(location));
  1232. string oldestLog;
  1233. uint64_t oldest_ts = (uint64_t)-1;
  1234. struct os_dirent *entry;
  1235. unsigned int maxLogs = (unsigned int)config_get_uint(App()->GetAppConfig(), "General", "MaxLogs");
  1236. os_dir_t *dir = os_opendir(logDir);
  1237. if (dir) {
  1238. unsigned int count = 0;
  1239. while ((entry = os_readdir(dir)) != NULL) {
  1240. if (entry->directory || *entry->d_name == '.')
  1241. continue;
  1242. uint64_t ts = convert_log_name(has_prefix, entry->d_name);
  1243. if (ts) {
  1244. if (ts < oldest_ts) {
  1245. oldestLog = entry->d_name;
  1246. oldest_ts = ts;
  1247. }
  1248. count++;
  1249. }
  1250. }
  1251. os_closedir(dir);
  1252. if (count > maxLogs) {
  1253. stringstream delPath;
  1254. delPath << logDir << "/" << oldestLog;
  1255. os_unlink(delPath.str().c_str());
  1256. }
  1257. }
  1258. }
  1259. static void get_last_log(bool has_prefix, const char *subdir_to_use, std::string &last)
  1260. {
  1261. BPtr<char> logDir(GetAppConfigPathPtr(subdir_to_use));
  1262. struct os_dirent *entry;
  1263. os_dir_t *dir = os_opendir(logDir);
  1264. uint64_t highest_ts = 0;
  1265. if (dir) {
  1266. while ((entry = os_readdir(dir)) != NULL) {
  1267. if (entry->directory || *entry->d_name == '.')
  1268. continue;
  1269. uint64_t ts = convert_log_name(has_prefix, entry->d_name);
  1270. if (ts > highest_ts) {
  1271. last = entry->d_name;
  1272. highest_ts = ts;
  1273. }
  1274. }
  1275. os_closedir(dir);
  1276. }
  1277. }
  1278. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1279. {
  1280. time_t now = time(0);
  1281. char file[256] = {};
  1282. struct tm *cur_time;
  1283. cur_time = localtime(&now);
  1284. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s", cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1285. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour, cur_time->tm_min, cur_time->tm_sec,
  1286. extension);
  1287. return string(file);
  1288. }
  1289. string GenerateSpecifiedFilename(const char *extension, bool noSpace, const char *format)
  1290. {
  1291. BPtr<char> filename = os_generate_formatted_filename(extension, !noSpace, format);
  1292. return string(filename);
  1293. }
  1294. static void FindBestFilename(string &strPath, bool noSpace)
  1295. {
  1296. int num = 2;
  1297. if (!os_file_exists(strPath.c_str()))
  1298. return;
  1299. const char *ext = strrchr(strPath.c_str(), '.');
  1300. if (!ext)
  1301. return;
  1302. int extStart = int(ext - strPath.c_str());
  1303. for (;;) {
  1304. string testPath = strPath;
  1305. string numStr;
  1306. numStr = noSpace ? "_" : " (";
  1307. numStr += to_string(num++);
  1308. if (!noSpace)
  1309. numStr += ")";
  1310. testPath.insert(extStart, numStr);
  1311. if (!os_file_exists(testPath.c_str())) {
  1312. strPath = testPath;
  1313. break;
  1314. }
  1315. }
  1316. }
  1317. static void ensure_directory_exists(string &path)
  1318. {
  1319. replace(path.begin(), path.end(), '\\', '/');
  1320. size_t last = path.rfind('/');
  1321. if (last == string::npos)
  1322. return;
  1323. string directory = path.substr(0, last);
  1324. os_mkdirs(directory.c_str());
  1325. }
  1326. static void remove_reserved_file_characters(string &s)
  1327. {
  1328. replace(s.begin(), s.end(), '\\', '/');
  1329. replace(s.begin(), s.end(), '*', '_');
  1330. replace(s.begin(), s.end(), '?', '_');
  1331. replace(s.begin(), s.end(), '"', '_');
  1332. replace(s.begin(), s.end(), '|', '_');
  1333. replace(s.begin(), s.end(), ':', '_');
  1334. replace(s.begin(), s.end(), '>', '_');
  1335. replace(s.begin(), s.end(), '<', '_');
  1336. }
  1337. string GetFormatString(const char *format, const char *prefix, const char *suffix)
  1338. {
  1339. string f;
  1340. f = format;
  1341. if (prefix && *prefix) {
  1342. string str_prefix = prefix;
  1343. if (str_prefix.back() != ' ')
  1344. str_prefix += " ";
  1345. size_t insert_pos = 0;
  1346. size_t tmp;
  1347. tmp = f.find_last_of('/');
  1348. if (tmp != string::npos && tmp > insert_pos)
  1349. insert_pos = tmp + 1;
  1350. tmp = f.find_last_of('\\');
  1351. if (tmp != string::npos && tmp > insert_pos)
  1352. insert_pos = tmp + 1;
  1353. f.insert(insert_pos, str_prefix);
  1354. }
  1355. if (suffix && *suffix) {
  1356. if (*suffix != ' ')
  1357. f += " ";
  1358. f += suffix;
  1359. }
  1360. remove_reserved_file_characters(f);
  1361. return f;
  1362. }
  1363. string GetFormatExt(const char *container)
  1364. {
  1365. string ext = container;
  1366. if (ext == "fragmented_mp4")
  1367. ext = "mp4";
  1368. if (ext == "hybrid_mp4")
  1369. ext = "mp4";
  1370. else if (ext == "fragmented_mov")
  1371. ext = "mov";
  1372. else if (ext == "hls")
  1373. ext = "m3u8";
  1374. else if (ext == "mpegts")
  1375. ext = "ts";
  1376. return ext;
  1377. }
  1378. string GetOutputFilename(const char *path, const char *container, bool noSpace, bool overwrite, const char *format)
  1379. {
  1380. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1381. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1382. if (!dir) {
  1383. if (main->isVisible())
  1384. OBSMessageBox::warning(main, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text"));
  1385. else
  1386. main->SysTrayNotify(QTStr("Output.BadPath.Text"), QSystemTrayIcon::Warning);
  1387. return "";
  1388. }
  1389. os_closedir(dir);
  1390. string strPath;
  1391. strPath += path;
  1392. char lastChar = strPath.back();
  1393. if (lastChar != '/' && lastChar != '\\')
  1394. strPath += "/";
  1395. string ext = GetFormatExt(container);
  1396. strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format);
  1397. ensure_directory_exists(strPath);
  1398. if (!overwrite)
  1399. FindBestFilename(strPath, noSpace);
  1400. return strPath;
  1401. }
  1402. vector<pair<string, string>> GetLocaleNames()
  1403. {
  1404. string path;
  1405. if (!GetDataFilePath("locale.ini", path))
  1406. throw "Could not find locale.ini path";
  1407. ConfigFile ini;
  1408. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1409. throw "Could not open locale.ini";
  1410. size_t sections = config_num_sections(ini);
  1411. vector<pair<string, string>> names;
  1412. names.reserve(sections);
  1413. for (size_t i = 0; i < sections; i++) {
  1414. const char *tag = config_get_section(ini, i);
  1415. const char *name = config_get_string(ini, tag, "Name");
  1416. names.emplace_back(tag, name);
  1417. }
  1418. return names;
  1419. }
  1420. static void create_log_file(fstream &logFile)
  1421. {
  1422. stringstream dst;
  1423. get_last_log(false, "obs-studio/logs", lastLogFile);
  1424. #ifdef _WIN32
  1425. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1426. #endif
  1427. currentLogFile = GenerateTimeDateFilename("txt");
  1428. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1429. BPtr<char> path(GetAppConfigPathPtr(dst.str().c_str()));
  1430. #ifdef _WIN32
  1431. BPtr<wchar_t> wpath;
  1432. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1433. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1434. #else
  1435. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1436. #endif
  1437. if (logFile.is_open()) {
  1438. delete_oldest_file(false, "obs-studio/logs");
  1439. base_set_log_handler(do_log, &logFile);
  1440. } else {
  1441. blog(LOG_ERROR, "Failed to open log file");
  1442. }
  1443. }
  1444. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1445. profiler_name_store_free(store);
  1446. };
  1447. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t, decltype(ProfilerNameStoreRelease)>;
  1448. ProfilerNameStore CreateNameStore()
  1449. {
  1450. return ProfilerNameStore{profiler_name_store_create(), ProfilerNameStoreRelease};
  1451. }
  1452. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1453. profile_snapshot_free(snap);
  1454. };
  1455. using ProfilerSnapshot = std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1456. ProfilerSnapshot GetSnapshot()
  1457. {
  1458. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1459. }
  1460. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1461. {
  1462. if (currentLogFile.empty())
  1463. return;
  1464. auto pos = currentLogFile.rfind('.');
  1465. if (pos == currentLogFile.npos)
  1466. return;
  1467. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1468. ostringstream dst;
  1469. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1470. dst.write(currentLogFile.c_str(), pos);
  1471. dst.write(LITERAL_SIZE(".csv.gz"));
  1472. #undef LITERAL_SIZE
  1473. BPtr<char> path = GetAppConfigPathPtr(dst.str().c_str());
  1474. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1475. blog(LOG_WARNING, "Could not save profiler data to '%s'", static_cast<const char *>(path));
  1476. }
  1477. static auto ProfilerFree = [](void *) {
  1478. profiler_stop();
  1479. auto snap = GetSnapshot();
  1480. profiler_print(snap.get());
  1481. profiler_print_time_between_calls(snap.get());
  1482. SaveProfilerData(snap);
  1483. profiler_free();
  1484. };
  1485. QAccessibleInterface *accessibleFactory(const QString &classname, QObject *object)
  1486. {
  1487. if (classname == QLatin1String("VolumeSlider") && object && object->isWidgetType())
  1488. return new VolumeAccessibleInterface(static_cast<QWidget *>(object));
  1489. return nullptr;
  1490. }
  1491. static const char *run_program_init = "run_program_init";
  1492. static int run_program(fstream &logFile, int argc, char *argv[])
  1493. {
  1494. int ret = -1;
  1495. auto profilerNameStore = CreateNameStore();
  1496. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(static_cast<void *>(&ProfilerFree), ProfilerFree);
  1497. profiler_start();
  1498. profile_register_root(run_program_init, 0);
  1499. ScopeProfiler prof{run_program_init};
  1500. #ifdef _WIN32
  1501. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1502. #endif
  1503. QCoreApplication::addLibraryPath(".");
  1504. #if __APPLE__
  1505. InstallNSApplicationSubclass();
  1506. InstallNSThreadLocks();
  1507. if (!isInBundle()) {
  1508. blog(LOG_ERROR,
  1509. "OBS cannot be run as a standalone binary on macOS. Run the Application bundle instead.");
  1510. return ret;
  1511. }
  1512. #endif
  1513. #if !defined(_WIN32) && !defined(__APPLE__)
  1514. /* NOTE: Users blindly set this, but this theme is incompatble with Qt6 and
  1515. * crashes loading saved geometry. Just turn off this theme and let users complain OBS
  1516. * looks ugly instead of crashing. */
  1517. const char *platform_theme = getenv("QT_QPA_PLATFORMTHEME");
  1518. if (platform_theme && strcmp(platform_theme, "qt5ct") == 0)
  1519. unsetenv("QT_QPA_PLATFORMTHEME");
  1520. #endif
  1521. /* NOTE: This disables an optimisation in Qt that attempts to determine if
  1522. * any "siblings" intersect with a widget when determining the approximate
  1523. * visible/unobscured area. However, by Qt's own admission this is slow
  1524. * and in the case of OBS it significantly slows down lists with many
  1525. * elements (e.g. Hotkeys) and it is actually faster to disable it. */
  1526. qputenv("QT_NO_SUBTRACTOPAQUESIBLINGS", "1");
  1527. OBSApp program(argc, argv, profilerNameStore.get());
  1528. try {
  1529. QAccessible::installFactory(accessibleFactory);
  1530. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Regular.ttf");
  1531. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Bold.ttf");
  1532. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Italic.ttf");
  1533. bool created_log = false;
  1534. program.AppInit();
  1535. delete_oldest_file(false, "obs-studio/profiler_data");
  1536. OBSTranslator translator;
  1537. program.installTranslator(&translator);
  1538. /* --------------------------------------- */
  1539. /* check and warn if already running */
  1540. bool cancel_launch = false;
  1541. bool already_running = false;
  1542. #ifdef _WIN32
  1543. RunOnceMutex rom =
  1544. #endif
  1545. CheckIfAlreadyRunning(already_running);
  1546. if (!already_running) {
  1547. goto run;
  1548. }
  1549. if (!multi) {
  1550. QMessageBox mb(QMessageBox::Question, QTStr("AlreadyRunning.Title"),
  1551. QTStr("AlreadyRunning.Text"));
  1552. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::YesRole);
  1553. QPushButton *cancelButton = mb.addButton(QTStr("Cancel"), QMessageBox::NoRole);
  1554. mb.setDefaultButton(cancelButton);
  1555. mb.exec();
  1556. cancel_launch = mb.clickedButton() == cancelButton;
  1557. }
  1558. if (cancel_launch)
  1559. return 0;
  1560. if (!created_log) {
  1561. create_log_file(logFile);
  1562. created_log = true;
  1563. }
  1564. if (multi) {
  1565. blog(LOG_INFO, "User enabled --multi flag and is now "
  1566. "running multiple instances of OBS.");
  1567. } else {
  1568. blog(LOG_WARNING, "================================");
  1569. blog(LOG_WARNING, "Warning: OBS is already running!");
  1570. blog(LOG_WARNING, "================================");
  1571. blog(LOG_WARNING, "User is now running multiple "
  1572. "instances of OBS!");
  1573. /* Clear unclean_shutdown flag as multiple instances
  1574. * running from the same config will lead to a
  1575. * false-positive detection.*/
  1576. unclean_shutdown = false;
  1577. }
  1578. /* --------------------------------------- */
  1579. run:
  1580. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1581. // Mounted by termina during chromeOS linux container startup
  1582. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1583. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1584. if (crosDir) {
  1585. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1586. QMessageBox mb(QMessageBox::Critical, QTStr("ChromeOS.Title"), QTStr("ChromeOS.Text"), buttons,
  1587. nullptr);
  1588. mb.exec();
  1589. return 0;
  1590. }
  1591. #endif
  1592. if (!created_log)
  1593. create_log_file(logFile);
  1594. if (unclean_shutdown) {
  1595. blog(LOG_WARNING, "[Safe Mode] Unclean shutdown detected!");
  1596. }
  1597. if (unclean_shutdown && !safe_mode) {
  1598. QMessageBox mb(QMessageBox::Warning, QTStr("AutoSafeMode.Title"), QTStr("AutoSafeMode.Text"));
  1599. QPushButton *launchSafeButton =
  1600. mb.addButton(QTStr("AutoSafeMode.LaunchSafe"), QMessageBox::AcceptRole);
  1601. QPushButton *launchNormalButton =
  1602. mb.addButton(QTStr("AutoSafeMode.LaunchNormal"), QMessageBox::RejectRole);
  1603. mb.setDefaultButton(launchNormalButton);
  1604. mb.exec();
  1605. safe_mode = mb.clickedButton() == launchSafeButton;
  1606. if (safe_mode) {
  1607. blog(LOG_INFO, "[Safe Mode] User has launched in Safe Mode.");
  1608. } else {
  1609. blog(LOG_WARNING, "[Safe Mode] User elected to launch normally.");
  1610. }
  1611. }
  1612. qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &, const QString &message) {
  1613. switch (type) {
  1614. #ifdef _DEBUG
  1615. case QtDebugMsg:
  1616. blog(LOG_DEBUG, "%s", QT_TO_UTF8(message));
  1617. break;
  1618. case QtInfoMsg:
  1619. blog(LOG_INFO, "%s", QT_TO_UTF8(message));
  1620. break;
  1621. #else
  1622. case QtDebugMsg:
  1623. case QtInfoMsg:
  1624. break;
  1625. #endif
  1626. case QtWarningMsg:
  1627. blog(LOG_WARNING, "%s", QT_TO_UTF8(message));
  1628. break;
  1629. case QtCriticalMsg:
  1630. case QtFatalMsg:
  1631. blog(LOG_ERROR, "%s", QT_TO_UTF8(message));
  1632. break;
  1633. }
  1634. });
  1635. #ifdef __APPLE__
  1636. MacPermissionStatus audio_permission = CheckPermission(kAudioDeviceAccess);
  1637. MacPermissionStatus video_permission = CheckPermission(kVideoDeviceAccess);
  1638. MacPermissionStatus accessibility_permission = CheckPermission(kAccessibility);
  1639. MacPermissionStatus screen_permission = CheckPermission(kScreenCapture);
  1640. int permissionsDialogLastShown =
  1641. config_get_int(App()->GetAppConfig(), "General", "MacOSPermissionsDialogLastShown");
  1642. if (permissionsDialogLastShown < MACOS_PERMISSIONS_DIALOG_VERSION) {
  1643. OBSPermissions check(nullptr, screen_permission, video_permission, audio_permission,
  1644. accessibility_permission);
  1645. check.exec();
  1646. }
  1647. #endif
  1648. #ifdef _WIN32
  1649. if (IsRunningOnWine()) {
  1650. QMessageBox mb(QMessageBox::Question, QTStr("Wine.Title"), QTStr("Wine.Text"));
  1651. mb.setTextFormat(Qt::RichText);
  1652. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::AcceptRole);
  1653. QPushButton *closeButton = mb.addButton(QMessageBox::Close);
  1654. mb.setDefaultButton(closeButton);
  1655. mb.exec();
  1656. if (mb.clickedButton() == closeButton)
  1657. return 0;
  1658. }
  1659. #endif
  1660. if (argc > 1) {
  1661. stringstream stor;
  1662. stor << argv[1];
  1663. for (int i = 2; i < argc; ++i) {
  1664. stor << " " << argv[i];
  1665. }
  1666. blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str());
  1667. }
  1668. if (!program.OBSInit())
  1669. return 0;
  1670. prof.Stop();
  1671. ret = program.exec();
  1672. } catch (const char *error) {
  1673. blog(LOG_ERROR, "%s", error);
  1674. OBSErrorBox(nullptr, "%s", error);
  1675. }
  1676. if (restart || restart_safe) {
  1677. arguments = qApp->arguments();
  1678. if (restart_safe) {
  1679. arguments.append("--safe-mode");
  1680. } else {
  1681. arguments.removeAll("--safe-mode");
  1682. }
  1683. }
  1684. return ret;
  1685. }
  1686. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1687. #ifdef _WIN32
  1688. #define CRASH_MESSAGE \
  1689. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1690. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1691. static void main_crash_handler(const char *format, va_list args, void * /* param */)
  1692. {
  1693. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1694. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1695. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1696. string crashFilePath = "obs-studio/crashes";
  1697. delete_oldest_file(true, crashFilePath.c_str());
  1698. string name = crashFilePath + "/";
  1699. name += "Crash " + GenerateTimeDateFilename("txt");
  1700. BPtr<char> path(GetAppConfigPathPtr(name.c_str()));
  1701. fstream file;
  1702. #ifdef _WIN32
  1703. BPtr<wchar_t> wpath;
  1704. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1705. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
  1706. #else
  1707. file.open(path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
  1708. #endif
  1709. file << text;
  1710. file.close();
  1711. string pathString(path.Get());
  1712. #ifdef _WIN32
  1713. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1714. #endif
  1715. string absolutePath = canonical(filesystem::path(pathString)).u8string();
  1716. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1717. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1718. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE, absolutePath.c_str());
  1719. string finalMessage = string(message_buffer.get(), message_buffer.get() + size);
  1720. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!", MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1721. if (ret == IDYES) {
  1722. size_t len = strlen(text);
  1723. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1724. memcpy(GlobalLock(mem), text, len);
  1725. GlobalUnlock(mem);
  1726. OpenClipboard(0);
  1727. EmptyClipboard();
  1728. SetClipboardData(CF_TEXT, mem);
  1729. CloseClipboard();
  1730. }
  1731. exit(-1);
  1732. }
  1733. static void load_debug_privilege(void)
  1734. {
  1735. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1736. TOKEN_PRIVILEGES tp;
  1737. HANDLE token;
  1738. LUID val;
  1739. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1740. return;
  1741. }
  1742. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1743. tp.PrivilegeCount = 1;
  1744. tp.Privileges[0].Luid = val;
  1745. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1746. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL);
  1747. }
  1748. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1749. tp.PrivilegeCount = 1;
  1750. tp.Privileges[0].Luid = val;
  1751. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1752. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL)) {
  1753. blog(LOG_INFO, "Could not set privilege to "
  1754. "increase GPU priority");
  1755. }
  1756. }
  1757. CloseHandle(token);
  1758. }
  1759. #endif
  1760. #ifdef __APPLE__
  1761. #define BASE_PATH ".."
  1762. #else
  1763. #define BASE_PATH "../.."
  1764. #endif
  1765. #define CONFIG_PATH BASE_PATH "/config"
  1766. #if defined(ENABLE_PORTABLE_CONFIG) || defined(_WIN32)
  1767. #define ALLOW_PORTABLE_MODE 1
  1768. #else
  1769. #define ALLOW_PORTABLE_MODE 0
  1770. #endif
  1771. int GetAppConfigPath(char *path, size_t size, const char *name)
  1772. {
  1773. #if ALLOW_PORTABLE_MODE
  1774. if (portable_mode) {
  1775. if (name && *name) {
  1776. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1777. } else {
  1778. return snprintf(path, size, CONFIG_PATH);
  1779. }
  1780. } else {
  1781. return os_get_config_path(path, size, name);
  1782. }
  1783. #else
  1784. return os_get_config_path(path, size, name);
  1785. #endif
  1786. }
  1787. char *GetAppConfigPathPtr(const char *name)
  1788. {
  1789. #if ALLOW_PORTABLE_MODE
  1790. if (portable_mode) {
  1791. char path[512];
  1792. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1793. return bstrdup(path);
  1794. } else {
  1795. return NULL;
  1796. }
  1797. } else {
  1798. return os_get_config_path_ptr(name);
  1799. }
  1800. #else
  1801. return os_get_config_path_ptr(name);
  1802. #endif
  1803. }
  1804. int GetProgramDataPath(char *path, size_t size, const char *name)
  1805. {
  1806. return os_get_program_data_path(path, size, name);
  1807. }
  1808. char *GetProgramDataPathPtr(const char *name)
  1809. {
  1810. return os_get_program_data_path_ptr(name);
  1811. }
  1812. bool GetFileSafeName(const char *name, std::string &file)
  1813. {
  1814. size_t base_len = strlen(name);
  1815. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1816. std::wstring wfile;
  1817. if (!len)
  1818. return false;
  1819. wfile.resize(len);
  1820. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1821. for (size_t i = wfile.size(); i > 0; i--) {
  1822. size_t im1 = i - 1;
  1823. if (iswspace(wfile[im1])) {
  1824. wfile[im1] = '_';
  1825. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1826. wfile.erase(im1, 1);
  1827. }
  1828. }
  1829. if (wfile.size() == 0)
  1830. wfile = L"characters_only";
  1831. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1832. if (!len)
  1833. return false;
  1834. file.resize(len);
  1835. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1836. return true;
  1837. }
  1838. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1839. {
  1840. size_t len = path.size();
  1841. if (extension) {
  1842. path += ".";
  1843. path += extension;
  1844. }
  1845. if (!os_file_exists(path.c_str()))
  1846. return true;
  1847. int index = 1;
  1848. do {
  1849. path.resize(len);
  1850. path += std::to_string(++index);
  1851. if (extension) {
  1852. path += ".";
  1853. path += extension;
  1854. }
  1855. } while (os_file_exists(path.c_str()));
  1856. return true;
  1857. }
  1858. bool WindowPositionValid(QRect rect)
  1859. {
  1860. for (QScreen *screen : QGuiApplication::screens()) {
  1861. if (screen->availableGeometry().intersects(rect))
  1862. return true;
  1863. }
  1864. return false;
  1865. }
  1866. static inline bool arg_is(const char *arg, const char *long_form, const char *short_form)
  1867. {
  1868. return (long_form && strcmp(arg, long_form) == 0) || (short_form && strcmp(arg, short_form) == 0);
  1869. }
  1870. static void check_safe_mode_sentinel(void)
  1871. {
  1872. #ifndef NDEBUG
  1873. /* Safe Mode detection is disabled in Debug builds to keep developers
  1874. * somewhat sane. */
  1875. return;
  1876. #else
  1877. if (disable_shutdown_check)
  1878. return;
  1879. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  1880. if (os_file_exists(sentinelPath)) {
  1881. unclean_shutdown = true;
  1882. return;
  1883. }
  1884. os_quick_write_utf8_file(sentinelPath, nullptr, 0, false);
  1885. #endif
  1886. }
  1887. static void delete_safe_mode_sentinel(void)
  1888. {
  1889. #ifndef NDEBUG
  1890. return;
  1891. #else
  1892. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  1893. os_unlink(sentinelPath);
  1894. #endif
  1895. }
  1896. #ifndef _WIN32
  1897. void OBSApp::SigIntSignalHandler(int s)
  1898. {
  1899. /* Handles SIGINT and writes to a socket. Qt will read
  1900. * from the socket in the main thread event loop and trigger
  1901. * a call to the ProcessSigInt slot, where we can safely run
  1902. * shutdown code without signal safety issues. */
  1903. UNUSED_PARAMETER(s);
  1904. char a = 1;
  1905. send(sigintFd[0], &a, sizeof(a), 0);
  1906. }
  1907. #endif
  1908. void OBSApp::ProcessSigInt(void)
  1909. {
  1910. /* This looks weird, but we can't ifdef a Qt slot function so
  1911. * the SIGINT handler simply does nothing on Windows. */
  1912. #ifndef _WIN32
  1913. char tmp;
  1914. recv(sigintFd[1], &tmp, sizeof(tmp), 0);
  1915. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1916. if (main)
  1917. main->close();
  1918. #endif
  1919. }
  1920. #ifdef _WIN32
  1921. void OBSApp::commitData(QSessionManager &manager)
  1922. {
  1923. if (auto main = App()->GetMainWindow()) {
  1924. QMetaObject::invokeMethod(main, "close", Qt::QueuedConnection);
  1925. manager.cancel();
  1926. }
  1927. }
  1928. #endif
  1929. #ifdef _WIN32
  1930. static constexpr char vcRunErrorTitle[] = "Outdated Visual C++ Runtime";
  1931. static constexpr char vcRunErrorMsg[] = "OBS Studio requires a newer version of the Microsoft Visual C++ "
  1932. "Redistributables.\n\nYou will now be directed to the download page.";
  1933. static constexpr char vcRunInstallerUrl[] = "https://obsproject.com/visual-studio-2022-runtimes";
  1934. static bool vc_runtime_outdated()
  1935. {
  1936. win_version_info ver;
  1937. if (!get_dll_ver(L"msvcp140.dll", &ver))
  1938. return true;
  1939. /* Major is always 14 (hence 140.dll), so we only care about minor. */
  1940. if (ver.minor >= 40)
  1941. return false;
  1942. int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle, MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL);
  1943. if (choice == IDOK) {
  1944. /* Open the URL in the default browser. */
  1945. ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL, SW_SHOWNORMAL);
  1946. }
  1947. return true;
  1948. }
  1949. #endif
  1950. int main(int argc, char *argv[])
  1951. {
  1952. #ifndef _WIN32
  1953. signal(SIGPIPE, SIG_IGN);
  1954. struct sigaction sig_handler;
  1955. sig_handler.sa_handler = OBSApp::SigIntSignalHandler;
  1956. sigemptyset(&sig_handler.sa_mask);
  1957. sig_handler.sa_flags = 0;
  1958. sigaction(SIGINT, &sig_handler, NULL);
  1959. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  1960. a closed pipe. */
  1961. sigset_t sigpipe_mask;
  1962. sigemptyset(&sigpipe_mask);
  1963. sigaddset(&sigpipe_mask, SIGPIPE);
  1964. sigset_t saved_mask;
  1965. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  1966. perror("pthread_sigmask");
  1967. exit(1);
  1968. }
  1969. #endif
  1970. #ifdef _WIN32
  1971. // Abort as early as possible if MSVC runtime is outdated
  1972. if (vc_runtime_outdated())
  1973. return 1;
  1974. // Try to keep this as early as possible
  1975. install_dll_blocklist_hook();
  1976. obs_init_win32_crash_handler();
  1977. SetErrorMode(SEM_FAILCRITICALERRORS);
  1978. load_debug_privilege();
  1979. base_set_crash_handler(main_crash_handler, nullptr);
  1980. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  1981. if (hRtwq) {
  1982. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  1983. PFN_RtwqStartup func = (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  1984. func();
  1985. }
  1986. #endif
  1987. base_get_log_handler(&def_log_handler, nullptr);
  1988. #if defined(__FreeBSD__)
  1989. move_to_xdg();
  1990. #endif
  1991. obs_set_cmdline_args(argc, argv);
  1992. for (int i = 1; i < argc; i++) {
  1993. if (arg_is(argv[i], "--multi", "-m")) {
  1994. multi = true;
  1995. disable_shutdown_check = true;
  1996. #if ALLOW_PORTABLE_MODE
  1997. } else if (arg_is(argv[i], "--portable", "-p")) {
  1998. portable_mode = true;
  1999. #endif
  2000. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2001. log_verbose = true;
  2002. } else if (arg_is(argv[i], "--safe-mode", nullptr)) {
  2003. safe_mode = true;
  2004. } else if (arg_is(argv[i], "--only-bundled-plugins", nullptr)) {
  2005. disable_3p_plugins = true;
  2006. } else if (arg_is(argv[i], "--disable-shutdown-check", nullptr)) {
  2007. /* This exists mostly to bypass the dialog during development. */
  2008. disable_shutdown_check = true;
  2009. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2010. opt_always_on_top = true;
  2011. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2012. unfiltered_log = true;
  2013. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2014. opt_start_streaming = true;
  2015. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2016. opt_start_recording = true;
  2017. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2018. opt_start_replaybuffer = true;
  2019. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2020. opt_start_virtualcam = true;
  2021. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2022. if (++i < argc)
  2023. opt_starting_collection = argv[i];
  2024. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2025. if (++i < argc)
  2026. opt_starting_profile = argv[i];
  2027. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2028. if (++i < argc)
  2029. opt_starting_scene = argv[i];
  2030. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2031. opt_minimize_tray = true;
  2032. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2033. opt_studio_mode = true;
  2034. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2035. opt_allow_opengl = true;
  2036. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2037. opt_disable_updater = true;
  2038. } else if (arg_is(argv[i], "--disable-missing-files-check", nullptr)) {
  2039. opt_disable_missing_files_check = true;
  2040. } else if (arg_is(argv[i], "--steam", nullptr)) {
  2041. steam = true;
  2042. } else if (arg_is(argv[i], "--help", "-h")) {
  2043. std::string help =
  2044. "--help, -h: Get list of available commands.\n\n"
  2045. "--startstreaming: Automatically start streaming.\n"
  2046. "--startrecording: Automatically start recording.\n"
  2047. "--startreplaybuffer: Start replay buffer.\n"
  2048. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2049. "--collection <string>: Use specific scene collection."
  2050. "\n"
  2051. "--profile <string>: Use specific profile.\n"
  2052. "--scene <string>: Start with specific scene.\n\n"
  2053. "--studio-mode: Enable studio mode.\n"
  2054. "--minimize-to-tray: Minimize to system tray.\n"
  2055. #if ALLOW_PORTABLE_MODE
  2056. "--portable, -p: Use portable mode.\n"
  2057. #endif
  2058. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2059. "--safe-mode: Run in Safe Mode (disables third-party plugins, scripting, and WebSockets).\n"
  2060. "--only-bundled-plugins: Only load included (first-party) plugins\n"
  2061. "--disable-shutdown-check: Disable unclean shutdown detection.\n"
  2062. "--verbose: Make log more verbose.\n"
  2063. "--always-on-top: Start in 'always on top' mode.\n\n"
  2064. "--unfiltered_log: Make log unfiltered.\n\n"
  2065. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2066. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n";
  2067. #ifdef _WIN32
  2068. MessageBoxA(NULL, help.c_str(), "Help", MB_OK | MB_ICONASTERISK);
  2069. #else
  2070. std::cout << help << "--version, -V: Get current version.\n";
  2071. #endif
  2072. exit(0);
  2073. } else if (arg_is(argv[i], "--version", "-V")) {
  2074. std::cout << "OBS Studio - " << App()->GetVersionString(false) << "\n";
  2075. exit(0);
  2076. }
  2077. }
  2078. #if ALLOW_PORTABLE_MODE
  2079. if (!portable_mode) {
  2080. portable_mode = os_file_exists(BASE_PATH "/portable_mode") ||
  2081. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2082. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2083. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2084. }
  2085. if (!opt_disable_updater) {
  2086. opt_disable_updater = os_file_exists(BASE_PATH "/disable_updater") ||
  2087. os_file_exists(BASE_PATH "/disable_updater.txt");
  2088. }
  2089. if (!opt_disable_missing_files_check) {
  2090. opt_disable_missing_files_check = os_file_exists(BASE_PATH "/disable_missing_files_check") ||
  2091. os_file_exists(BASE_PATH "/disable_missing_files_check.txt");
  2092. }
  2093. #endif
  2094. check_safe_mode_sentinel();
  2095. fstream logFile;
  2096. curl_global_init(CURL_GLOBAL_ALL);
  2097. int ret = run_program(logFile, argc, argv);
  2098. #ifdef _WIN32
  2099. if (hRtwq) {
  2100. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  2101. PFN_RtwqShutdown func = (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  2102. func();
  2103. FreeLibrary(hRtwq);
  2104. }
  2105. log_blocked_dlls();
  2106. #endif
  2107. delete_safe_mode_sentinel();
  2108. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2109. base_set_log_handler(nullptr, nullptr);
  2110. if (restart || restart_safe) {
  2111. auto executable = arguments.takeFirst();
  2112. QProcess::startDetached(executable, arguments);
  2113. }
  2114. return ret;
  2115. }