obs-app.cpp 68 KB

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