obs-app.cpp 86 KB

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