obs-app.cpp 85 KB

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