obs-app.cpp 82 KB

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