obs-app.cpp 70 KB

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