window-basic-main.cpp 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677
  1. /******************************************************************************
  2. Copyright (C) 2013-2015 by Hugh Bailey <[email protected]>
  3. Zachary Lund <[email protected]>
  4. Philippe Groarke <[email protected]>
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ******************************************************************************/
  16. #include <time.h>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QRect>
  25. #include <QScreen>
  26. #include <util/dstr.h>
  27. #include <util/util.hpp>
  28. #include <util/platform.h>
  29. #include <util/profiler.hpp>
  30. #include <util/dstr.hpp>
  31. #include <graphics/math-defs.h>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-basic-properties.hpp"
  44. #include "window-log-reply.hpp"
  45. #include "window-projector.hpp"
  46. #include "window-remux.hpp"
  47. #include "qt-wrappers.hpp"
  48. #include "display-helpers.hpp"
  49. #include "volume-control.hpp"
  50. #include "remote-text.hpp"
  51. #if defined(_WIN32) && defined(ENABLE_WIN_UPDATER)
  52. #include "win-update/win-update.hpp"
  53. #endif
  54. #include "ui_OBSBasic.h"
  55. #include <fstream>
  56. #include <sstream>
  57. #include <QScreen>
  58. #include <QWindow>
  59. using namespace std;
  60. namespace {
  61. template <typename OBSRef>
  62. struct SignalContainer {
  63. OBSRef ref;
  64. vector<shared_ptr<OBSSignal>> handlers;
  65. };
  66. }
  67. Q_DECLARE_METATYPE(OBSScene);
  68. Q_DECLARE_METATYPE(OBSSceneItem);
  69. Q_DECLARE_METATYPE(OBSSource);
  70. Q_DECLARE_METATYPE(obs_order_movement);
  71. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  72. template <typename T>
  73. static T GetOBSRef(QListWidgetItem *item)
  74. {
  75. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  76. }
  77. template <typename T>
  78. static void SetOBSRef(QListWidgetItem *item, T &&val)
  79. {
  80. item->setData(static_cast<int>(QtDataRole::OBSRef),
  81. QVariant::fromValue(val));
  82. }
  83. static void AddExtraModulePaths()
  84. {
  85. char base_module_dir[512];
  86. #if defined(_WIN32) || defined(__APPLE__)
  87. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  88. "obs-studio/plugins/%module%");
  89. #else
  90. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  91. "obs-studio/plugins/%module%");
  92. #endif
  93. if (ret <= 0)
  94. return;
  95. string path = (char*)base_module_dir;
  96. #if defined(__APPLE__)
  97. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  98. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  99. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  100. obs_add_module_path(config_bin, config_data);
  101. #elif ARCH_BITS == 64
  102. obs_add_module_path((path + "/bin/64bit").c_str(),
  103. (path + "/data").c_str());
  104. #else
  105. obs_add_module_path((path + "/bin/32bit").c_str(),
  106. (path + "/data").c_str());
  107. #endif
  108. }
  109. static QList<QKeySequence> DeleteKeys;
  110. OBSBasic::OBSBasic(QWidget *parent)
  111. : OBSMainWindow (parent),
  112. ui (new Ui::OBSBasic)
  113. {
  114. setAttribute(Qt::WA_NativeWindow);
  115. projectorArray.resize(10, "");
  116. previewProjectorArray.resize(10, 0);
  117. setAcceptDrops(true);
  118. ui->setupUi(this);
  119. ui->previewDisabledLabel->setVisible(false);
  120. startingDockLayout = saveState();
  121. copyActionsDynamicProperties();
  122. ui->sources->setItemDelegate(new VisibilityItemDelegate(ui->sources));
  123. const char *geometry = config_get_string(App()->GlobalConfig(),
  124. "BasicWindow", "geometry");
  125. if (geometry != NULL) {
  126. QByteArray byteArray = QByteArray::fromBase64(
  127. QByteArray(geometry));
  128. restoreGeometry(byteArray);
  129. QRect windowGeometry = normalGeometry();
  130. if (!WindowPositionValid(windowGeometry)) {
  131. QRect rect = App()->desktop()->geometry();
  132. setGeometry(QStyle::alignedRect(
  133. Qt::LeftToRight,
  134. Qt::AlignCenter,
  135. size(), rect));
  136. }
  137. }
  138. char styleSheetPath[512];
  139. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  140. "stylesheet.qss");
  141. if (ret > 0) {
  142. if (QFile::exists(styleSheetPath)) {
  143. QString path = QString("file:///") +
  144. QT_UTF8(styleSheetPath);
  145. App()->setStyleSheet(path);
  146. }
  147. }
  148. qRegisterMetaType<OBSScene> ("OBSScene");
  149. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  150. qRegisterMetaType<OBSSource> ("OBSSource");
  151. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  152. qRegisterMetaTypeStreamOperators<
  153. std::vector<std::shared_ptr<OBSSignal>>>(
  154. "std::vector<std::shared_ptr<OBSSignal>>");
  155. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  156. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  157. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  158. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  159. auto displayResize = [this]() {
  160. struct obs_video_info ovi;
  161. if (obs_get_video_info(&ovi))
  162. ResizePreview(ovi.base_width, ovi.base_height);
  163. };
  164. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  165. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  166. installEventFilter(CreateShortcutFilter());
  167. stringstream name;
  168. name << "OBS " << App()->GetVersionString();
  169. blog(LOG_INFO, "%s", name.str().c_str());
  170. blog(LOG_INFO, "---------------------------------");
  171. UpdateTitleBar();
  172. connect(ui->scenes->itemDelegate(),
  173. SIGNAL(closeEditor(QWidget*,
  174. QAbstractItemDelegate::EndEditHint)),
  175. this,
  176. SLOT(SceneNameEdited(QWidget*,
  177. QAbstractItemDelegate::EndEditHint)));
  178. connect(ui->sources->itemDelegate(),
  179. SIGNAL(closeEditor(QWidget*,
  180. QAbstractItemDelegate::EndEditHint)),
  181. this,
  182. SLOT(SceneItemNameEdited(QWidget*,
  183. QAbstractItemDelegate::EndEditHint)));
  184. cpuUsageInfo = os_cpu_usage_info_start();
  185. cpuUsageTimer = new QTimer(this);
  186. connect(cpuUsageTimer, SIGNAL(timeout()),
  187. ui->statusbar, SLOT(UpdateCPUUsage()));
  188. cpuUsageTimer->start(3000);
  189. DeleteKeys =
  190. #ifdef __APPLE__
  191. QList<QKeySequence>{{Qt::Key_Backspace}} <<
  192. #endif
  193. QKeySequence::keyBindings(QKeySequence::Delete);
  194. #ifdef __APPLE__
  195. ui->actionRemoveSource->setShortcuts(DeleteKeys);
  196. ui->actionRemoveScene->setShortcuts(DeleteKeys);
  197. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  198. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  199. #endif
  200. auto addNudge = [this](const QKeySequence &seq, const char *s)
  201. {
  202. QAction *nudge = new QAction(ui->preview);
  203. nudge->setShortcut(seq);
  204. nudge->setShortcutContext(Qt::WidgetShortcut);
  205. ui->preview->addAction(nudge);
  206. connect(nudge, SIGNAL(triggered()), this, s);
  207. };
  208. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  209. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  210. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  211. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  212. auto assignDockToggle = [this](QDockWidget *dock, QAction *action)
  213. {
  214. auto handleWindowToggle = [action] (bool vis)
  215. {
  216. action->blockSignals(true);
  217. action->setChecked(vis);
  218. action->blockSignals(false);
  219. };
  220. auto handleMenuToggle = [dock] (bool check)
  221. {
  222. dock->blockSignals(true);
  223. dock->setVisible(check);
  224. dock->blockSignals(false);
  225. };
  226. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  227. handleWindowToggle);
  228. dock->connect(action, &QAction::toggled,
  229. handleMenuToggle);
  230. };
  231. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  232. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  233. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  234. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  235. assignDockToggle(ui->controlsDock, ui->toggleControls);
  236. }
  237. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  238. vector<OBSSource> &audioSources)
  239. {
  240. obs_source_t *source = obs_get_output_source(channel);
  241. if (!source)
  242. return;
  243. audioSources.push_back(source);
  244. obs_data_t *data = obs_save_source(source);
  245. obs_data_set_obj(parent, name, data);
  246. obs_data_release(data);
  247. obs_source_release(source);
  248. }
  249. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  250. obs_data_array_t *quickTransitionData, int transitionDuration,
  251. obs_data_array_t *transitions,
  252. OBSScene &scene, OBSSource &curProgramScene,
  253. obs_data_array_t *savedProjectorList,
  254. obs_data_array_t *savedPreviewProjectorList)
  255. {
  256. obs_data_t *saveData = obs_data_create();
  257. vector<OBSSource> audioSources;
  258. audioSources.reserve(5);
  259. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  260. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  261. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  262. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  263. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  264. auto FilterAudioSources = [&](obs_source_t *source)
  265. {
  266. return find(begin(audioSources), end(audioSources), source) ==
  267. end(audioSources);
  268. };
  269. using FilterAudioSources_t = decltype(FilterAudioSources);
  270. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  271. [](void *data, obs_source_t *source)
  272. {
  273. return (*static_cast<FilterAudioSources_t*>(data))(source);
  274. }, static_cast<void*>(&FilterAudioSources));
  275. obs_source_t *transition = obs_get_output_source(0);
  276. obs_source_t *currentScene = obs_scene_get_source(scene);
  277. const char *sceneName = obs_source_get_name(currentScene);
  278. const char *programName = obs_source_get_name(curProgramScene);
  279. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  280. "Basic", "SceneCollection");
  281. obs_data_set_string(saveData, "current_scene", sceneName);
  282. obs_data_set_string(saveData, "current_program_scene", programName);
  283. obs_data_set_array(saveData, "scene_order", sceneOrder);
  284. obs_data_set_string(saveData, "name", sceneCollection);
  285. obs_data_set_array(saveData, "sources", sourcesArray);
  286. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  287. obs_data_set_array(saveData, "transitions", transitions);
  288. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  289. obs_data_set_array(saveData, "saved_preview_projectors",
  290. savedPreviewProjectorList);
  291. obs_data_array_release(sourcesArray);
  292. obs_data_set_string(saveData, "current_transition",
  293. obs_source_get_name(transition));
  294. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  295. obs_source_release(transition);
  296. return saveData;
  297. }
  298. void OBSBasic::copyActionsDynamicProperties()
  299. {
  300. // Themes need the QAction dynamic properties
  301. for (QAction *x : ui->scenesToolbar->actions()) {
  302. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  303. for (QByteArray &y : x->dynamicPropertyNames()) {
  304. temp->setProperty(y, x->property(y));
  305. }
  306. }
  307. for (QAction *x : ui->sourcesToolbar->actions()) {
  308. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  309. for (QByteArray &y : x->dynamicPropertyNames()) {
  310. temp->setProperty(y, x->property(y));
  311. }
  312. }
  313. }
  314. void OBSBasic::ClearVolumeControls()
  315. {
  316. VolControl *control;
  317. for (size_t i = 0; i < volumes.size(); i++) {
  318. control = volumes[i];
  319. delete control;
  320. }
  321. volumes.clear();
  322. }
  323. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  324. {
  325. obs_data_array_t *sceneOrder = obs_data_array_create();
  326. for (int i = 0; i < ui->scenes->count(); i++) {
  327. obs_data_t *data = obs_data_create();
  328. obs_data_set_string(data, "name",
  329. QT_TO_UTF8(ui->scenes->item(i)->text()));
  330. obs_data_array_push_back(sceneOrder, data);
  331. obs_data_release(data);
  332. }
  333. return sceneOrder;
  334. }
  335. obs_data_array_t *OBSBasic::SaveProjectors()
  336. {
  337. obs_data_array_t *saveProjector = obs_data_array_create();
  338. for (size_t i = 0; i < projectorArray.size(); i++) {
  339. obs_data_t *data = obs_data_create();
  340. obs_data_set_string(data, "saved_projectors",
  341. projectorArray.at(i).c_str());
  342. obs_data_array_push_back(saveProjector, data);
  343. obs_data_release(data);
  344. }
  345. return saveProjector;
  346. }
  347. obs_data_array_t *OBSBasic::SavePreviewProjectors()
  348. {
  349. obs_data_array_t *saveProjector = obs_data_array_create();
  350. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  351. obs_data_t *data = obs_data_create();
  352. obs_data_set_int(data, "saved_preview_projectors",
  353. previewProjectorArray.at(i));
  354. obs_data_array_push_back(saveProjector, data);
  355. obs_data_release(data);
  356. }
  357. return saveProjector;
  358. }
  359. void OBSBasic::Save(const char *file)
  360. {
  361. OBSScene scene = GetCurrentScene();
  362. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  363. if (!curProgramScene)
  364. curProgramScene = obs_scene_get_source(scene);
  365. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  366. obs_data_array_t *transitions = SaveTransitions();
  367. obs_data_array_t *quickTrData = SaveQuickTransitions();
  368. obs_data_array_t *savedProjectorList = SaveProjectors();
  369. obs_data_array_t *savedPreviewProjectorList = SavePreviewProjectors();
  370. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  371. ui->transitionDuration->value(), transitions,
  372. scene, curProgramScene, savedProjectorList,
  373. savedPreviewProjectorList);
  374. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  375. obs_data_set_bool(saveData, "scaling_enabled",
  376. ui->preview->IsFixedScaling());
  377. obs_data_set_int(saveData, "scaling_level",
  378. ui->preview->GetScalingLevel());
  379. obs_data_set_double(saveData, "scaling_off_x",
  380. ui->preview->GetScrollX());
  381. obs_data_set_double(saveData, "scaling_off_y",
  382. ui->preview->GetScrollY());
  383. if (api) {
  384. obs_data_t *moduleObj = obs_data_create();
  385. api->on_save(moduleObj);
  386. obs_data_set_obj(saveData, "modules", moduleObj);
  387. obs_data_release(moduleObj);
  388. }
  389. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  390. blog(LOG_ERROR, "Could not save scene data to %s", file);
  391. obs_data_release(saveData);
  392. obs_data_array_release(sceneOrder);
  393. obs_data_array_release(quickTrData);
  394. obs_data_array_release(transitions);
  395. obs_data_array_release(savedProjectorList);
  396. obs_data_array_release(savedPreviewProjectorList);
  397. }
  398. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  399. {
  400. obs_data_t *data = obs_data_get_obj(parent, name);
  401. if (!data)
  402. return;
  403. obs_source_t *source = obs_load_source(data);
  404. if (source) {
  405. obs_set_output_source(channel, source);
  406. obs_source_release(source);
  407. }
  408. obs_data_release(data);
  409. }
  410. static inline bool HasAudioDevices(const char *source_id)
  411. {
  412. const char *output_id = source_id;
  413. obs_properties_t *props = obs_get_source_properties(output_id);
  414. size_t count = 0;
  415. if (!props)
  416. return false;
  417. obs_property_t *devices = obs_properties_get(props, "device_id");
  418. if (devices)
  419. count = obs_property_list_item_count(devices);
  420. obs_properties_destroy(props);
  421. return count != 0;
  422. }
  423. void OBSBasic::CreateFirstRunSources()
  424. {
  425. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  426. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  427. if (hasDesktopAudio)
  428. ResetAudioDevice(App()->OutputAudioSource(), "default",
  429. Str("Basic.DesktopDevice1"), 1);
  430. if (hasInputAudio)
  431. ResetAudioDevice(App()->InputAudioSource(), "default",
  432. Str("Basic.AuxDevice1"), 3);
  433. }
  434. void OBSBasic::CreateDefaultScene(bool firstStart)
  435. {
  436. disableSaving++;
  437. ClearSceneData();
  438. InitDefaultTransitions();
  439. CreateDefaultQuickTransitions();
  440. ui->transitionDuration->setValue(300);
  441. SetTransition(fadeTransition);
  442. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  443. if (firstStart)
  444. CreateFirstRunSources();
  445. AddScene(obs_scene_get_source(scene));
  446. SetCurrentScene(scene, true);
  447. obs_scene_release(scene);
  448. disableSaving--;
  449. }
  450. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  451. {
  452. for (int i = 0; i < lw->count(); i++) {
  453. QListWidgetItem *item = lw->item(i);
  454. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  455. if (newIndex != i) {
  456. item = lw->takeItem(i);
  457. lw->insertItem(newIndex, item);
  458. }
  459. break;
  460. }
  461. }
  462. }
  463. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  464. {
  465. size_t num = obs_data_array_count(array);
  466. for (size_t i = 0; i < num; i++) {
  467. obs_data_t *data = obs_data_array_item(array, i);
  468. const char *name = obs_data_get_string(data, "name");
  469. ReorderItemByName(ui->scenes, name, (int)i);
  470. obs_data_release(data);
  471. }
  472. }
  473. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  474. {
  475. size_t num = obs_data_array_count(array);
  476. for (size_t i = 0; i < num; i++) {
  477. obs_data_t *data = obs_data_array_item(array, i);
  478. projectorArray.at(i) = obs_data_get_string(data,
  479. "saved_projectors");
  480. obs_data_release(data);
  481. }
  482. }
  483. void OBSBasic::LoadSavedPreviewProjectors(obs_data_array_t *array)
  484. {
  485. size_t num = obs_data_array_count(array);
  486. for (size_t i = 0; i < num; i++) {
  487. obs_data_t *data = obs_data_array_item(array, i);
  488. previewProjectorArray.at(i) = obs_data_get_int(data,
  489. "saved_preview_projectors");
  490. obs_data_release(data);
  491. }
  492. }
  493. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  494. {
  495. const char *name = obs_source_get_name(filter);
  496. const char *id = obs_source_get_id(filter);
  497. int val = (int)(intptr_t)v_val;
  498. string indent;
  499. for (int i = 0; i < val; i++)
  500. indent += " ";
  501. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  502. }
  503. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  504. {
  505. obs_source_t *source = obs_sceneitem_get_source(item);
  506. const char *name = obs_source_get_name(source);
  507. const char *id = obs_source_get_id(source);
  508. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  509. obs_monitoring_type monitoring_type =
  510. obs_source_get_monitoring_type(source);
  511. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  512. const char *type =
  513. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  514. ? "monitor only"
  515. : "monitor and output";
  516. blog(LOG_INFO, " - monitoring: %s", type);
  517. }
  518. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  519. return true;
  520. }
  521. void OBSBasic::LogScenes()
  522. {
  523. blog(LOG_INFO, "------------------------------------------------");
  524. blog(LOG_INFO, "Loaded scenes:");
  525. for (int i = 0; i < ui->scenes->count(); i++) {
  526. QListWidgetItem *item = ui->scenes->item(i);
  527. OBSScene scene = GetOBSRef<OBSScene>(item);
  528. obs_source_t *source = obs_scene_get_source(scene);
  529. const char *name = obs_source_get_name(source);
  530. blog(LOG_INFO, "- scene '%s':", name);
  531. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  532. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  533. }
  534. blog(LOG_INFO, "------------------------------------------------");
  535. }
  536. void OBSBasic::Load(const char *file)
  537. {
  538. disableSaving++;
  539. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  540. if (!data) {
  541. disableSaving--;
  542. blog(LOG_INFO, "No scene file found, creating default scene");
  543. CreateDefaultScene(true);
  544. SaveProject();
  545. return;
  546. }
  547. ClearSceneData();
  548. InitDefaultTransitions();
  549. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  550. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  551. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  552. const char *sceneName = obs_data_get_string(data,
  553. "current_scene");
  554. const char *programSceneName = obs_data_get_string(data,
  555. "current_program_scene");
  556. const char *transitionName = obs_data_get_string(data,
  557. "current_transition");
  558. if (!opt_starting_scene.empty()) {
  559. programSceneName = opt_starting_scene.c_str();
  560. if (!IsPreviewProgramMode())
  561. sceneName = opt_starting_scene.c_str();
  562. }
  563. int newDuration = obs_data_get_int(data, "transition_duration");
  564. if (!newDuration)
  565. newDuration = 300;
  566. if (!transitionName)
  567. transitionName = obs_source_get_name(fadeTransition);
  568. const char *curSceneCollection = config_get_string(
  569. App()->GlobalConfig(), "Basic", "SceneCollection");
  570. obs_data_set_default_string(data, "name", curSceneCollection);
  571. const char *name = obs_data_get_string(data, "name");
  572. obs_source_t *curScene;
  573. obs_source_t *curProgramScene;
  574. obs_source_t *curTransition;
  575. if (!name || !*name)
  576. name = curSceneCollection;
  577. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  578. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  579. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  580. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  581. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  582. obs_load_sources(sources, OBSBasic::SourceLoaded, this);
  583. if (transitions)
  584. LoadTransitions(transitions);
  585. if (sceneOrder)
  586. LoadSceneListOrder(sceneOrder);
  587. obs_data_array_release(transitions);
  588. curTransition = FindTransition(transitionName);
  589. if (!curTransition)
  590. curTransition = fadeTransition;
  591. ui->transitionDuration->setValue(newDuration);
  592. SetTransition(curTransition);
  593. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  594. "saved_projectors");
  595. if (savedProjectors)
  596. LoadSavedProjectors(savedProjectors);
  597. obs_data_array_release(savedProjectors);
  598. obs_data_array_t *savedPreviewProjectors = obs_data_get_array(data,
  599. "saved_preview_projectors");
  600. if (savedPreviewProjectors)
  601. LoadSavedPreviewProjectors(savedPreviewProjectors);
  602. obs_data_array_release(savedPreviewProjectors);
  603. retryScene:
  604. curScene = obs_get_source_by_name(sceneName);
  605. curProgramScene = obs_get_source_by_name(programSceneName);
  606. /* if the starting scene command line parameter is bad at all,
  607. * fall back to original settings */
  608. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  609. sceneName = obs_data_get_string(data, "current_scene");
  610. programSceneName = obs_data_get_string(data,
  611. "current_program_scene");
  612. obs_source_release(curScene);
  613. obs_source_release(curProgramScene);
  614. opt_starting_scene.clear();
  615. goto retryScene;
  616. }
  617. if (!curProgramScene) {
  618. curProgramScene = curScene;
  619. obs_source_addref(curScene);
  620. }
  621. SetCurrentScene(curScene, true);
  622. if (IsPreviewProgramMode())
  623. TransitionToScene(curProgramScene, true);
  624. obs_source_release(curScene);
  625. obs_source_release(curProgramScene);
  626. obs_data_array_release(sources);
  627. obs_data_array_release(sceneOrder);
  628. std::string file_base = strrchr(file, '/') + 1;
  629. file_base.erase(file_base.size() - 5, 5);
  630. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  631. name);
  632. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  633. file_base.c_str());
  634. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  635. "quick_transitions");
  636. LoadQuickTransitions(quickTransitionData);
  637. obs_data_array_release(quickTransitionData);
  638. RefreshQuickTransitions();
  639. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  640. ui->preview->SetLocked(previewLocked);
  641. ui->actionLockPreview->setChecked(previewLocked);
  642. /* ---------------------- */
  643. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  644. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  645. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  646. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  647. if (fixedScaling) {
  648. ui->preview->SetScalingLevel(scalingLevel);
  649. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  650. }
  651. ui->preview->SetFixedScaling(fixedScaling);
  652. /* ---------------------- */
  653. if (api) {
  654. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  655. api->on_load(modulesObj);
  656. obs_data_release(modulesObj);
  657. }
  658. obs_data_release(data);
  659. if (!opt_starting_scene.empty())
  660. opt_starting_scene.clear();
  661. if (opt_start_streaming) {
  662. QMetaObject::invokeMethod(this, "StartStreaming",
  663. Qt::QueuedConnection);
  664. opt_start_streaming = false;
  665. }
  666. if (opt_start_recording) {
  667. QMetaObject::invokeMethod(this, "StartRecording",
  668. Qt::QueuedConnection);
  669. opt_start_recording = false;
  670. }
  671. if (opt_start_replaybuffer) {
  672. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  673. Qt::QueuedConnection);
  674. opt_start_replaybuffer = false;
  675. }
  676. LogScenes();
  677. disableSaving--;
  678. }
  679. #define SERVICE_PATH "service.json"
  680. void OBSBasic::SaveService()
  681. {
  682. if (!service)
  683. return;
  684. char serviceJsonPath[512];
  685. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  686. SERVICE_PATH);
  687. if (ret <= 0)
  688. return;
  689. obs_data_t *data = obs_data_create();
  690. obs_data_t *settings = obs_service_get_settings(service);
  691. obs_data_set_string(data, "type", obs_service_get_type(service));
  692. obs_data_set_obj(data, "settings", settings);
  693. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  694. blog(LOG_WARNING, "Failed to save service");
  695. obs_data_release(settings);
  696. obs_data_release(data);
  697. }
  698. bool OBSBasic::LoadService()
  699. {
  700. const char *type;
  701. char serviceJsonPath[512];
  702. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  703. SERVICE_PATH);
  704. if (ret <= 0)
  705. return false;
  706. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  707. "bak");
  708. obs_data_set_default_string(data, "type", "rtmp_common");
  709. type = obs_data_get_string(data, "type");
  710. obs_data_t *settings = obs_data_get_obj(data, "settings");
  711. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  712. service = obs_service_create(type, "default_service", settings,
  713. hotkey_data);
  714. obs_service_release(service);
  715. obs_data_release(hotkey_data);
  716. obs_data_release(settings);
  717. obs_data_release(data);
  718. return !!service;
  719. }
  720. bool OBSBasic::InitService()
  721. {
  722. ProfileScope("OBSBasic::InitService");
  723. if (LoadService())
  724. return true;
  725. service = obs_service_create("rtmp_common", "default_service", nullptr,
  726. nullptr);
  727. if (!service)
  728. return false;
  729. obs_service_release(service);
  730. return true;
  731. }
  732. static const double scaled_vals[] =
  733. {
  734. 1.0,
  735. 1.25,
  736. (1.0/0.75),
  737. 1.5,
  738. (1.0/0.6),
  739. 1.75,
  740. 2.0,
  741. 2.25,
  742. 2.5,
  743. 2.75,
  744. 3.0,
  745. 0.0
  746. };
  747. bool OBSBasic::InitBasicConfigDefaults()
  748. {
  749. QList<QScreen*> screens = QGuiApplication::screens();
  750. if (!screens.size()) {
  751. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  752. "technically shouldn't be possible.");
  753. return false;
  754. }
  755. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  756. uint32_t cx = primaryScreen->size().width();
  757. uint32_t cy = primaryScreen->size().height();
  758. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  759. "General", "Pre19Defaults");
  760. /* use 1920x1080 for new default base res if main monitor is above
  761. * 1920x1080, but don't apply for people from older builds -- only to
  762. * new users */
  763. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  764. cx = 1920;
  765. cy = 1080;
  766. }
  767. /* ----------------------------------------------------- */
  768. /* move over mixer values in advanced if older config */
  769. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  770. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  771. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  772. "RecTrackIndex");
  773. track = 1ULL << (track - 1);
  774. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  775. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  776. config_save_safe(basicConfig, "tmp", nullptr);
  777. }
  778. /* ----------------------------------------------------- */
  779. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  780. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  781. GetDefaultVideoSavePath().c_str());
  782. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  783. "flv");
  784. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  785. 2500);
  786. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  787. SIMPLE_ENCODER_X264);
  788. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  789. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  790. false);
  791. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  792. true);
  793. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  794. "veryfast");
  795. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  796. "Stream");
  797. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  798. SIMPLE_ENCODER_X264);
  799. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  800. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  801. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  802. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  803. "Replay");
  804. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  805. true);
  806. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  807. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  808. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  809. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  810. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  811. GetDefaultVideoSavePath().c_str());
  812. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  813. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  814. false);
  815. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  816. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  817. "none");
  818. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  819. true);
  820. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  821. GetDefaultVideoSavePath().c_str());
  822. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  823. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  824. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  825. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  826. false);
  827. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  828. false);
  829. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  830. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  831. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  832. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  833. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  834. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  835. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  836. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  837. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  838. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  839. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  840. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  841. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  842. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  843. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  844. config_save_safe(basicConfig, "tmp", nullptr);
  845. }
  846. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  847. "%CCYY-%MM-%DD %hh-%mm-%ss");
  848. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  849. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  850. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  851. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  852. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  853. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  854. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  855. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  856. false);
  857. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  858. false);
  859. int i = 0;
  860. uint32_t scale_cx = cx;
  861. uint32_t scale_cy = cy;
  862. /* use a default scaled resolution that has a pixel count no higher
  863. * than 1280x720 */
  864. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  865. double scale = scaled_vals[i++];
  866. scale_cx = uint32_t(double(cx) / scale);
  867. scale_cy = uint32_t(double(cy) / scale);
  868. }
  869. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  870. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  871. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  872. * changing */
  873. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  874. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  875. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  876. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  877. config_save_safe(basicConfig, "tmp", nullptr);
  878. }
  879. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  880. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  881. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  882. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  883. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  884. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  885. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  886. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  887. config_set_default_string(basicConfig, "Video", "ColorRange",
  888. "Partial");
  889. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  890. "default");
  891. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  892. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  893. ".Default"));
  894. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  895. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  896. "Stereo");
  897. return true;
  898. }
  899. bool OBSBasic::InitBasicConfig()
  900. {
  901. ProfileScope("OBSBasic::InitBasicConfig");
  902. char configPath[512];
  903. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  904. if (ret <= 0) {
  905. OBSErrorBox(nullptr, "Failed to get profile path");
  906. return false;
  907. }
  908. if (os_mkdir(configPath) == MKDIR_ERROR) {
  909. OBSErrorBox(nullptr, "Failed to create profile path");
  910. return false;
  911. }
  912. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  913. if (ret <= 0) {
  914. OBSErrorBox(nullptr, "Failed to get base.ini path");
  915. return false;
  916. }
  917. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  918. if (code != CONFIG_SUCCESS) {
  919. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  920. return false;
  921. }
  922. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  923. const char *curName = config_get_string(App()->GlobalConfig(),
  924. "Basic", "Profile");
  925. config_set_string(basicConfig, "General", "Name", curName);
  926. basicConfig.SaveSafe("tmp");
  927. }
  928. return InitBasicConfigDefaults();
  929. }
  930. void OBSBasic::InitOBSCallbacks()
  931. {
  932. ProfileScope("OBSBasic::InitOBSCallbacks");
  933. signalHandlers.reserve(signalHandlers.size() + 6);
  934. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  935. OBSBasic::SourceRemoved, this);
  936. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  937. OBSBasic::SourceActivated, this);
  938. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  939. OBSBasic::SourceDeactivated, this);
  940. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  941. OBSBasic::SourceRenamed, this);
  942. }
  943. void OBSBasic::InitPrimitives()
  944. {
  945. ProfileScope("OBSBasic::InitPrimitives");
  946. obs_enter_graphics();
  947. gs_render_start(true);
  948. gs_vertex2f(0.0f, 0.0f);
  949. gs_vertex2f(0.0f, 1.0f);
  950. gs_vertex2f(1.0f, 1.0f);
  951. gs_vertex2f(1.0f, 0.0f);
  952. gs_vertex2f(0.0f, 0.0f);
  953. box = gs_render_save();
  954. gs_render_start(true);
  955. gs_vertex2f(0.0f, 0.0f);
  956. gs_vertex2f(0.0f, 1.0f);
  957. boxLeft = gs_render_save();
  958. gs_render_start(true);
  959. gs_vertex2f(0.0f, 0.0f);
  960. gs_vertex2f(1.0f, 0.0f);
  961. boxTop = gs_render_save();
  962. gs_render_start(true);
  963. gs_vertex2f(1.0f, 0.0f);
  964. gs_vertex2f(1.0f, 1.0f);
  965. boxRight = gs_render_save();
  966. gs_render_start(true);
  967. gs_vertex2f(0.0f, 1.0f);
  968. gs_vertex2f(1.0f, 1.0f);
  969. boxBottom = gs_render_save();
  970. gs_render_start(true);
  971. for (int i = 0; i <= 360; i += (360/20)) {
  972. float pos = RAD(float(i));
  973. gs_vertex2f(cosf(pos), sinf(pos));
  974. }
  975. circle = gs_render_save();
  976. obs_leave_graphics();
  977. }
  978. void OBSBasic::ReplayBufferClicked()
  979. {
  980. if (outputHandler->ReplayBufferActive())
  981. StopReplayBuffer();
  982. else
  983. StartReplayBuffer();
  984. };
  985. void OBSBasic::ResetOutputs()
  986. {
  987. ProfileScope("OBSBasic::ResetOutputs");
  988. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  989. bool advOut = astrcmpi(mode, "Advanced") == 0;
  990. if (!outputHandler || !outputHandler->Active()) {
  991. outputHandler.reset();
  992. outputHandler.reset(advOut ?
  993. CreateAdvancedOutputHandler(this) :
  994. CreateSimpleOutputHandler(this));
  995. delete replayBufferButton;
  996. if (outputHandler->replayBuffer) {
  997. replayBufferButton = new QPushButton(
  998. QTStr("Basic.Main.StartReplayBuffer"),
  999. this);
  1000. connect(replayBufferButton.data(),
  1001. &QPushButton::clicked,
  1002. this,
  1003. &OBSBasic::ReplayBufferClicked);
  1004. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1005. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1006. }
  1007. if (sysTrayReplayBuffer)
  1008. sysTrayReplayBuffer->setEnabled(
  1009. !!outputHandler->replayBuffer);
  1010. } else {
  1011. outputHandler->Update();
  1012. }
  1013. }
  1014. #define STARTUP_SEPARATOR \
  1015. "==== Startup complete ==============================================="
  1016. #define SHUTDOWN_SEPARATOR \
  1017. "==== Shutting down =================================================="
  1018. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  1019. #define UNSUPPORTED_ERROR \
  1020. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1021. "not found. Your GPU may not be supported."
  1022. #define UNKNOWN_ERROR \
  1023. "Failed to initialize video. Your GPU may not be supported, " \
  1024. "or your graphics drivers may need to be updated."
  1025. void OBSBasic::OBSInit()
  1026. {
  1027. ProfileScope("OBSBasic::OBSInit");
  1028. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1029. "Basic", "SceneCollectionFile");
  1030. char savePath[512];
  1031. char fileName[512];
  1032. int ret;
  1033. if (!sceneCollection)
  1034. throw "Failed to get scene collection name";
  1035. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1036. sceneCollection);
  1037. if (ret <= 0)
  1038. throw "Failed to create scene collection file name";
  1039. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1040. if (ret <= 0)
  1041. throw "Failed to get scene collection json file path";
  1042. if (!InitBasicConfig())
  1043. throw "Failed to load basic.ini";
  1044. if (!ResetAudio())
  1045. throw "Failed to initialize audio";
  1046. ret = ResetVideo();
  1047. switch (ret) {
  1048. case OBS_VIDEO_MODULE_NOT_FOUND:
  1049. throw "Failed to initialize video: Graphics module not found";
  1050. case OBS_VIDEO_NOT_SUPPORTED:
  1051. throw UNSUPPORTED_ERROR;
  1052. case OBS_VIDEO_INVALID_PARAM:
  1053. throw "Failed to initialize video: Invalid parameters";
  1054. default:
  1055. if (ret != OBS_VIDEO_SUCCESS)
  1056. throw UNKNOWN_ERROR;
  1057. }
  1058. /* load audio monitoring */
  1059. #if defined(_WIN32) || defined(__APPLE__)
  1060. const char *device_name = config_get_string(basicConfig, "Audio",
  1061. "MonitoringDeviceName");
  1062. const char *device_id = config_get_string(basicConfig, "Audio",
  1063. "MonitoringDeviceId");
  1064. obs_set_audio_monitoring_device(device_name, device_id);
  1065. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1066. device_name, device_id);
  1067. #endif
  1068. InitOBSCallbacks();
  1069. InitHotkeys();
  1070. api = InitializeAPIInterface(this);
  1071. AddExtraModulePaths();
  1072. blog(LOG_INFO, "---------------------------------");
  1073. obs_load_all_modules();
  1074. blog(LOG_INFO, "---------------------------------");
  1075. obs_log_loaded_modules();
  1076. blog(LOG_INFO, "---------------------------------");
  1077. obs_post_load_modules();
  1078. blog(LOG_INFO, STARTUP_SEPARATOR);
  1079. ResetOutputs();
  1080. CreateHotkeys();
  1081. if (!InitService())
  1082. throw "Failed to initialize service";
  1083. InitPrimitives();
  1084. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1085. "BasicWindow", "SceneDuplicationMode");
  1086. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1087. "BasicWindow", "SwapScenesMode");
  1088. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1089. "BasicWindow", "EditPropertiesMode");
  1090. if (!opt_studio_mode) {
  1091. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1092. "BasicWindow", "PreviewProgramMode"));
  1093. } else {
  1094. SetPreviewProgramMode(true);
  1095. opt_studio_mode = false;
  1096. }
  1097. #define SET_VISIBILITY(name, control) \
  1098. do { \
  1099. if (config_has_user_value(App()->GlobalConfig(), \
  1100. "BasicWindow", name)) { \
  1101. bool visible = config_get_bool(App()->GlobalConfig(), \
  1102. "BasicWindow", name); \
  1103. ui->control->setChecked(visible); \
  1104. } \
  1105. } while (false)
  1106. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1107. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1108. #undef SET_VISIBILITY
  1109. {
  1110. ProfileScope("OBSBasic::Load");
  1111. disableSaving--;
  1112. Load(savePath);
  1113. disableSaving++;
  1114. }
  1115. TimedCheckForUpdates();
  1116. loaded = true;
  1117. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1118. "BasicWindow", "PreviewEnabled");
  1119. if (!previewEnabled && !IsPreviewProgramMode())
  1120. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1121. Qt::QueuedConnection,
  1122. Q_ARG(bool, previewEnabled));
  1123. #ifdef _WIN32
  1124. uint32_t winVer = GetWindowsVersion();
  1125. if (winVer > 0 && winVer < 0x602) {
  1126. bool disableAero = config_get_bool(basicConfig, "Video",
  1127. "DisableAero");
  1128. SetAeroEnabled(!disableAero);
  1129. }
  1130. #endif
  1131. RefreshSceneCollections();
  1132. RefreshProfiles();
  1133. disableSaving--;
  1134. auto addDisplay = [this] (OBSQTDisplay *window)
  1135. {
  1136. obs_display_add_draw_callback(window->GetDisplay(),
  1137. OBSBasic::RenderMain, this);
  1138. struct obs_video_info ovi;
  1139. if (obs_get_video_info(&ovi))
  1140. ResizePreview(ovi.base_width, ovi.base_height);
  1141. };
  1142. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1143. #ifdef _WIN32
  1144. SetWin32DropStyle(this);
  1145. show();
  1146. #endif
  1147. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1148. "AlwaysOnTop");
  1149. if (alwaysOnTop || opt_always_on_top) {
  1150. SetAlwaysOnTop(this, true);
  1151. ui->actionAlwaysOnTop->setChecked(true);
  1152. }
  1153. #ifndef _WIN32
  1154. show();
  1155. #endif
  1156. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1157. "BasicWindow", "DockState");
  1158. if (!dockStateStr) {
  1159. on_resetUI_triggered();
  1160. } else {
  1161. QByteArray dockState =
  1162. QByteArray::fromBase64(QByteArray(dockStateStr));
  1163. if (!restoreState(dockState))
  1164. on_resetUI_triggered();
  1165. }
  1166. config_set_default_bool(App()->GlobalConfig(), "BasicWindow",
  1167. "DocksLocked", true);
  1168. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1169. "BasicWindow", "DocksLocked");
  1170. on_lockUI_toggled(docksLocked);
  1171. ui->lockUI->blockSignals(true);
  1172. ui->lockUI->setChecked(docksLocked);
  1173. ui->lockUI->blockSignals(false);
  1174. SystemTray(true);
  1175. OpenSavedProjectors();
  1176. if (windowState().testFlag(Qt::WindowFullScreen))
  1177. fullscreenInterface = true;
  1178. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1179. "General", "LastVersion");
  1180. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1181. "FirstRun");
  1182. if (!first_run) {
  1183. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1184. true);
  1185. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1186. }
  1187. if (!first_run && !has_last_version && !Active()) {
  1188. QString msg;
  1189. msg = QTStr("Basic.FirstStartup.RunWizard");
  1190. msg += "\n\n";
  1191. msg += QTStr("Basic.FirstStartup.RunWizard.BetaWarning");
  1192. QMessageBox::StandardButton button =
  1193. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1194. msg);
  1195. if (button == QMessageBox::Yes) {
  1196. on_autoConfigure_triggered();
  1197. } else {
  1198. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1199. OBSMessageBox::information(this,
  1200. QTStr("Basic.AutoConfig"), msg);
  1201. }
  1202. }
  1203. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1204. on_stats_triggered();
  1205. OBSBasicStats::InitializeValues();
  1206. }
  1207. void OBSBasic::InitHotkeys()
  1208. {
  1209. ProfileScope("OBSBasic::InitHotkeys");
  1210. struct obs_hotkeys_translations t = {};
  1211. t.insert = Str("Hotkeys.Insert");
  1212. t.del = Str("Hotkeys.Delete");
  1213. t.home = Str("Hotkeys.Home");
  1214. t.end = Str("Hotkeys.End");
  1215. t.page_up = Str("Hotkeys.PageUp");
  1216. t.page_down = Str("Hotkeys.PageDown");
  1217. t.num_lock = Str("Hotkeys.NumLock");
  1218. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1219. t.caps_lock = Str("Hotkeys.CapsLock");
  1220. t.backspace = Str("Hotkeys.Backspace");
  1221. t.tab = Str("Hotkeys.Tab");
  1222. t.print = Str("Hotkeys.Print");
  1223. t.pause = Str("Hotkeys.Pause");
  1224. t.left = Str("Hotkeys.Left");
  1225. t.right = Str("Hotkeys.Right");
  1226. t.up = Str("Hotkeys.Up");
  1227. t.down = Str("Hotkeys.Down");
  1228. #ifdef _WIN32
  1229. t.meta = Str("Hotkeys.Windows");
  1230. #else
  1231. t.meta = Str("Hotkeys.Super");
  1232. #endif
  1233. t.menu = Str("Hotkeys.Menu");
  1234. t.space = Str("Hotkeys.Space");
  1235. t.numpad_num = Str("Hotkeys.NumpadNum");
  1236. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1237. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1238. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1239. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1240. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1241. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1242. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1243. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1244. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1245. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1246. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1247. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1248. t.mouse_num = Str("Hotkeys.MouseButton");
  1249. obs_hotkeys_set_translations(&t);
  1250. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1251. Str("Push-to-mute"), Str("Push-to-talk"));
  1252. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1253. Str("SceneItemShow"), Str("SceneItemHide"));
  1254. obs_hotkey_enable_callback_rerouting(true);
  1255. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1256. }
  1257. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1258. {
  1259. obs_hotkey_trigger_routed_callback(id, pressed);
  1260. }
  1261. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1262. {
  1263. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1264. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1265. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1266. }
  1267. void OBSBasic::CreateHotkeys()
  1268. {
  1269. ProfileScope("OBSBasic::CreateHotkeys");
  1270. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1271. {
  1272. const char *info = config_get_string(basicConfig,
  1273. "Hotkeys", name);
  1274. if (!info)
  1275. return {};
  1276. obs_data_t *data = obs_data_create_from_json(info);
  1277. if (!data)
  1278. return {};
  1279. OBSData res = data;
  1280. obs_data_release(data);
  1281. return res;
  1282. };
  1283. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1284. {
  1285. obs_data_array_t *array =
  1286. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1287. obs_hotkey_load(id, array);
  1288. obs_data_array_release(array);
  1289. };
  1290. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1291. const char *name1)
  1292. {
  1293. obs_data_array_t *array0 =
  1294. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1295. obs_data_array_t *array1 =
  1296. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1297. obs_hotkey_pair_load(id, array0, array1);
  1298. obs_data_array_release(array0);
  1299. obs_data_array_release(array1);
  1300. };
  1301. #define MAKE_CALLBACK(pred, method) \
  1302. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1303. { \
  1304. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1305. if (pred && pressed) { \
  1306. method(); \
  1307. return true; \
  1308. } \
  1309. return false; \
  1310. }
  1311. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1312. "OBSBasic.StartStreaming",
  1313. Str("Basic.Main.StartStreaming"),
  1314. "OBSBasic.StopStreaming",
  1315. Str("Basic.Main.StopStreaming"),
  1316. MAKE_CALLBACK(!basic.outputHandler->StreamingActive(),
  1317. basic.StartStreaming),
  1318. MAKE_CALLBACK(basic.outputHandler->StreamingActive(),
  1319. basic.StopStreaming),
  1320. this, this);
  1321. LoadHotkeyPair(streamingHotkeys,
  1322. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1323. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1324. {
  1325. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1326. if (basic.outputHandler->StreamingActive() && pressed) {
  1327. basic.ForceStopStreaming();
  1328. }
  1329. };
  1330. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1331. "OBSBasic.ForceStopStreaming",
  1332. Str("Basic.Main.ForceStopStreaming"),
  1333. cb, this);
  1334. LoadHotkey(forceStreamingStopHotkey,
  1335. "OBSBasic.ForceStopStreaming");
  1336. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1337. "OBSBasic.StartRecording",
  1338. Str("Basic.Main.StartRecording"),
  1339. "OBSBasic.StopRecording",
  1340. Str("Basic.Main.StopRecording"),
  1341. MAKE_CALLBACK(!basic.outputHandler->RecordingActive(),
  1342. basic.StartRecording),
  1343. MAKE_CALLBACK(basic.outputHandler->RecordingActive(),
  1344. basic.StopRecording),
  1345. this, this);
  1346. LoadHotkeyPair(recordingHotkeys,
  1347. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1348. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1349. "OBSBasic.StartReplayBuffer",
  1350. Str("Basic.Main.StartReplayBuffer"),
  1351. "OBSBasic.StopReplayBuffer",
  1352. Str("Basic.Main.StopReplayBuffer"),
  1353. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1354. basic.StartReplayBuffer),
  1355. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1356. basic.StopReplayBuffer),
  1357. this, this);
  1358. LoadHotkeyPair(replayBufHotkeys,
  1359. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1360. #undef MAKE_CALLBACK
  1361. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1362. obs_hotkey_t*, bool pressed)
  1363. {
  1364. if (pressed)
  1365. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1366. "on_modeSwitch_clicked",
  1367. Qt::QueuedConnection);
  1368. };
  1369. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1370. "OBSBasic.TogglePreviewProgram",
  1371. Str("Basic.TogglePreviewProgramMode"),
  1372. togglePreviewProgram, this);
  1373. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1374. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1375. bool pressed)
  1376. {
  1377. if (pressed)
  1378. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1379. "TransitionClicked",
  1380. Qt::QueuedConnection);
  1381. };
  1382. transitionHotkey = obs_hotkey_register_frontend(
  1383. "OBSBasic.Transition",
  1384. Str("Transition"), transition, this);
  1385. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1386. }
  1387. void OBSBasic::ClearHotkeys()
  1388. {
  1389. obs_hotkey_pair_unregister(streamingHotkeys);
  1390. obs_hotkey_pair_unregister(recordingHotkeys);
  1391. obs_hotkey_pair_unregister(replayBufHotkeys);
  1392. obs_hotkey_unregister(forceStreamingStopHotkey);
  1393. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1394. obs_hotkey_unregister(transitionHotkey);
  1395. }
  1396. OBSBasic::~OBSBasic()
  1397. {
  1398. if (updateCheckThread && updateCheckThread->isRunning())
  1399. updateCheckThread->wait();
  1400. delete programOptions;
  1401. delete program;
  1402. /* XXX: any obs data must be released before calling obs_shutdown.
  1403. * currently, we can't automate this with C++ RAII because of the
  1404. * delicate nature of obs_shutdown needing to be freed before the UI
  1405. * can be freed, and we have no control over the destruction order of
  1406. * the Qt UI stuff, so we have to manually clear any references to
  1407. * libobs. */
  1408. delete cpuUsageTimer;
  1409. os_cpu_usage_info_destroy(cpuUsageInfo);
  1410. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1411. ClearHotkeys();
  1412. service = nullptr;
  1413. outputHandler.reset();
  1414. if (interaction)
  1415. delete interaction;
  1416. if (properties)
  1417. delete properties;
  1418. if (filters)
  1419. delete filters;
  1420. if (transformWindow)
  1421. delete transformWindow;
  1422. if (advAudioWindow)
  1423. delete advAudioWindow;
  1424. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1425. OBSBasic::RenderMain, this);
  1426. obs_enter_graphics();
  1427. gs_vertexbuffer_destroy(box);
  1428. gs_vertexbuffer_destroy(boxLeft);
  1429. gs_vertexbuffer_destroy(boxTop);
  1430. gs_vertexbuffer_destroy(boxRight);
  1431. gs_vertexbuffer_destroy(boxBottom);
  1432. gs_vertexbuffer_destroy(circle);
  1433. obs_leave_graphics();
  1434. /* When shutting down, sometimes source references can get in to the
  1435. * event queue, and if we don't forcibly process those events they
  1436. * won't get processed until after obs_shutdown has been called. I
  1437. * really wish there were a more elegant way to deal with this via C++,
  1438. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1439. * normal C++ behavior for your data to be freed in the order that you
  1440. * expect or want it to. */
  1441. QApplication::sendPostedEvents(this);
  1442. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1443. LIBOBS_API_VER);
  1444. bool alwaysOnTop = IsAlwaysOnTop(this);
  1445. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1446. previewEnabled);
  1447. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1448. alwaysOnTop);
  1449. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1450. "SceneDuplicationMode", sceneDuplicationMode);
  1451. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1452. "SwapScenesMode", swapScenesMode);
  1453. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1454. "EditPropertiesMode", editPropertiesMode);
  1455. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1456. "PreviewProgramMode", IsPreviewProgramMode());
  1457. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1458. "DocksLocked", ui->lockUI->isChecked());
  1459. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1460. #ifdef _WIN32
  1461. uint32_t winVer = GetWindowsVersion();
  1462. if (winVer > 0 && winVer < 0x602) {
  1463. bool disableAero = config_get_bool(basicConfig, "Video",
  1464. "DisableAero");
  1465. if (disableAero) {
  1466. SetAeroEnabled(true);
  1467. }
  1468. }
  1469. #endif
  1470. }
  1471. void OBSBasic::SaveProjectNow()
  1472. {
  1473. if (disableSaving)
  1474. return;
  1475. projectChanged = true;
  1476. SaveProjectDeferred();
  1477. }
  1478. void OBSBasic::SaveProject()
  1479. {
  1480. if (disableSaving)
  1481. return;
  1482. projectChanged = true;
  1483. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1484. Qt::QueuedConnection);
  1485. }
  1486. void OBSBasic::SaveProjectDeferred()
  1487. {
  1488. if (disableSaving)
  1489. return;
  1490. if (!projectChanged)
  1491. return;
  1492. projectChanged = false;
  1493. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1494. "Basic", "SceneCollectionFile");
  1495. char savePath[512];
  1496. char fileName[512];
  1497. int ret;
  1498. if (!sceneCollection)
  1499. return;
  1500. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1501. sceneCollection);
  1502. if (ret <= 0)
  1503. return;
  1504. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1505. if (ret <= 0)
  1506. return;
  1507. Save(savePath);
  1508. }
  1509. OBSScene OBSBasic::GetCurrentScene()
  1510. {
  1511. QListWidgetItem *item = ui->scenes->currentItem();
  1512. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1513. }
  1514. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1515. {
  1516. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1517. }
  1518. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1519. {
  1520. return GetSceneItem(GetTopSelectedSourceItem());
  1521. }
  1522. void OBSBasic::UpdatePreviewScalingMenu()
  1523. {
  1524. bool fixedScaling = ui->preview->IsFixedScaling();
  1525. float scalingAmount = ui->preview->GetScalingAmount();
  1526. if (!fixedScaling) {
  1527. ui->actionScaleWindow->setChecked(true);
  1528. ui->actionScaleCanvas->setChecked(false);
  1529. ui->actionScaleOutput->setChecked(false);
  1530. return;
  1531. }
  1532. obs_video_info ovi;
  1533. obs_get_video_info(&ovi);
  1534. ui->actionScaleWindow->setChecked(false);
  1535. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1536. ui->actionScaleOutput->setChecked(
  1537. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1538. }
  1539. void OBSBasic::UpdateSources(OBSScene scene)
  1540. {
  1541. ClearListItems(ui->sources);
  1542. obs_scene_enum_items(scene,
  1543. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  1544. {
  1545. OBSBasic *window = static_cast<OBSBasic*>(p);
  1546. window->InsertSceneItem(item);
  1547. UNUSED_PARAMETER(scene);
  1548. return true;
  1549. }, this);
  1550. }
  1551. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  1552. {
  1553. QListWidgetItem *listItem = new QListWidgetItem();
  1554. SetOBSRef(listItem, OBSSceneItem(item));
  1555. ui->sources->insertItem(0, listItem);
  1556. ui->sources->setCurrentRow(0, QItemSelectionModel::ClearAndSelect);
  1557. SetupVisibilityItem(ui->sources, listItem, item);
  1558. }
  1559. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1560. {
  1561. if (interaction)
  1562. interaction->close();
  1563. interaction = new OBSBasicInteraction(this, source);
  1564. interaction->Init();
  1565. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1566. }
  1567. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1568. {
  1569. if (properties)
  1570. properties->close();
  1571. properties = new OBSBasicProperties(this, source);
  1572. properties->Init();
  1573. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1574. }
  1575. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1576. {
  1577. if (filters)
  1578. filters->close();
  1579. filters = new OBSBasicFilters(this, source);
  1580. filters->Init();
  1581. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1582. }
  1583. /* Qt callbacks for invokeMethod */
  1584. void OBSBasic::AddScene(OBSSource source)
  1585. {
  1586. const char *name = obs_source_get_name(source);
  1587. obs_scene_t *scene = obs_scene_from_source(source);
  1588. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1589. SetOBSRef(item, OBSScene(scene));
  1590. ui->scenes->addItem(item);
  1591. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1592. Str("Basic.Hotkeys.SelectScene"),
  1593. [](void *data,
  1594. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1595. {
  1596. OBSBasic *main =
  1597. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1598. auto potential_source = static_cast<obs_source_t*>(data);
  1599. auto source = obs_source_get_ref(potential_source);
  1600. if (source && pressed)
  1601. main->SetCurrentScene(source);
  1602. obs_source_release(source);
  1603. }, static_cast<obs_source_t*>(source));
  1604. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1605. SignalContainer<OBSScene> container;
  1606. container.ref = scene;
  1607. container.handlers.assign({
  1608. std::make_shared<OBSSignal>(handler, "item_add",
  1609. OBSBasic::SceneItemAdded, this),
  1610. std::make_shared<OBSSignal>(handler, "item_remove",
  1611. OBSBasic::SceneItemRemoved, this),
  1612. std::make_shared<OBSSignal>(handler, "item_select",
  1613. OBSBasic::SceneItemSelected, this),
  1614. std::make_shared<OBSSignal>(handler, "item_deselect",
  1615. OBSBasic::SceneItemDeselected, this),
  1616. std::make_shared<OBSSignal>(handler, "reorder",
  1617. OBSBasic::SceneReordered, this),
  1618. });
  1619. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  1620. QVariant::fromValue(container));
  1621. /* if the scene already has items (a duplicated scene) add them */
  1622. auto addSceneItem = [this] (obs_sceneitem_t *item)
  1623. {
  1624. AddSceneItem(item);
  1625. };
  1626. using addSceneItem_t = decltype(addSceneItem);
  1627. obs_scene_enum_items(scene,
  1628. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  1629. {
  1630. addSceneItem_t *func;
  1631. func = reinterpret_cast<addSceneItem_t*>(param);
  1632. (*func)(item);
  1633. return true;
  1634. }, &addSceneItem);
  1635. SaveProject();
  1636. if (!disableSaving) {
  1637. obs_source_t *source = obs_scene_get_source(scene);
  1638. blog(LOG_INFO, "User added scene '%s'",
  1639. obs_source_get_name(source));
  1640. }
  1641. if (api)
  1642. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1643. }
  1644. void OBSBasic::RemoveScene(OBSSource source)
  1645. {
  1646. obs_scene_t *scene = obs_scene_from_source(source);
  1647. QListWidgetItem *sel = nullptr;
  1648. int count = ui->scenes->count();
  1649. for (int i = 0; i < count; i++) {
  1650. auto item = ui->scenes->item(i);
  1651. auto cur_scene = GetOBSRef<OBSScene>(item);
  1652. if (cur_scene != scene)
  1653. continue;
  1654. sel = item;
  1655. break;
  1656. }
  1657. if (sel != nullptr) {
  1658. if (sel == ui->scenes->currentItem())
  1659. ClearListItems(ui->sources);
  1660. delete sel;
  1661. }
  1662. SaveProject();
  1663. if (!disableSaving) {
  1664. blog(LOG_INFO, "User Removed scene '%s'",
  1665. obs_source_get_name(source));
  1666. }
  1667. if (api)
  1668. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1669. }
  1670. void OBSBasic::AddSceneItem(OBSSceneItem item)
  1671. {
  1672. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1673. if (GetCurrentScene() == scene)
  1674. InsertSceneItem(item);
  1675. SaveProject();
  1676. if (!disableSaving) {
  1677. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1678. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1679. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  1680. obs_source_get_name(itemSource),
  1681. obs_source_get_id(itemSource),
  1682. obs_source_get_name(sceneSource));
  1683. }
  1684. }
  1685. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  1686. {
  1687. for (int i = 0; i < ui->sources->count(); i++) {
  1688. QListWidgetItem *listItem = ui->sources->item(i);
  1689. if (GetOBSRef<OBSSceneItem>(listItem) == item) {
  1690. DeleteListItem(ui->sources, listItem);
  1691. break;
  1692. }
  1693. }
  1694. SaveProject();
  1695. if (!disableSaving) {
  1696. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1697. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1698. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1699. blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'",
  1700. obs_source_get_name(itemSource),
  1701. obs_source_get_id(itemSource),
  1702. obs_source_get_name(sceneSource));
  1703. }
  1704. }
  1705. void OBSBasic::UpdateSceneSelection(OBSSource source)
  1706. {
  1707. if (source) {
  1708. obs_scene_t *scene = obs_scene_from_source(source);
  1709. const char *name = obs_source_get_name(source);
  1710. if (!scene)
  1711. return;
  1712. QList<QListWidgetItem*> items =
  1713. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  1714. if (items.count()) {
  1715. sceneChanging = true;
  1716. ui->scenes->setCurrentItem(items.first());
  1717. sceneChanging = false;
  1718. UpdateSources(scene);
  1719. }
  1720. }
  1721. }
  1722. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  1723. const QString &prevName)
  1724. {
  1725. QList<QListWidgetItem*> items =
  1726. listWidget->findItems(prevName, Qt::MatchExactly);
  1727. for (int i = 0; i < items.count(); i++)
  1728. items[i]->setText(newName);
  1729. }
  1730. void OBSBasic::RenameSources(QString newName, QString prevName)
  1731. {
  1732. RenameListValues(ui->scenes, newName, prevName);
  1733. for (size_t i = 0; i < volumes.size(); i++) {
  1734. if (volumes[i]->GetName().compare(prevName) == 0)
  1735. volumes[i]->SetName(newName);
  1736. }
  1737. std::string newText = newName.toUtf8().constData();
  1738. std::string prevText = prevName.toUtf8().constData();
  1739. for (size_t j = 0; j < projectorArray.size(); j++) {
  1740. if (projectorArray.at(j) == prevText)
  1741. projectorArray.at(j) = newText;
  1742. }
  1743. SaveProject();
  1744. }
  1745. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  1746. {
  1747. SignalBlocker sourcesSignalBlocker(ui->sources);
  1748. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  1749. return;
  1750. for (int i = 0; i < ui->sources->count(); i++) {
  1751. QListWidgetItem *witem = ui->sources->item(i);
  1752. QVariant data =
  1753. witem->data(static_cast<int>(QtDataRole::OBSRef));
  1754. if (!data.canConvert<OBSSceneItem>())
  1755. continue;
  1756. if (item != data.value<OBSSceneItem>())
  1757. continue;
  1758. witem->setSelected(select);
  1759. break;
  1760. }
  1761. }
  1762. void OBSBasic::GetAudioSourceFilters()
  1763. {
  1764. QAction *action = reinterpret_cast<QAction*>(sender());
  1765. VolControl *vol = action->property("volControl").value<VolControl*>();
  1766. obs_source_t *source = vol->GetSource();
  1767. CreateFiltersWindow(source);
  1768. }
  1769. void OBSBasic::GetAudioSourceProperties()
  1770. {
  1771. QAction *action = reinterpret_cast<QAction*>(sender());
  1772. VolControl *vol = action->property("volControl").value<VolControl*>();
  1773. obs_source_t *source = vol->GetSource();
  1774. CreatePropertiesWindow(source);
  1775. }
  1776. void OBSBasic::VolControlContextMenu()
  1777. {
  1778. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1779. QAction filtersAction(QTStr("Filters"), this);
  1780. QAction propertiesAction(QTStr("Properties"), this);
  1781. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1782. connect(&filtersAction, &QAction::triggered,
  1783. this, &OBSBasic::GetAudioSourceFilters,
  1784. Qt::DirectConnection);
  1785. connect(&propertiesAction, &QAction::triggered,
  1786. this, &OBSBasic::GetAudioSourceProperties,
  1787. Qt::DirectConnection);
  1788. connect(&advPropAction, &QAction::triggered,
  1789. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1790. Qt::DirectConnection);
  1791. filtersAction.setProperty("volControl",
  1792. QVariant::fromValue<VolControl*>(vol));
  1793. propertiesAction.setProperty("volControl",
  1794. QVariant::fromValue<VolControl*>(vol));
  1795. QMenu popup(this);
  1796. popup.addAction(&filtersAction);
  1797. popup.addAction(&propertiesAction);
  1798. popup.addAction(&advPropAction);
  1799. popup.exec(QCursor::pos());
  1800. }
  1801. void OBSBasic::ActivateAudioSource(OBSSource source)
  1802. {
  1803. VolControl *vol = new VolControl(source, true);
  1804. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  1805. connect(vol, &QWidget::customContextMenuRequested,
  1806. this, &OBSBasic::VolControlContextMenu);
  1807. connect(vol, &VolControl::ConfigClicked,
  1808. this, &OBSBasic::VolControlContextMenu);
  1809. volumes.push_back(vol);
  1810. ui->volumeWidgets->layout()->addWidget(vol);
  1811. }
  1812. void OBSBasic::DeactivateAudioSource(OBSSource source)
  1813. {
  1814. for (size_t i = 0; i < volumes.size(); i++) {
  1815. if (volumes[i]->GetSource() == source) {
  1816. delete volumes[i];
  1817. volumes.erase(volumes.begin() + i);
  1818. break;
  1819. }
  1820. }
  1821. }
  1822. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  1823. {
  1824. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE) {
  1825. int count = ui->scenes->count();
  1826. if (count == 1) {
  1827. OBSMessageBox::information(this,
  1828. QTStr("FinalScene.Title"),
  1829. QTStr("FinalScene.Text"));
  1830. return false;
  1831. }
  1832. }
  1833. const char *name = obs_source_get_name(source);
  1834. QString text = QTStr("ConfirmRemove.Text");
  1835. text.replace("$1", QT_UTF8(name));
  1836. QMessageBox remove_source(this);
  1837. remove_source.setText(text);
  1838. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  1839. QMessageBox::YesRole);
  1840. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  1841. remove_source.setIcon(QMessageBox::Question);
  1842. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  1843. remove_source.exec();
  1844. return Yes == remove_source.clickedButton();
  1845. }
  1846. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  1847. #ifdef UPDATE_SPARKLE
  1848. void init_sparkle_updater(bool update_to_undeployed);
  1849. void trigger_sparkle_update();
  1850. #endif
  1851. void OBSBasic::TimedCheckForUpdates()
  1852. {
  1853. if (!config_get_bool(App()->GlobalConfig(), "General",
  1854. "EnableAutoUpdates"))
  1855. return;
  1856. #ifdef UPDATE_SPARKLE
  1857. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  1858. "UpdateToUndeployed"));
  1859. #elif ENABLE_WIN_UPDATER
  1860. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  1861. "LastUpdateCheck");
  1862. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1863. "LastVersion");
  1864. if (lastVersion < LIBOBS_API_VER) {
  1865. lastUpdate = 0;
  1866. config_set_int(App()->GlobalConfig(), "General",
  1867. "LastUpdateCheck", 0);
  1868. }
  1869. long long t = (long long)time(nullptr);
  1870. long long secs = t - lastUpdate;
  1871. if (secs > UPDATE_CHECK_INTERVAL)
  1872. CheckForUpdates(false);
  1873. #endif
  1874. }
  1875. void OBSBasic::CheckForUpdates(bool manualUpdate)
  1876. {
  1877. #ifdef UPDATE_SPARKLE
  1878. trigger_sparkle_update();
  1879. #elif ENABLE_WIN_UPDATER
  1880. ui->actionCheckForUpdates->setEnabled(false);
  1881. if (updateCheckThread && updateCheckThread->isRunning())
  1882. return;
  1883. updateCheckThread = new AutoUpdateThread(manualUpdate);
  1884. updateCheckThread->start();
  1885. #endif
  1886. UNUSED_PARAMETER(manualUpdate);
  1887. }
  1888. void OBSBasic::updateCheckFinished()
  1889. {
  1890. ui->actionCheckForUpdates->setEnabled(true);
  1891. }
  1892. void OBSBasic::DuplicateSelectedScene()
  1893. {
  1894. OBSScene curScene = GetCurrentScene();
  1895. if (!curScene)
  1896. return;
  1897. OBSSource curSceneSource = obs_scene_get_source(curScene);
  1898. QString format{obs_source_get_name(curSceneSource)};
  1899. format += " %1";
  1900. int i = 2;
  1901. QString placeHolderText = format.arg(i);
  1902. obs_source_t *source = nullptr;
  1903. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1904. obs_source_release(source);
  1905. placeHolderText = format.arg(++i);
  1906. }
  1907. for (;;) {
  1908. string name;
  1909. bool accepted = NameDialog::AskForName(this,
  1910. QTStr("Basic.Main.AddSceneDlg.Title"),
  1911. QTStr("Basic.Main.AddSceneDlg.Text"),
  1912. name,
  1913. placeHolderText);
  1914. if (!accepted)
  1915. return;
  1916. if (name.empty()) {
  1917. OBSMessageBox::information(this,
  1918. QTStr("NoNameEntered.Title"),
  1919. QTStr("NoNameEntered.Text"));
  1920. continue;
  1921. }
  1922. obs_source_t *source = obs_get_source_by_name(name.c_str());
  1923. if (source) {
  1924. OBSMessageBox::information(this,
  1925. QTStr("NameExists.Title"),
  1926. QTStr("NameExists.Text"));
  1927. obs_source_release(source);
  1928. continue;
  1929. }
  1930. obs_scene_t *scene = obs_scene_duplicate(curScene,
  1931. name.c_str(), OBS_SCENE_DUP_REFS);
  1932. source = obs_scene_get_source(scene);
  1933. AddScene(source);
  1934. SetCurrentScene(source, true);
  1935. obs_scene_release(scene);
  1936. break;
  1937. }
  1938. }
  1939. void OBSBasic::RemoveSelectedScene()
  1940. {
  1941. OBSScene scene = GetCurrentScene();
  1942. if (scene) {
  1943. obs_source_t *source = obs_scene_get_source(scene);
  1944. if (QueryRemoveSource(source)) {
  1945. obs_source_remove(source);
  1946. if (api)
  1947. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1948. }
  1949. }
  1950. }
  1951. void OBSBasic::RemoveSelectedSceneItem()
  1952. {
  1953. OBSSceneItem item = GetCurrentSceneItem();
  1954. if (item) {
  1955. obs_source_t *source = obs_sceneitem_get_source(item);
  1956. if (QueryRemoveSource(source))
  1957. obs_sceneitem_remove(item);
  1958. }
  1959. }
  1960. struct ReorderInfo {
  1961. int idx = 0;
  1962. OBSBasic *window;
  1963. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  1964. };
  1965. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  1966. {
  1967. int count = ui->sources->count();
  1968. int idx_inv = count - (int)idx - 1;
  1969. for (int i = 0; i < count; i++) {
  1970. QListWidgetItem *listItem = ui->sources->item(i);
  1971. OBSSceneItem sceneItem = GetOBSRef<OBSSceneItem>(listItem);
  1972. if (sceneItem == item) {
  1973. if ((int)idx_inv != i) {
  1974. bool sel = (ui->sources->currentRow() == i);
  1975. listItem = TakeListItem(ui->sources, i);
  1976. if (listItem) {
  1977. ui->sources->insertItem(idx_inv,
  1978. listItem);
  1979. SetupVisibilityItem(ui->sources,
  1980. listItem, item);
  1981. if (sel)
  1982. ui->sources->setCurrentRow(
  1983. idx_inv);
  1984. }
  1985. }
  1986. break;
  1987. }
  1988. }
  1989. }
  1990. void OBSBasic::ReorderSources(OBSScene scene)
  1991. {
  1992. ReorderInfo info(this);
  1993. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  1994. return;
  1995. obs_scene_enum_items(scene,
  1996. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  1997. {
  1998. ReorderInfo *info =
  1999. reinterpret_cast<ReorderInfo*>(p);
  2000. info->window->ReorderSceneItem(item,
  2001. info->idx++);
  2002. return true;
  2003. }, &info);
  2004. SaveProject();
  2005. }
  2006. /* OBS Callbacks */
  2007. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2008. {
  2009. OBSBasic *window = static_cast<OBSBasic*>(data);
  2010. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2011. QMetaObject::invokeMethod(window, "ReorderSources",
  2012. Q_ARG(OBSScene, OBSScene(scene)));
  2013. }
  2014. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2015. {
  2016. OBSBasic *window = static_cast<OBSBasic*>(data);
  2017. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2018. QMetaObject::invokeMethod(window, "AddSceneItem",
  2019. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2020. }
  2021. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  2022. {
  2023. OBSBasic *window = static_cast<OBSBasic*>(data);
  2024. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2025. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  2026. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2027. }
  2028. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2029. {
  2030. OBSBasic *window = static_cast<OBSBasic*>(data);
  2031. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2032. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2033. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2034. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2035. Q_ARG(bool, true));
  2036. }
  2037. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2038. {
  2039. OBSBasic *window = static_cast<OBSBasic*>(data);
  2040. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2041. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2042. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2043. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2044. Q_ARG(bool, false));
  2045. }
  2046. void OBSBasic::SourceLoaded(void *data, obs_source_t *source)
  2047. {
  2048. OBSBasic *window = static_cast<OBSBasic*>(data);
  2049. if (obs_scene_from_source(source) != NULL)
  2050. QMetaObject::invokeMethod(window,
  2051. "AddScene",
  2052. Q_ARG(OBSSource, OBSSource(source)));
  2053. }
  2054. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2055. {
  2056. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2057. if (obs_scene_from_source(source) != NULL)
  2058. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2059. "RemoveScene",
  2060. Q_ARG(OBSSource, OBSSource(source)));
  2061. }
  2062. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2063. {
  2064. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2065. uint32_t flags = obs_source_get_output_flags(source);
  2066. if (flags & OBS_SOURCE_AUDIO)
  2067. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2068. "ActivateAudioSource",
  2069. Q_ARG(OBSSource, OBSSource(source)));
  2070. }
  2071. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2072. {
  2073. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2074. uint32_t flags = obs_source_get_output_flags(source);
  2075. if (flags & OBS_SOURCE_AUDIO)
  2076. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2077. "DeactivateAudioSource",
  2078. Q_ARG(OBSSource, OBSSource(source)));
  2079. }
  2080. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2081. {
  2082. const char *newName = calldata_string(params, "new_name");
  2083. const char *prevName = calldata_string(params, "prev_name");
  2084. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2085. "RenameSources",
  2086. Q_ARG(QString, QT_UTF8(newName)),
  2087. Q_ARG(QString, QT_UTF8(prevName)));
  2088. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2089. }
  2090. void OBSBasic::DrawBackdrop(float cx, float cy)
  2091. {
  2092. if (!box)
  2093. return;
  2094. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2095. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2096. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2097. vec4 colorVal;
  2098. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2099. gs_effect_set_vec4(color, &colorVal);
  2100. gs_technique_begin(tech);
  2101. gs_technique_begin_pass(tech, 0);
  2102. gs_matrix_push();
  2103. gs_matrix_identity();
  2104. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2105. gs_load_vertexbuffer(box);
  2106. gs_draw(GS_TRISTRIP, 0, 0);
  2107. gs_matrix_pop();
  2108. gs_technique_end_pass(tech);
  2109. gs_technique_end(tech);
  2110. gs_load_vertexbuffer(nullptr);
  2111. }
  2112. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2113. {
  2114. OBSBasic *window = static_cast<OBSBasic*>(data);
  2115. obs_video_info ovi;
  2116. obs_get_video_info(&ovi);
  2117. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2118. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2119. gs_viewport_push();
  2120. gs_projection_push();
  2121. /* --------------------------------------- */
  2122. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2123. -100.0f, 100.0f);
  2124. gs_set_viewport(window->previewX, window->previewY,
  2125. window->previewCX, window->previewCY);
  2126. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2127. if (window->IsPreviewProgramMode()) {
  2128. OBSScene scene = window->GetCurrentScene();
  2129. obs_source_t *source = obs_scene_get_source(scene);
  2130. if (source)
  2131. obs_source_video_render(source);
  2132. } else {
  2133. obs_render_main_view();
  2134. }
  2135. gs_load_vertexbuffer(nullptr);
  2136. /* --------------------------------------- */
  2137. QSize previewSize = GetPixelSize(window->ui->preview);
  2138. float right = float(previewSize.width()) - window->previewX;
  2139. float bottom = float(previewSize.height()) - window->previewY;
  2140. gs_ortho(-window->previewX, right,
  2141. -window->previewY, bottom,
  2142. -100.0f, 100.0f);
  2143. gs_reset_viewport();
  2144. window->ui->preview->DrawSceneEditing();
  2145. /* --------------------------------------- */
  2146. gs_projection_pop();
  2147. gs_viewport_pop();
  2148. UNUSED_PARAMETER(cx);
  2149. UNUSED_PARAMETER(cy);
  2150. }
  2151. /* Main class functions */
  2152. obs_service_t *OBSBasic::GetService()
  2153. {
  2154. if (!service) {
  2155. service = obs_service_create("rtmp_common", NULL, NULL,
  2156. nullptr);
  2157. obs_service_release(service);
  2158. }
  2159. return service;
  2160. }
  2161. void OBSBasic::SetService(obs_service_t *newService)
  2162. {
  2163. if (newService)
  2164. service = newService;
  2165. }
  2166. bool OBSBasic::StreamingActive() const
  2167. {
  2168. if (!outputHandler)
  2169. return false;
  2170. return outputHandler->StreamingActive();
  2171. }
  2172. bool OBSBasic::Active() const
  2173. {
  2174. if (!outputHandler)
  2175. return false;
  2176. return outputHandler->Active();
  2177. }
  2178. #ifdef _WIN32
  2179. #define IS_WIN32 1
  2180. #else
  2181. #define IS_WIN32 0
  2182. #endif
  2183. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2184. {
  2185. return obs_reset_video(ovi);
  2186. }
  2187. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2188. {
  2189. const char *scaleTypeStr = config_get_string(basicConfig,
  2190. "Video", "ScaleType");
  2191. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2192. return OBS_SCALE_BILINEAR;
  2193. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2194. return OBS_SCALE_LANCZOS;
  2195. else
  2196. return OBS_SCALE_BICUBIC;
  2197. }
  2198. static inline enum video_format GetVideoFormatFromName(const char *name)
  2199. {
  2200. if (astrcmpi(name, "I420") == 0)
  2201. return VIDEO_FORMAT_I420;
  2202. else if (astrcmpi(name, "NV12") == 0)
  2203. return VIDEO_FORMAT_NV12;
  2204. else if (astrcmpi(name, "I444") == 0)
  2205. return VIDEO_FORMAT_I444;
  2206. #if 0 //currently unsupported
  2207. else if (astrcmpi(name, "YVYU") == 0)
  2208. return VIDEO_FORMAT_YVYU;
  2209. else if (astrcmpi(name, "YUY2") == 0)
  2210. return VIDEO_FORMAT_YUY2;
  2211. else if (astrcmpi(name, "UYVY") == 0)
  2212. return VIDEO_FORMAT_UYVY;
  2213. #endif
  2214. else
  2215. return VIDEO_FORMAT_RGBA;
  2216. }
  2217. int OBSBasic::ResetVideo()
  2218. {
  2219. if (outputHandler && outputHandler->Active())
  2220. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2221. ProfileScope("OBSBasic::ResetVideo");
  2222. struct obs_video_info ovi;
  2223. int ret;
  2224. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2225. const char *colorFormat = config_get_string(basicConfig, "Video",
  2226. "ColorFormat");
  2227. const char *colorSpace = config_get_string(basicConfig, "Video",
  2228. "ColorSpace");
  2229. const char *colorRange = config_get_string(basicConfig, "Video",
  2230. "ColorRange");
  2231. ovi.graphics_module = App()->GetRenderModule();
  2232. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2233. "Video", "BaseCX");
  2234. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2235. "Video", "BaseCY");
  2236. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2237. "Video", "OutputCX");
  2238. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2239. "Video", "OutputCY");
  2240. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2241. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2242. VIDEO_CS_601 : VIDEO_CS_709;
  2243. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2244. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2245. ovi.adapter = 0;
  2246. ovi.gpu_conversion = true;
  2247. ovi.scale_type = GetScaleType(basicConfig);
  2248. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2249. ovi.base_width = 1920;
  2250. ovi.base_height = 1080;
  2251. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2252. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2253. }
  2254. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2255. ovi.output_width = ovi.base_width;
  2256. ovi.output_height = ovi.base_height;
  2257. config_set_uint(basicConfig, "Video", "OutputCX",
  2258. ovi.base_width);
  2259. config_set_uint(basicConfig, "Video", "OutputCY",
  2260. ovi.base_height);
  2261. }
  2262. ret = AttemptToResetVideo(&ovi);
  2263. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2264. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2265. blog(LOG_WARNING, "Tried to reset when "
  2266. "already active");
  2267. return ret;
  2268. }
  2269. /* Try OpenGL if DirectX fails on windows */
  2270. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2271. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2272. "with graphics_module='%s', retrying "
  2273. "with graphics_module='%s'",
  2274. ret, ovi.graphics_module,
  2275. DL_OPENGL);
  2276. ovi.graphics_module = DL_OPENGL;
  2277. ret = AttemptToResetVideo(&ovi);
  2278. }
  2279. } else if (ret == OBS_VIDEO_SUCCESS) {
  2280. ResizePreview(ovi.base_width, ovi.base_height);
  2281. if (program)
  2282. ResizeProgram(ovi.base_width, ovi.base_height);
  2283. }
  2284. if (ret == OBS_VIDEO_SUCCESS)
  2285. OBSBasicStats::InitializeValues();
  2286. return ret;
  2287. }
  2288. bool OBSBasic::ResetAudio()
  2289. {
  2290. ProfileScope("OBSBasic::ResetAudio");
  2291. struct obs_audio_info ai;
  2292. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2293. "SampleRate");
  2294. const char *channelSetupStr = config_get_string(basicConfig,
  2295. "Audio", "ChannelSetup");
  2296. if (strcmp(channelSetupStr, "Mono") == 0)
  2297. ai.speakers = SPEAKERS_MONO;
  2298. else
  2299. ai.speakers = SPEAKERS_STEREO;
  2300. return obs_reset_audio(&ai);
  2301. }
  2302. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2303. const char *deviceDesc, int channel)
  2304. {
  2305. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2306. obs_source_t *source;
  2307. obs_data_t *settings;
  2308. source = obs_get_output_source(channel);
  2309. if (source) {
  2310. if (disable) {
  2311. obs_set_output_source(channel, nullptr);
  2312. } else {
  2313. settings = obs_source_get_settings(source);
  2314. const char *oldId = obs_data_get_string(settings,
  2315. "device_id");
  2316. if (strcmp(oldId, deviceId) != 0) {
  2317. obs_data_set_string(settings, "device_id",
  2318. deviceId);
  2319. obs_source_update(source, settings);
  2320. }
  2321. obs_data_release(settings);
  2322. }
  2323. obs_source_release(source);
  2324. } else if (!disable) {
  2325. settings = obs_data_create();
  2326. obs_data_set_string(settings, "device_id", deviceId);
  2327. source = obs_source_create(sourceId, deviceDesc, settings,
  2328. nullptr);
  2329. obs_data_release(settings);
  2330. obs_set_output_source(channel, source);
  2331. obs_source_release(source);
  2332. }
  2333. }
  2334. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2335. {
  2336. QSize targetSize;
  2337. bool isFixedScaling;
  2338. obs_video_info ovi;
  2339. /* resize preview panel to fix to the top section of the window */
  2340. targetSize = GetPixelSize(ui->preview);
  2341. isFixedScaling = ui->preview->IsFixedScaling();
  2342. obs_get_video_info(&ovi);
  2343. if (isFixedScaling) {
  2344. previewScale = ui->preview->GetScalingAmount();
  2345. GetCenterPosFromFixedScale(int(cx), int(cy),
  2346. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2347. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2348. previewX, previewY, previewScale);
  2349. previewX += ui->preview->GetScrollX();
  2350. previewY += ui->preview->GetScrollY();
  2351. } else {
  2352. GetScaleAndCenterPos(int(cx), int(cy),
  2353. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2354. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2355. previewX, previewY, previewScale);
  2356. }
  2357. previewX += float(PREVIEW_EDGE_SIZE);
  2358. previewY += float(PREVIEW_EDGE_SIZE);
  2359. }
  2360. void OBSBasic::CloseDialogs()
  2361. {
  2362. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2363. if (!childDialogs.isEmpty()) {
  2364. for (int i = 0; i < childDialogs.size(); ++i) {
  2365. childDialogs.at(i)->close();
  2366. }
  2367. }
  2368. for (QPointer<QWidget> &projector : windowProjectors) {
  2369. delete projector;
  2370. projector.clear();
  2371. }
  2372. for (QPointer<QWidget> &projector : projectors) {
  2373. delete projector;
  2374. projector.clear();
  2375. }
  2376. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2377. }
  2378. void OBSBasic::EnumDialogs()
  2379. {
  2380. visDialogs.clear();
  2381. modalDialogs.clear();
  2382. visMsgBoxes.clear();
  2383. /* fill list of Visible dialogs and Modal dialogs */
  2384. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2385. for (QDialog *dialog : dialogs) {
  2386. if (dialog->isVisible())
  2387. visDialogs.append(dialog);
  2388. if (dialog->isModal())
  2389. modalDialogs.append(dialog);
  2390. }
  2391. /* fill list of Visible message boxes */
  2392. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2393. for (QMessageBox *msgbox : msgBoxes) {
  2394. if (msgbox->isVisible())
  2395. visMsgBoxes.append(msgbox);
  2396. }
  2397. }
  2398. void OBSBasic::ClearSceneData()
  2399. {
  2400. disableSaving++;
  2401. CloseDialogs();
  2402. ClearVolumeControls();
  2403. ClearListItems(ui->scenes);
  2404. ClearListItems(ui->sources);
  2405. ClearQuickTransitions();
  2406. ui->transitions->clear();
  2407. obs_set_output_source(0, nullptr);
  2408. obs_set_output_source(1, nullptr);
  2409. obs_set_output_source(2, nullptr);
  2410. obs_set_output_source(3, nullptr);
  2411. obs_set_output_source(4, nullptr);
  2412. obs_set_output_source(5, nullptr);
  2413. lastScene = nullptr;
  2414. swapScene = nullptr;
  2415. programScene = nullptr;
  2416. auto cb = [](void *unused, obs_source_t *source)
  2417. {
  2418. obs_source_remove(source);
  2419. UNUSED_PARAMETER(unused);
  2420. return true;
  2421. };
  2422. obs_enum_sources(cb, nullptr);
  2423. disableSaving--;
  2424. blog(LOG_INFO, "All scene data cleared");
  2425. blog(LOG_INFO, "------------------------------------------------");
  2426. }
  2427. void OBSBasic::closeEvent(QCloseEvent *event)
  2428. {
  2429. if (isVisible())
  2430. config_set_string(App()->GlobalConfig(),
  2431. "BasicWindow", "geometry",
  2432. saveGeometry().toBase64().constData());
  2433. config_set_string(App()->GlobalConfig(),
  2434. "BasicWindow", "DockState",
  2435. saveState().toBase64().constData());
  2436. if (outputHandler && outputHandler->Active()) {
  2437. SetShowing(true);
  2438. QMessageBox::StandardButton button = OBSMessageBox::question(
  2439. this, QTStr("ConfirmExit.Title"),
  2440. QTStr("ConfirmExit.Text"));
  2441. if (button == QMessageBox::No) {
  2442. event->ignore();
  2443. return;
  2444. }
  2445. }
  2446. QWidget::closeEvent(event);
  2447. if (!event->isAccepted())
  2448. return;
  2449. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2450. if (updateCheckThread)
  2451. updateCheckThread->wait();
  2452. if (logUploadThread)
  2453. logUploadThread->wait();
  2454. signalHandlers.clear();
  2455. SaveProjectNow();
  2456. if (api)
  2457. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2458. disableSaving++;
  2459. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2460. * sources, etc) so that all references are released before shutdown */
  2461. ClearSceneData();
  2462. App()->quit();
  2463. }
  2464. void OBSBasic::changeEvent(QEvent *event)
  2465. {
  2466. if (event->type() == QEvent::WindowStateChange &&
  2467. isMinimized() &&
  2468. trayIcon &&
  2469. trayIcon->isVisible() &&
  2470. sysTrayMinimizeToTray()) {
  2471. ToggleShowHide();
  2472. }
  2473. }
  2474. void OBSBasic::on_actionShow_Recordings_triggered()
  2475. {
  2476. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2477. const char *path = strcmp(mode, "Advanced") ?
  2478. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2479. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2480. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2481. }
  2482. void OBSBasic::on_actionRemux_triggered()
  2483. {
  2484. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2485. const char *path = strcmp(mode, "Advanced") ?
  2486. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2487. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2488. OBSRemux remux(path, this);
  2489. remux.exec();
  2490. }
  2491. void OBSBasic::on_action_Settings_triggered()
  2492. {
  2493. OBSBasicSettings settings(this);
  2494. settings.exec();
  2495. SystemTray(false);
  2496. }
  2497. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2498. {
  2499. if (advAudioWindow != nullptr) {
  2500. advAudioWindow->raise();
  2501. return;
  2502. }
  2503. advAudioWindow = new OBSBasicAdvAudio(this);
  2504. advAudioWindow->show();
  2505. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2506. connect(advAudioWindow, SIGNAL(destroyed()),
  2507. this, SLOT(on_advAudioProps_destroyed()));
  2508. }
  2509. void OBSBasic::on_advAudioProps_clicked()
  2510. {
  2511. on_actionAdvAudioProperties_triggered();
  2512. }
  2513. void OBSBasic::on_advAudioProps_destroyed()
  2514. {
  2515. advAudioWindow = nullptr;
  2516. }
  2517. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2518. QListWidgetItem *prev)
  2519. {
  2520. obs_source_t *source = NULL;
  2521. if (sceneChanging)
  2522. return;
  2523. if (current) {
  2524. obs_scene_t *scene;
  2525. scene = GetOBSRef<OBSScene>(current);
  2526. source = obs_scene_get_source(scene);
  2527. }
  2528. SetCurrentScene(source);
  2529. UNUSED_PARAMETER(prev);
  2530. }
  2531. void OBSBasic::EditSceneName()
  2532. {
  2533. QListWidgetItem *item = ui->scenes->currentItem();
  2534. Qt::ItemFlags flags = item->flags();
  2535. item->setFlags(flags | Qt::ItemIsEditable);
  2536. ui->scenes->editItem(item);
  2537. item->setFlags(flags);
  2538. }
  2539. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2540. const char *slot)
  2541. {
  2542. QAction *action;
  2543. QList<QScreen*> screens = QGuiApplication::screens();
  2544. for (int i = 0; i < screens.size(); i++) {
  2545. QRect screenGeometry = screens[i]->geometry();
  2546. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2547. arg(QTStr("Display"),
  2548. QString::number(i),
  2549. QString::number((int)screenGeometry.width()),
  2550. QString::number((int)screenGeometry.height()),
  2551. QString::number((int)screenGeometry.x()),
  2552. QString::number((int)screenGeometry.y()));
  2553. action = parent->addAction(str, target, slot);
  2554. action->setProperty("monitor", i);
  2555. }
  2556. }
  2557. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2558. {
  2559. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2560. QPointer<QMenu> sceneProjectorMenu;
  2561. QMenu popup(this);
  2562. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2563. popup.addAction(QTStr("Add"),
  2564. this, SLOT(on_actionAddScene_triggered()));
  2565. if (item) {
  2566. popup.addSeparator();
  2567. popup.addAction(QTStr("Duplicate"),
  2568. this, SLOT(DuplicateSelectedScene()));
  2569. popup.addAction(QTStr("Rename"),
  2570. this, SLOT(EditSceneName()));
  2571. popup.addAction(QTStr("Remove"),
  2572. this, SLOT(RemoveSelectedScene()),
  2573. DeleteKeys.front());
  2574. popup.addSeparator();
  2575. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2576. this, SLOT(on_actionSceneUp_triggered()));
  2577. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2578. this, SLOT(on_actionSceneDown_triggered()));
  2579. order.addSeparator();
  2580. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2581. this, SLOT(MoveSceneToTop()));
  2582. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2583. this, SLOT(MoveSceneToBottom()));
  2584. popup.addMenu(&order);
  2585. popup.addSeparator();
  2586. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2587. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2588. SLOT(OpenSceneProjector()));
  2589. popup.addMenu(sceneProjectorMenu);
  2590. QAction *sceneWindow = popup.addAction(
  2591. QTStr("SceneWindow"),
  2592. this, SLOT(OpenSceneWindow()));
  2593. popup.addAction(sceneWindow);
  2594. popup.addSeparator();
  2595. popup.addAction(QTStr("Filters"), this,
  2596. SLOT(OpenSceneFilters()));
  2597. }
  2598. popup.exec(QCursor::pos());
  2599. }
  2600. void OBSBasic::on_actionAddScene_triggered()
  2601. {
  2602. string name;
  2603. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2604. int i = 2;
  2605. QString placeHolderText = format.arg(i);
  2606. obs_source_t *source = nullptr;
  2607. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2608. obs_source_release(source);
  2609. placeHolderText = format.arg(++i);
  2610. }
  2611. bool accepted = NameDialog::AskForName(this,
  2612. QTStr("Basic.Main.AddSceneDlg.Title"),
  2613. QTStr("Basic.Main.AddSceneDlg.Text"),
  2614. name,
  2615. placeHolderText);
  2616. if (accepted) {
  2617. if (name.empty()) {
  2618. OBSMessageBox::information(this,
  2619. QTStr("NoNameEntered.Title"),
  2620. QTStr("NoNameEntered.Text"));
  2621. on_actionAddScene_triggered();
  2622. return;
  2623. }
  2624. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2625. if (source) {
  2626. OBSMessageBox::information(this,
  2627. QTStr("NameExists.Title"),
  2628. QTStr("NameExists.Text"));
  2629. obs_source_release(source);
  2630. on_actionAddScene_triggered();
  2631. return;
  2632. }
  2633. obs_scene_t *scene = obs_scene_create(name.c_str());
  2634. source = obs_scene_get_source(scene);
  2635. AddScene(source);
  2636. SetCurrentScene(source);
  2637. obs_scene_release(scene);
  2638. }
  2639. }
  2640. void OBSBasic::on_actionRemoveScene_triggered()
  2641. {
  2642. OBSScene scene = GetCurrentScene();
  2643. obs_source_t *source = obs_scene_get_source(scene);
  2644. if (source && QueryRemoveSource(source))
  2645. obs_source_remove(source);
  2646. }
  2647. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2648. {
  2649. int idx = ui->scenes->currentRow();
  2650. if (idx == -1 || idx == invalidIdx)
  2651. return;
  2652. sceneChanging = true;
  2653. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2654. if (!relative)
  2655. idx = 0;
  2656. ui->scenes->insertItem(idx + offset, item);
  2657. ui->scenes->setCurrentRow(idx + offset);
  2658. item->setSelected(true);
  2659. sceneChanging = false;
  2660. }
  2661. void OBSBasic::on_actionSceneUp_triggered()
  2662. {
  2663. ChangeSceneIndex(true, -1, 0);
  2664. }
  2665. void OBSBasic::on_actionSceneDown_triggered()
  2666. {
  2667. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2668. }
  2669. void OBSBasic::MoveSceneToTop()
  2670. {
  2671. ChangeSceneIndex(false, 0, 0);
  2672. }
  2673. void OBSBasic::MoveSceneToBottom()
  2674. {
  2675. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2676. ui->scenes->count() - 1);
  2677. }
  2678. void OBSBasic::on_sources_itemSelectionChanged()
  2679. {
  2680. SignalBlocker sourcesSignalBlocker(ui->sources);
  2681. auto updateItemSelection = [&]()
  2682. {
  2683. ignoreSelectionUpdate = true;
  2684. for (int i = 0; i < ui->sources->count(); i++)
  2685. {
  2686. QListWidgetItem *wItem = ui->sources->item(i);
  2687. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2688. obs_sceneitem_select(item, wItem->isSelected());
  2689. }
  2690. ignoreSelectionUpdate = false;
  2691. };
  2692. using updateItemSelection_t = decltype(updateItemSelection);
  2693. obs_scene_atomic_update(GetCurrentScene(),
  2694. [](void *data, obs_scene_t *)
  2695. {
  2696. (*static_cast<updateItemSelection_t*>(data))();
  2697. }, static_cast<void*>(&updateItemSelection));
  2698. }
  2699. void OBSBasic::EditSceneItemName()
  2700. {
  2701. QListWidgetItem *item = GetTopSelectedSourceItem();
  2702. Qt::ItemFlags flags = item->flags();
  2703. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2704. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2705. const char *name = obs_source_get_name(source);
  2706. item->setText(QT_UTF8(name));
  2707. item->setFlags(flags | Qt::ItemIsEditable);
  2708. ui->sources->removeItemWidget(item);
  2709. ui->sources->editItem(item);
  2710. item->setFlags(flags);
  2711. }
  2712. void OBSBasic::SetDeinterlacingMode()
  2713. {
  2714. QAction *action = reinterpret_cast<QAction*>(sender());
  2715. obs_deinterlace_mode mode =
  2716. (obs_deinterlace_mode)action->property("mode").toInt();
  2717. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2718. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2719. obs_source_set_deinterlace_mode(source, mode);
  2720. }
  2721. void OBSBasic::SetDeinterlacingOrder()
  2722. {
  2723. QAction *action = reinterpret_cast<QAction*>(sender());
  2724. obs_deinterlace_field_order order =
  2725. (obs_deinterlace_field_order)action->property("order").toInt();
  2726. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2727. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2728. obs_source_set_deinterlace_field_order(source, order);
  2729. }
  2730. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2731. {
  2732. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2733. obs_deinterlace_mode deinterlaceMode =
  2734. obs_source_get_deinterlace_mode(source);
  2735. obs_deinterlace_field_order deinterlaceOrder =
  2736. obs_source_get_deinterlace_field_order(source);
  2737. QAction *action;
  2738. #define ADD_MODE(name, mode) \
  2739. action = menu->addAction(QTStr("" name), this, \
  2740. SLOT(SetDeinterlacingMode())); \
  2741. action->setProperty("mode", (int)mode); \
  2742. action->setCheckable(true); \
  2743. action->setChecked(deinterlaceMode == mode);
  2744. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2745. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2746. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2747. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2748. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2749. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2750. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2751. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2752. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2753. #undef ADD_MODE
  2754. menu->addSeparator();
  2755. #define ADD_ORDER(name, order) \
  2756. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2757. SLOT(SetDeinterlacingOrder())); \
  2758. action->setProperty("order", (int)order); \
  2759. action->setCheckable(true); \
  2760. action->setChecked(deinterlaceOrder == order);
  2761. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2762. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2763. #undef ADD_ORDER
  2764. return menu;
  2765. }
  2766. void OBSBasic::SetScaleFilter()
  2767. {
  2768. QAction *action = reinterpret_cast<QAction*>(sender());
  2769. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2770. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2771. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2772. }
  2773. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2774. {
  2775. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2776. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2777. QAction *action;
  2778. #define ADD_MODE(name, mode) \
  2779. action = menu->addAction(QTStr("" name), this, \
  2780. SLOT(SetScaleFilter())); \
  2781. action->setProperty("mode", (int)mode); \
  2782. action->setCheckable(true); \
  2783. action->setChecked(scaleFilter == mode);
  2784. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2785. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2786. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2787. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2788. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2789. #undef ADD_MODE
  2790. return menu;
  2791. }
  2792. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2793. {
  2794. QMenu popup(this);
  2795. QPointer<QMenu> previewProjector;
  2796. QPointer<QMenu> sourceProjector;
  2797. if (preview) {
  2798. QAction *action = popup.addAction(
  2799. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2800. this, SLOT(TogglePreview()));
  2801. action->setCheckable(true);
  2802. action->setChecked(
  2803. obs_display_enabled(ui->preview->GetDisplay()));
  2804. if (IsPreviewProgramMode())
  2805. action->setEnabled(false);
  2806. popup.addAction(ui->actionLockPreview);
  2807. popup.addMenu(ui->scalingMenu);
  2808. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2809. AddProjectorMenuMonitors(previewProjector, this,
  2810. SLOT(OpenPreviewProjector()));
  2811. popup.addMenu(previewProjector);
  2812. QAction *previewWindow = popup.addAction(
  2813. QTStr("PreviewWindow"),
  2814. this, SLOT(OpenPreviewWindow()));
  2815. popup.addAction(previewWindow);
  2816. popup.addSeparator();
  2817. }
  2818. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2819. if (addSourceMenu)
  2820. popup.addMenu(addSourceMenu);
  2821. ui->actionCopyFilters->setEnabled(false);
  2822. popup.addSeparator();
  2823. popup.addAction(ui->actionCopySource);
  2824. popup.addAction(ui->actionPasteRef);
  2825. popup.addAction(ui->actionPasteDup);
  2826. popup.addSeparator();
  2827. popup.addSeparator();
  2828. popup.addAction(ui->actionCopyFilters);
  2829. popup.addAction(ui->actionPasteFilters);
  2830. popup.addSeparator();
  2831. if (item) {
  2832. if (addSourceMenu)
  2833. popup.addSeparator();
  2834. OBSSceneItem sceneItem = GetSceneItem(item);
  2835. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2836. uint32_t flags = obs_source_get_output_flags(source);
  2837. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2838. OBS_SOURCE_ASYNC_VIDEO;
  2839. QAction *action;
  2840. popup.addAction(QTStr("Rename"), this,
  2841. SLOT(EditSceneItemName()));
  2842. popup.addAction(QTStr("Remove"), this,
  2843. SLOT(on_actionRemoveSource_triggered()),
  2844. DeleteKeys.front());
  2845. popup.addSeparator();
  2846. popup.addMenu(ui->orderMenu);
  2847. popup.addMenu(ui->transformMenu);
  2848. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2849. AddProjectorMenuMonitors(sourceProjector, this,
  2850. SLOT(OpenSourceProjector()));
  2851. QAction *sourceWindow = popup.addAction(
  2852. QTStr("SourceWindow"),
  2853. this, SLOT(OpenSourceWindow()));
  2854. popup.addAction(sourceWindow);
  2855. popup.addSeparator();
  2856. if (isAsyncVideo) {
  2857. popup.addMenu(AddDeinterlacingMenu(source));
  2858. popup.addSeparator();
  2859. }
  2860. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  2861. popup.addSeparator();
  2862. popup.addMenu(sourceProjector);
  2863. popup.addAction(sourceWindow);
  2864. popup.addSeparator();
  2865. action = popup.addAction(QTStr("Interact"), this,
  2866. SLOT(on_actionInteract_triggered()));
  2867. action->setEnabled(obs_source_get_output_flags(source) &
  2868. OBS_SOURCE_INTERACTION);
  2869. popup.addAction(QTStr("Filters"), this,
  2870. SLOT(OpenFilters()));
  2871. popup.addAction(QTStr("Properties"), this,
  2872. SLOT(on_actionSourceProperties_triggered()));
  2873. ui->actionCopyFilters->setEnabled(true);
  2874. }
  2875. popup.exec(QCursor::pos());
  2876. }
  2877. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  2878. {
  2879. if (ui->scenes->count())
  2880. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  2881. }
  2882. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  2883. {
  2884. if (!witem)
  2885. return;
  2886. OBSSceneItem item = GetSceneItem(witem);
  2887. OBSSource source = obs_sceneitem_get_source(item);
  2888. if (source)
  2889. CreatePropertiesWindow(source);
  2890. }
  2891. void OBSBasic::AddSource(const char *id)
  2892. {
  2893. if (id && *id) {
  2894. OBSBasicSourceSelect sourceSelect(this, id);
  2895. sourceSelect.exec();
  2896. if (sourceSelect.newSource)
  2897. CreatePropertiesWindow(sourceSelect.newSource);
  2898. }
  2899. }
  2900. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  2901. {
  2902. const char *type;
  2903. bool foundValues = false;
  2904. bool foundDeprecated = false;
  2905. size_t idx = 0;
  2906. QMenu *popup = new QMenu(QTStr("Add"), this);
  2907. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  2908. auto getActionAfter = [] (QMenu *menu, const QString &name)
  2909. {
  2910. QList<QAction*> actions = menu->actions();
  2911. for (QAction *menuAction : actions) {
  2912. if (menuAction->text().compare(name) >= 0)
  2913. return menuAction;
  2914. }
  2915. return (QAction*)nullptr;
  2916. };
  2917. auto addSource = [this, getActionAfter] (QMenu *popup,
  2918. const char *type, const char *name)
  2919. {
  2920. QString qname = QT_UTF8(name);
  2921. QAction *popupItem = new QAction(qname, this);
  2922. popupItem->setData(QT_UTF8(type));
  2923. connect(popupItem, SIGNAL(triggered(bool)),
  2924. this, SLOT(AddSourceFromAction()));
  2925. QAction *after = getActionAfter(popup, qname);
  2926. popup->insertAction(after, popupItem);
  2927. };
  2928. while (obs_enum_input_types(idx++, &type)) {
  2929. const char *name = obs_source_get_display_name(type);
  2930. uint32_t caps = obs_get_source_output_flags(type);
  2931. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  2932. addSource(popup, type, name);
  2933. } else {
  2934. addSource(deprecated, type, name);
  2935. foundDeprecated = true;
  2936. }
  2937. foundValues = true;
  2938. }
  2939. addSource(popup, "scene", Str("Basic.Scene"));
  2940. if (!foundDeprecated) {
  2941. delete deprecated;
  2942. deprecated = nullptr;
  2943. }
  2944. if (!foundValues) {
  2945. delete popup;
  2946. popup = nullptr;
  2947. } else if (foundDeprecated) {
  2948. popup->addMenu(deprecated);
  2949. }
  2950. return popup;
  2951. }
  2952. void OBSBasic::AddSourceFromAction()
  2953. {
  2954. QAction *action = qobject_cast<QAction*>(sender());
  2955. if (!action)
  2956. return;
  2957. AddSource(QT_TO_UTF8(action->data().toString()));
  2958. }
  2959. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  2960. {
  2961. if (!GetCurrentScene()) {
  2962. // Tell the user he needs a scene first (help beginners).
  2963. OBSMessageBox::information(this,
  2964. QTStr("Basic.Main.AddSourceHelp.Title"),
  2965. QTStr("Basic.Main.AddSourceHelp.Text"));
  2966. return;
  2967. }
  2968. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  2969. if (popup)
  2970. popup->exec(pos);
  2971. }
  2972. void OBSBasic::on_actionAddSource_triggered()
  2973. {
  2974. AddSourcePopupMenu(QCursor::pos());
  2975. }
  2976. void OBSBasic::on_actionRemoveSource_triggered()
  2977. {
  2978. vector<OBSSceneItem> items;
  2979. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  2980. {
  2981. vector<OBSSceneItem> &items =
  2982. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  2983. if (obs_sceneitem_selected(item))
  2984. items.emplace_back(item);
  2985. return true;
  2986. };
  2987. obs_scene_enum_items(GetCurrentScene(), func, &items);
  2988. if (!items.size())
  2989. return;
  2990. auto removeMultiple = [this] (size_t count)
  2991. {
  2992. QString text = QTStr("ConfirmRemove.TextMultiple")
  2993. .arg(QString::number(count));
  2994. QMessageBox remove_items(this);
  2995. remove_items.setText(text);
  2996. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  2997. QMessageBox::YesRole);
  2998. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  2999. remove_items.setIcon(QMessageBox::Question);
  3000. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3001. remove_items.exec();
  3002. return Yes == remove_items.clickedButton();
  3003. };
  3004. if (items.size() == 1) {
  3005. OBSSceneItem &item = items[0];
  3006. obs_source_t *source = obs_sceneitem_get_source(item);
  3007. if (source && QueryRemoveSource(source))
  3008. obs_sceneitem_remove(item);
  3009. } else {
  3010. if (removeMultiple(items.size())) {
  3011. for (auto &item : items)
  3012. obs_sceneitem_remove(item);
  3013. }
  3014. }
  3015. }
  3016. void OBSBasic::on_actionInteract_triggered()
  3017. {
  3018. OBSSceneItem item = GetCurrentSceneItem();
  3019. OBSSource source = obs_sceneitem_get_source(item);
  3020. if (source)
  3021. CreateInteractionWindow(source);
  3022. }
  3023. void OBSBasic::on_actionSourceProperties_triggered()
  3024. {
  3025. OBSSceneItem item = GetCurrentSceneItem();
  3026. OBSSource source = obs_sceneitem_get_source(item);
  3027. if (source)
  3028. CreatePropertiesWindow(source);
  3029. }
  3030. void OBSBasic::on_actionSourceUp_triggered()
  3031. {
  3032. OBSSceneItem item = GetCurrentSceneItem();
  3033. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3034. }
  3035. void OBSBasic::on_actionSourceDown_triggered()
  3036. {
  3037. OBSSceneItem item = GetCurrentSceneItem();
  3038. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3039. }
  3040. void OBSBasic::on_actionMoveUp_triggered()
  3041. {
  3042. OBSSceneItem item = GetCurrentSceneItem();
  3043. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3044. }
  3045. void OBSBasic::on_actionMoveDown_triggered()
  3046. {
  3047. OBSSceneItem item = GetCurrentSceneItem();
  3048. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3049. }
  3050. void OBSBasic::on_actionMoveToTop_triggered()
  3051. {
  3052. OBSSceneItem item = GetCurrentSceneItem();
  3053. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3054. }
  3055. void OBSBasic::on_actionMoveToBottom_triggered()
  3056. {
  3057. OBSSceneItem item = GetCurrentSceneItem();
  3058. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3059. }
  3060. static BPtr<char> ReadLogFile(const char *log)
  3061. {
  3062. char logDir[512];
  3063. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3064. return nullptr;
  3065. string path = (char*)logDir;
  3066. path += "/";
  3067. path += log;
  3068. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3069. if (!file)
  3070. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3071. return file;
  3072. }
  3073. void OBSBasic::UploadLog(const char *file)
  3074. {
  3075. BPtr<char> fileString{ReadLogFile(file)};
  3076. if (!fileString)
  3077. return;
  3078. if (!*fileString)
  3079. return;
  3080. ui->menuLogFiles->setEnabled(false);
  3081. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  3082. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  3083. data_t content{obs_data_create(), data_deleter};
  3084. data_t files{obs_data_create(), data_deleter};
  3085. data_t request{obs_data_create(), data_deleter};
  3086. obs_data_set_string(content.get(), "content", fileString);
  3087. obs_data_set_obj(files.get(), file, content.get());
  3088. stringstream ss;
  3089. ss << "OBS " << App()->GetVersionString()
  3090. << " log file uploaded at " << CurrentDateTimeString();
  3091. obs_data_set_string(request.get(), "description", ss.str().c_str());
  3092. obs_data_set_bool(request.get(), "public", false);
  3093. obs_data_set_obj(request.get(), "files", files.get());
  3094. const char *json = obs_data_get_json(request.get());
  3095. if (!json) {
  3096. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  3097. return;
  3098. }
  3099. QBuffer *postData = new QBuffer();
  3100. postData->setData(json, (int) strlen(json));
  3101. if (logUploadThread) {
  3102. logUploadThread->wait();
  3103. delete logUploadThread;
  3104. }
  3105. RemoteTextThread *thread = new RemoteTextThread(
  3106. "https://api.github.com/gists",
  3107. "application/json", json);
  3108. logUploadThread = thread;
  3109. connect(thread, &RemoteTextThread::Result,
  3110. this, &OBSBasic::logUploadFinished);
  3111. logUploadThread->start();
  3112. }
  3113. void OBSBasic::on_actionShowLogs_triggered()
  3114. {
  3115. char logDir[512];
  3116. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3117. return;
  3118. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3119. QDesktopServices::openUrl(url);
  3120. }
  3121. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3122. {
  3123. UploadLog(App()->GetCurrentLog());
  3124. }
  3125. void OBSBasic::on_actionUploadLastLog_triggered()
  3126. {
  3127. UploadLog(App()->GetLastLog());
  3128. }
  3129. void OBSBasic::on_actionViewCurrentLog_triggered()
  3130. {
  3131. char logDir[512];
  3132. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3133. return;
  3134. const char* log = App()->GetCurrentLog();
  3135. string path = (char*)logDir;
  3136. path += "/";
  3137. path += log;
  3138. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3139. QDesktopServices::openUrl(url);
  3140. }
  3141. void OBSBasic::on_actionCheckForUpdates_triggered()
  3142. {
  3143. CheckForUpdates(true);
  3144. }
  3145. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3146. {
  3147. ui->menuLogFiles->setEnabled(true);
  3148. if (text.isEmpty()) {
  3149. OBSMessageBox::information(this,
  3150. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3151. error);
  3152. return;
  3153. }
  3154. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3155. QString logURL = obs_data_get_string(returnData, "html_url");
  3156. obs_data_release(returnData);
  3157. OBSLogReply logDialog(this, logURL);
  3158. logDialog.exec();
  3159. }
  3160. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3161. obs_source_t *source, const string &name)
  3162. {
  3163. const char *prevName = obs_source_get_name(source);
  3164. if (name == prevName)
  3165. return;
  3166. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3167. QListWidgetItem *listItem = listWidget->currentItem();
  3168. if (foundSource || name.empty()) {
  3169. listItem->setText(QT_UTF8(prevName));
  3170. if (foundSource) {
  3171. OBSMessageBox::information(parent,
  3172. QTStr("NameExists.Title"),
  3173. QTStr("NameExists.Text"));
  3174. } else if (name.empty()) {
  3175. OBSMessageBox::information(parent,
  3176. QTStr("NoNameEntered.Title"),
  3177. QTStr("NoNameEntered.Text"));
  3178. }
  3179. obs_source_release(foundSource);
  3180. } else {
  3181. listItem->setText(QT_UTF8(name.c_str()));
  3182. obs_source_set_name(source, name.c_str());
  3183. }
  3184. }
  3185. void OBSBasic::SceneNameEdited(QWidget *editor,
  3186. QAbstractItemDelegate::EndEditHint endHint)
  3187. {
  3188. OBSScene scene = GetCurrentScene();
  3189. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3190. string text = QT_TO_UTF8(edit->text().trimmed());
  3191. if (!scene)
  3192. return;
  3193. obs_source_t *source = obs_scene_get_source(scene);
  3194. RenameListItem(this, ui->scenes, source, text);
  3195. if (api)
  3196. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3197. UNUSED_PARAMETER(endHint);
  3198. }
  3199. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  3200. QAbstractItemDelegate::EndEditHint endHint)
  3201. {
  3202. OBSSceneItem item = GetCurrentSceneItem();
  3203. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3204. string text = QT_TO_UTF8(edit->text().trimmed());
  3205. if (!item)
  3206. return;
  3207. obs_source_t *source = obs_sceneitem_get_source(item);
  3208. RenameListItem(this, ui->sources, source, text);
  3209. QListWidgetItem *listItem = ui->sources->currentItem();
  3210. listItem->setText(QString());
  3211. SetupVisibilityItem(ui->sources, listItem, item);
  3212. UNUSED_PARAMETER(endHint);
  3213. }
  3214. void OBSBasic::OpenFilters()
  3215. {
  3216. OBSSceneItem item = GetCurrentSceneItem();
  3217. OBSSource source = obs_sceneitem_get_source(item);
  3218. CreateFiltersWindow(source);
  3219. }
  3220. void OBSBasic::OpenSceneFilters()
  3221. {
  3222. OBSScene scene = GetCurrentScene();
  3223. OBSSource source = obs_scene_get_source(scene);
  3224. CreateFiltersWindow(source);
  3225. }
  3226. #define RECORDING_START \
  3227. "==== Recording Start ==============================================="
  3228. #define RECORDING_STOP \
  3229. "==== Recording Stop ================================================"
  3230. #define REPLAY_BUFFER_START \
  3231. "==== Replay Buffer Start ==========================================="
  3232. #define REPLAY_BUFFER_STOP \
  3233. "==== Replay Buffer Stop ============================================"
  3234. #define STREAMING_START \
  3235. "==== Streaming Start ==============================================="
  3236. #define STREAMING_STOP \
  3237. "==== Streaming Stop ================================================"
  3238. void OBSBasic::StartStreaming()
  3239. {
  3240. if (outputHandler->StreamingActive())
  3241. return;
  3242. if (disableOutputsRef)
  3243. return;
  3244. if (api)
  3245. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3246. SaveProject();
  3247. ui->streamButton->setEnabled(false);
  3248. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3249. if (sysTrayStream) {
  3250. sysTrayStream->setEnabled(false);
  3251. sysTrayStream->setText(ui->streamButton->text());
  3252. }
  3253. if (!outputHandler->StartStreaming(service)) {
  3254. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3255. ui->streamButton->setEnabled(true);
  3256. if (sysTrayStream) {
  3257. sysTrayStream->setText(ui->streamButton->text());
  3258. sysTrayStream->setEnabled(true);
  3259. }
  3260. QMessageBox::critical(this,
  3261. QTStr("Output.StartStreamFailed"),
  3262. QTStr("Output.StartFailedGeneric"));
  3263. return;
  3264. }
  3265. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3266. "BasicWindow", "RecordWhenStreaming");
  3267. if (recordWhenStreaming)
  3268. StartRecording();
  3269. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3270. "BasicWindow", "ReplayBufferWhileStreaming");
  3271. if (replayBufferWhileStreaming)
  3272. StartReplayBuffer();
  3273. }
  3274. #ifdef _WIN32
  3275. static inline void UpdateProcessPriority()
  3276. {
  3277. const char *priority = config_get_string(App()->GlobalConfig(),
  3278. "General", "ProcessPriority");
  3279. if (priority && strcmp(priority, "Normal") != 0)
  3280. SetProcessPriority(priority);
  3281. }
  3282. static inline void ClearProcessPriority()
  3283. {
  3284. const char *priority = config_get_string(App()->GlobalConfig(),
  3285. "General", "ProcessPriority");
  3286. if (priority && strcmp(priority, "Normal") != 0)
  3287. SetProcessPriority("Normal");
  3288. }
  3289. #else
  3290. #define UpdateProcessPriority() do {} while(false)
  3291. #define ClearProcessPriority() do {} while(false)
  3292. #endif
  3293. inline void OBSBasic::OnActivate()
  3294. {
  3295. if (ui->profileMenu->isEnabled()) {
  3296. ui->profileMenu->setEnabled(false);
  3297. ui->autoConfigure->setEnabled(false);
  3298. App()->IncrementSleepInhibition();
  3299. UpdateProcessPriority();
  3300. if (trayIcon)
  3301. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3302. }
  3303. }
  3304. inline void OBSBasic::OnDeactivate()
  3305. {
  3306. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3307. ui->profileMenu->setEnabled(true);
  3308. ui->autoConfigure->setEnabled(true);
  3309. App()->DecrementSleepInhibition();
  3310. ClearProcessPriority();
  3311. if (trayIcon)
  3312. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3313. }
  3314. }
  3315. void OBSBasic::StopStreaming()
  3316. {
  3317. SaveProject();
  3318. if (outputHandler->StreamingActive())
  3319. outputHandler->StopStreaming(streamingStopping);
  3320. OnDeactivate();
  3321. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3322. "BasicWindow", "RecordWhenStreaming");
  3323. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3324. "BasicWindow", "KeepRecordingWhenStreamStops");
  3325. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3326. StopRecording();
  3327. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3328. "BasicWindow", "ReplayBufferWhileStreaming");
  3329. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3330. "BasicWindow", "KeepReplayBufferStreamStops");
  3331. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3332. StopReplayBuffer();
  3333. }
  3334. void OBSBasic::ForceStopStreaming()
  3335. {
  3336. SaveProject();
  3337. if (outputHandler->StreamingActive())
  3338. outputHandler->StopStreaming(true);
  3339. OnDeactivate();
  3340. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3341. "BasicWindow", "RecordWhenStreaming");
  3342. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3343. "BasicWindow", "KeepRecordingWhenStreamStops");
  3344. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3345. StopRecording();
  3346. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3347. "BasicWindow", "ReplayBufferWhileStreaming");
  3348. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3349. "BasicWindow", "KeepReplayBufferStreamStops");
  3350. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3351. StopReplayBuffer();
  3352. }
  3353. void OBSBasic::StreamDelayStarting(int sec)
  3354. {
  3355. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3356. ui->streamButton->setEnabled(true);
  3357. if (sysTrayStream) {
  3358. sysTrayStream->setText(ui->streamButton->text());
  3359. sysTrayStream->setEnabled(true);
  3360. }
  3361. if (!startStreamMenu.isNull())
  3362. startStreamMenu->deleteLater();
  3363. startStreamMenu = new QMenu();
  3364. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3365. this, SLOT(StopStreaming()));
  3366. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3367. this, SLOT(ForceStopStreaming()));
  3368. ui->streamButton->setMenu(startStreamMenu);
  3369. ui->statusbar->StreamDelayStarting(sec);
  3370. OnActivate();
  3371. }
  3372. void OBSBasic::StreamDelayStopping(int sec)
  3373. {
  3374. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3375. ui->streamButton->setEnabled(true);
  3376. if (sysTrayStream) {
  3377. sysTrayStream->setText(ui->streamButton->text());
  3378. sysTrayStream->setEnabled(true);
  3379. }
  3380. if (!startStreamMenu.isNull())
  3381. startStreamMenu->deleteLater();
  3382. startStreamMenu = new QMenu();
  3383. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3384. this, SLOT(StartStreaming()));
  3385. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3386. this, SLOT(ForceStopStreaming()));
  3387. ui->streamButton->setMenu(startStreamMenu);
  3388. ui->statusbar->StreamDelayStopping(sec);
  3389. }
  3390. void OBSBasic::StreamingStart()
  3391. {
  3392. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3393. ui->streamButton->setEnabled(true);
  3394. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3395. if (sysTrayStream) {
  3396. sysTrayStream->setText(ui->streamButton->text());
  3397. sysTrayStream->setEnabled(true);
  3398. }
  3399. if (api)
  3400. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3401. OnActivate();
  3402. blog(LOG_INFO, STREAMING_START);
  3403. }
  3404. void OBSBasic::StreamStopping()
  3405. {
  3406. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3407. if (sysTrayStream)
  3408. sysTrayStream->setText(ui->streamButton->text());
  3409. streamingStopping = true;
  3410. if (api)
  3411. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3412. }
  3413. void OBSBasic::StreamingStop(int code, QString last_error)
  3414. {
  3415. const char *errorDescription;
  3416. DStr errorMessage;
  3417. bool use_last_error = false;
  3418. switch (code) {
  3419. case OBS_OUTPUT_BAD_PATH:
  3420. errorDescription = Str("Output.ConnectFail.BadPath");
  3421. break;
  3422. case OBS_OUTPUT_CONNECT_FAILED:
  3423. use_last_error = true;
  3424. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3425. break;
  3426. case OBS_OUTPUT_INVALID_STREAM:
  3427. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3428. break;
  3429. default:
  3430. case OBS_OUTPUT_ERROR:
  3431. use_last_error = true;
  3432. errorDescription = Str("Output.ConnectFail.Error");
  3433. break;
  3434. case OBS_OUTPUT_DISCONNECTED:
  3435. /* doesn't happen if output is set to reconnect. note that
  3436. * reconnects are handled in the output, not in the UI */
  3437. use_last_error = true;
  3438. errorDescription = Str("Output.ConnectFail.Disconnected");
  3439. }
  3440. if (use_last_error && !last_error.isEmpty())
  3441. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3442. QT_TO_UTF8(last_error));
  3443. else
  3444. dstr_copy(errorMessage, errorDescription);
  3445. ui->statusbar->StreamStopped();
  3446. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3447. ui->streamButton->setEnabled(true);
  3448. if (sysTrayStream) {
  3449. sysTrayStream->setText(ui->streamButton->text());
  3450. sysTrayStream->setEnabled(true);
  3451. }
  3452. streamingStopping = false;
  3453. if (api)
  3454. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3455. OnDeactivate();
  3456. blog(LOG_INFO, STREAMING_STOP);
  3457. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3458. OBSMessageBox::information(this,
  3459. QTStr("Output.ConnectFail.Title"),
  3460. QT_UTF8(errorMessage));
  3461. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3462. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3463. }
  3464. if (!startStreamMenu.isNull()) {
  3465. ui->streamButton->setMenu(nullptr);
  3466. startStreamMenu->deleteLater();
  3467. startStreamMenu = nullptr;
  3468. }
  3469. }
  3470. void OBSBasic::StartRecording()
  3471. {
  3472. if (outputHandler->RecordingActive())
  3473. return;
  3474. if (disableOutputsRef)
  3475. return;
  3476. if (api)
  3477. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3478. SaveProject();
  3479. outputHandler->StartRecording();
  3480. }
  3481. void OBSBasic::RecordStopping()
  3482. {
  3483. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3484. if (sysTrayRecord)
  3485. sysTrayRecord->setText(ui->recordButton->text());
  3486. recordingStopping = true;
  3487. if (api)
  3488. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3489. }
  3490. void OBSBasic::StopRecording()
  3491. {
  3492. SaveProject();
  3493. if (outputHandler->RecordingActive())
  3494. outputHandler->StopRecording(recordingStopping);
  3495. OnDeactivate();
  3496. }
  3497. void OBSBasic::RecordingStart()
  3498. {
  3499. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3500. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3501. if (sysTrayRecord)
  3502. sysTrayRecord->setText(ui->recordButton->text());
  3503. recordingStopping = false;
  3504. if (api)
  3505. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3506. OnActivate();
  3507. blog(LOG_INFO, RECORDING_START);
  3508. }
  3509. void OBSBasic::RecordingStop(int code)
  3510. {
  3511. ui->statusbar->RecordingStopped();
  3512. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3513. if (sysTrayRecord)
  3514. sysTrayRecord->setText(ui->recordButton->text());
  3515. blog(LOG_INFO, RECORDING_STOP);
  3516. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3517. OBSMessageBox::information(this,
  3518. QTStr("Output.RecordFail.Title"),
  3519. QTStr("Output.RecordFail.Unsupported"));
  3520. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3521. OBSMessageBox::information(this,
  3522. QTStr("Output.RecordNoSpace.Title"),
  3523. QTStr("Output.RecordNoSpace.Msg"));
  3524. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3525. OBSMessageBox::information(this,
  3526. QTStr("Output.RecordError.Title"),
  3527. QTStr("Output.RecordError.Msg"));
  3528. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3529. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3530. QSystemTrayIcon::Warning);
  3531. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3532. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3533. QSystemTrayIcon::Warning);
  3534. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3535. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3536. QSystemTrayIcon::Warning);
  3537. }
  3538. if (api)
  3539. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3540. OnDeactivate();
  3541. }
  3542. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3543. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3544. void OBSBasic::StartReplayBuffer()
  3545. {
  3546. if (!outputHandler || !outputHandler->replayBuffer)
  3547. return;
  3548. if (outputHandler->ReplayBufferActive())
  3549. return;
  3550. if (disableOutputsRef)
  3551. return;
  3552. obs_output_t *output = outputHandler->replayBuffer;
  3553. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3554. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3555. "ReplayBuffer.Save");
  3556. size_t count = obs_data_array_count(bindings);
  3557. obs_data_array_release(bindings);
  3558. obs_data_release(hotkeys);
  3559. if (!count) {
  3560. OBSMessageBox::information(this,
  3561. RP_NO_HOTKEY_TITLE,
  3562. RP_NO_HOTKEY_TEXT);
  3563. return;
  3564. }
  3565. if (api)
  3566. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3567. SaveProject();
  3568. outputHandler->StartReplayBuffer();
  3569. }
  3570. void OBSBasic::ReplayBufferStopping()
  3571. {
  3572. if (!outputHandler || !outputHandler->replayBuffer)
  3573. return;
  3574. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3575. if (sysTrayReplayBuffer)
  3576. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3577. replayBufferStopping = true;
  3578. if (api)
  3579. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3580. }
  3581. void OBSBasic::StopReplayBuffer()
  3582. {
  3583. if (!outputHandler || !outputHandler->replayBuffer)
  3584. return;
  3585. SaveProject();
  3586. if (outputHandler->ReplayBufferActive())
  3587. outputHandler->StopReplayBuffer(replayBufferStopping);
  3588. OnDeactivate();
  3589. }
  3590. void OBSBasic::ReplayBufferStart()
  3591. {
  3592. if (!outputHandler || !outputHandler->replayBuffer)
  3593. return;
  3594. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3595. if (sysTrayReplayBuffer)
  3596. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3597. replayBufferStopping = false;
  3598. if (api)
  3599. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3600. OnActivate();
  3601. blog(LOG_INFO, REPLAY_BUFFER_START);
  3602. }
  3603. void OBSBasic::ReplayBufferStop(int code)
  3604. {
  3605. if (!outputHandler || !outputHandler->replayBuffer)
  3606. return;
  3607. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3608. if (sysTrayReplayBuffer)
  3609. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3610. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3611. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3612. OBSMessageBox::information(this,
  3613. QTStr("Output.RecordFail.Title"),
  3614. QTStr("Output.RecordFail.Unsupported"));
  3615. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3616. OBSMessageBox::information(this,
  3617. QTStr("Output.RecordNoSpace.Title"),
  3618. QTStr("Output.RecordNoSpace.Msg"));
  3619. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3620. OBSMessageBox::information(this,
  3621. QTStr("Output.RecordError.Title"),
  3622. QTStr("Output.RecordError.Msg"));
  3623. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3624. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3625. QSystemTrayIcon::Warning);
  3626. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3627. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3628. QSystemTrayIcon::Warning);
  3629. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3630. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3631. QSystemTrayIcon::Warning);
  3632. }
  3633. if (api)
  3634. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3635. OnDeactivate();
  3636. }
  3637. void OBSBasic::on_streamButton_clicked()
  3638. {
  3639. if (outputHandler->StreamingActive()) {
  3640. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3641. "WarnBeforeStoppingStream");
  3642. if (confirm && isVisible()) {
  3643. QMessageBox::StandardButton button =
  3644. OBSMessageBox::question(this,
  3645. QTStr("ConfirmStop.Title"),
  3646. QTStr("ConfirmStop.Text"));
  3647. if (button == QMessageBox::No)
  3648. return;
  3649. }
  3650. StopStreaming();
  3651. } else {
  3652. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3653. "WarnBeforeStartingStream");
  3654. if (confirm && isVisible()) {
  3655. QMessageBox::StandardButton button =
  3656. OBSMessageBox::question(this,
  3657. QTStr("ConfirmStart.Title"),
  3658. QTStr("ConfirmStart.Text"));
  3659. if (button == QMessageBox::No)
  3660. return;
  3661. }
  3662. StartStreaming();
  3663. }
  3664. }
  3665. void OBSBasic::on_recordButton_clicked()
  3666. {
  3667. if (outputHandler->RecordingActive())
  3668. StopRecording();
  3669. else
  3670. StartRecording();
  3671. }
  3672. void OBSBasic::on_settingsButton_clicked()
  3673. {
  3674. on_action_Settings_triggered();
  3675. }
  3676. void OBSBasic::on_actionWebsite_triggered()
  3677. {
  3678. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3679. QDesktopServices::openUrl(url);
  3680. }
  3681. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3682. {
  3683. char path[512];
  3684. int ret = GetConfigPath(path, 512, "obs-studio");
  3685. if (ret <= 0)
  3686. return;
  3687. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3688. }
  3689. void OBSBasic::on_actionShowProfileFolder_triggered()
  3690. {
  3691. char path[512];
  3692. int ret = GetProfilePath(path, 512, "");
  3693. if (ret <= 0)
  3694. return;
  3695. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3696. }
  3697. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3698. {
  3699. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3700. QListWidgetItem *topItem = nullptr;
  3701. if (selectedItems.size() != 0)
  3702. topItem = selectedItems[0];
  3703. return topItem;
  3704. }
  3705. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3706. {
  3707. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3708. UNUSED_PARAMETER(pos);
  3709. }
  3710. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3711. const QPoint &pos)
  3712. {
  3713. QMenu popup(this);
  3714. QPointer<QMenu> previewProjector;
  3715. QAction *action = popup.addAction(
  3716. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3717. this, SLOT(TogglePreview()));
  3718. action->setCheckable(true);
  3719. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3720. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3721. AddProjectorMenuMonitors(previewProjector, this,
  3722. SLOT(OpenPreviewProjector()));
  3723. QAction *previewWindow = popup.addAction(
  3724. QTStr("PreviewWindow"),
  3725. this, SLOT(OpenPreviewWindow()));
  3726. popup.addMenu(previewProjector);
  3727. popup.addAction(previewWindow);
  3728. popup.exec(QCursor::pos());
  3729. UNUSED_PARAMETER(pos);
  3730. }
  3731. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3732. {
  3733. CloseDialogs();
  3734. /* Make sure all dialogs are safely and successfully closed before
  3735. * switching the always on top mode due to the fact that windows all
  3736. * have to be recreated, so queue the actual toggle to happen after
  3737. * all events related to closing the dialogs have finished */
  3738. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3739. Qt::QueuedConnection);
  3740. }
  3741. void OBSBasic::ToggleAlwaysOnTop()
  3742. {
  3743. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3744. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3745. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3746. show();
  3747. }
  3748. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3749. {
  3750. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3751. if (strcmp(val, "10") == 0) {
  3752. num = 10;
  3753. den = 1;
  3754. } else if (strcmp(val, "20") == 0) {
  3755. num = 20;
  3756. den = 1;
  3757. } else if (strcmp(val, "24 NTSC") == 0) {
  3758. num = 24000;
  3759. den = 1001;
  3760. } else if (strcmp(val, "25") == 0) {
  3761. num = 25;
  3762. den = 1;
  3763. } else if (strcmp(val, "29.97") == 0) {
  3764. num = 30000;
  3765. den = 1001;
  3766. } else if (strcmp(val, "48") == 0) {
  3767. num = 48;
  3768. den = 1;
  3769. } else if (strcmp(val, "59.94") == 0) {
  3770. num = 60000;
  3771. den = 1001;
  3772. } else if (strcmp(val, "60") == 0) {
  3773. num = 60;
  3774. den = 1;
  3775. } else {
  3776. num = 30;
  3777. den = 1;
  3778. }
  3779. }
  3780. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3781. {
  3782. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3783. den = 1;
  3784. }
  3785. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3786. {
  3787. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3788. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3789. }
  3790. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3791. {
  3792. num = 1000000000;
  3793. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3794. }
  3795. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3796. {
  3797. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3798. if (type == 1) //"Integer"
  3799. GetFPSInteger(num, den);
  3800. else if (type == 2) //"Fraction"
  3801. GetFPSFraction(num, den);
  3802. else if (false) //"Nanoseconds", currently not implemented
  3803. GetFPSNanoseconds(num, den);
  3804. else
  3805. GetFPSCommon(num, den);
  3806. }
  3807. config_t *OBSBasic::Config() const
  3808. {
  3809. return basicConfig;
  3810. }
  3811. void OBSBasic::on_actionEditTransform_triggered()
  3812. {
  3813. if (transformWindow)
  3814. transformWindow->close();
  3815. transformWindow = new OBSBasicTransform(this);
  3816. transformWindow->show();
  3817. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3818. }
  3819. static obs_transform_info copiedTransformInfo;
  3820. static obs_sceneitem_crop copiedCropInfo;
  3821. void OBSBasic::on_actionCopyTransform_triggered()
  3822. {
  3823. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3824. {
  3825. if (!obs_sceneitem_selected(item))
  3826. return true;
  3827. obs_sceneitem_defer_update_begin(item);
  3828. obs_sceneitem_get_info(item, &copiedTransformInfo);
  3829. obs_sceneitem_get_crop(item, &copiedCropInfo);
  3830. obs_sceneitem_defer_update_end(item);
  3831. UNUSED_PARAMETER(scene);
  3832. UNUSED_PARAMETER(param);
  3833. return true;
  3834. };
  3835. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3836. ui->actionPasteTransform->setEnabled(true);
  3837. }
  3838. void OBSBasic::on_actionPasteTransform_triggered()
  3839. {
  3840. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3841. {
  3842. if (!obs_sceneitem_selected(item))
  3843. return true;
  3844. obs_sceneitem_defer_update_begin(item);
  3845. obs_sceneitem_set_info(item, &copiedTransformInfo);
  3846. obs_sceneitem_set_crop(item, &copiedCropInfo);
  3847. obs_sceneitem_defer_update_end(item);
  3848. UNUSED_PARAMETER(scene);
  3849. UNUSED_PARAMETER(param);
  3850. return true;
  3851. };
  3852. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3853. }
  3854. void OBSBasic::on_actionResetTransform_triggered()
  3855. {
  3856. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3857. {
  3858. if (!obs_sceneitem_selected(item))
  3859. return true;
  3860. obs_sceneitem_defer_update_begin(item);
  3861. obs_transform_info info;
  3862. vec2_set(&info.pos, 0.0f, 0.0f);
  3863. vec2_set(&info.scale, 1.0f, 1.0f);
  3864. info.rot = 0.0f;
  3865. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  3866. info.bounds_type = OBS_BOUNDS_NONE;
  3867. info.bounds_alignment = OBS_ALIGN_CENTER;
  3868. vec2_set(&info.bounds, 0.0f, 0.0f);
  3869. obs_sceneitem_set_info(item, &info);
  3870. obs_sceneitem_crop crop = {};
  3871. obs_sceneitem_set_crop(item, &crop);
  3872. obs_sceneitem_defer_update_end(item);
  3873. UNUSED_PARAMETER(scene);
  3874. UNUSED_PARAMETER(param);
  3875. return true;
  3876. };
  3877. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3878. }
  3879. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  3880. {
  3881. matrix4 boxTransform;
  3882. obs_sceneitem_get_box_transform(item, &boxTransform);
  3883. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  3884. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  3885. auto GetMinPos = [&] (float x, float y)
  3886. {
  3887. vec3 pos;
  3888. vec3_set(&pos, x, y, 0.0f);
  3889. vec3_transform(&pos, &pos, &boxTransform);
  3890. vec3_min(&tl, &tl, &pos);
  3891. vec3_max(&br, &br, &pos);
  3892. };
  3893. GetMinPos(0.0f, 0.0f);
  3894. GetMinPos(1.0f, 0.0f);
  3895. GetMinPos(0.0f, 1.0f);
  3896. GetMinPos(1.0f, 1.0f);
  3897. }
  3898. static vec3 GetItemTL(obs_sceneitem_t *item)
  3899. {
  3900. vec3 tl, br;
  3901. GetItemBox(item, tl, br);
  3902. return tl;
  3903. }
  3904. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  3905. {
  3906. vec3 newTL;
  3907. vec2 pos;
  3908. obs_sceneitem_get_pos(item, &pos);
  3909. newTL = GetItemTL(item);
  3910. pos.x += tl.x - newTL.x;
  3911. pos.y += tl.y - newTL.y;
  3912. obs_sceneitem_set_pos(item, &pos);
  3913. }
  3914. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  3915. void *param)
  3916. {
  3917. if (!obs_sceneitem_selected(item))
  3918. return true;
  3919. float rot = *reinterpret_cast<float*>(param);
  3920. vec3 tl = GetItemTL(item);
  3921. rot += obs_sceneitem_get_rot(item);
  3922. if (rot >= 360.0f) rot -= 360.0f;
  3923. else if (rot <= -360.0f) rot += 360.0f;
  3924. obs_sceneitem_set_rot(item, rot);
  3925. SetItemTL(item, tl);
  3926. UNUSED_PARAMETER(scene);
  3927. UNUSED_PARAMETER(param);
  3928. return true;
  3929. };
  3930. void OBSBasic::on_actionRotate90CW_triggered()
  3931. {
  3932. float f90CW = 90.0f;
  3933. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  3934. }
  3935. void OBSBasic::on_actionRotate90CCW_triggered()
  3936. {
  3937. float f90CCW = -90.0f;
  3938. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  3939. }
  3940. void OBSBasic::on_actionRotate180_triggered()
  3941. {
  3942. float f180 = 180.0f;
  3943. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  3944. }
  3945. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  3946. void *param)
  3947. {
  3948. vec2 &mul = *reinterpret_cast<vec2*>(param);
  3949. if (!obs_sceneitem_selected(item))
  3950. return true;
  3951. vec3 tl = GetItemTL(item);
  3952. vec2 scale;
  3953. obs_sceneitem_get_scale(item, &scale);
  3954. vec2_mul(&scale, &scale, &mul);
  3955. obs_sceneitem_set_scale(item, &scale);
  3956. SetItemTL(item, tl);
  3957. UNUSED_PARAMETER(scene);
  3958. return true;
  3959. }
  3960. void OBSBasic::on_actionFlipHorizontal_triggered()
  3961. {
  3962. vec2 scale;
  3963. vec2_set(&scale, -1.0f, 1.0f);
  3964. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  3965. &scale);
  3966. }
  3967. void OBSBasic::on_actionFlipVertical_triggered()
  3968. {
  3969. vec2 scale;
  3970. vec2_set(&scale, 1.0f, -1.0f);
  3971. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  3972. &scale);
  3973. }
  3974. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  3975. void *param)
  3976. {
  3977. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  3978. if (!obs_sceneitem_selected(item))
  3979. return true;
  3980. obs_video_info ovi;
  3981. obs_get_video_info(&ovi);
  3982. obs_transform_info itemInfo;
  3983. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  3984. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  3985. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  3986. itemInfo.rot = 0.0f;
  3987. vec2_set(&itemInfo.bounds,
  3988. float(ovi.base_width), float(ovi.base_height));
  3989. itemInfo.bounds_type = boundsType;
  3990. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  3991. obs_sceneitem_set_info(item, &itemInfo);
  3992. UNUSED_PARAMETER(scene);
  3993. return true;
  3994. }
  3995. void OBSBasic::on_actionFitToScreen_triggered()
  3996. {
  3997. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  3998. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  3999. &boundsType);
  4000. }
  4001. void OBSBasic::on_actionStretchToScreen_triggered()
  4002. {
  4003. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4004. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4005. &boundsType);
  4006. }
  4007. void OBSBasic::on_actionCenterToScreen_triggered()
  4008. {
  4009. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4010. {
  4011. vec3 tl, br, itemCenter, screenCenter, offset;
  4012. obs_video_info ovi;
  4013. if (!obs_sceneitem_selected(item))
  4014. return true;
  4015. obs_get_video_info(&ovi);
  4016. vec3_set(&screenCenter, float(ovi.base_width),
  4017. float(ovi.base_height), 0.0f);
  4018. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4019. GetItemBox(item, tl, br);
  4020. vec3_sub(&itemCenter, &br, &tl);
  4021. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4022. vec3_add(&itemCenter, &itemCenter, &tl);
  4023. vec3_sub(&offset, &screenCenter, &itemCenter);
  4024. vec3_add(&tl, &tl, &offset);
  4025. SetItemTL(item, tl);
  4026. UNUSED_PARAMETER(scene);
  4027. UNUSED_PARAMETER(param);
  4028. return true;
  4029. };
  4030. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4031. }
  4032. void OBSBasic::EnablePreviewDisplay(bool enable)
  4033. {
  4034. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4035. ui->preview->setVisible(enable);
  4036. ui->previewDisabledLabel->setVisible(!enable);
  4037. }
  4038. void OBSBasic::TogglePreview()
  4039. {
  4040. previewEnabled = !previewEnabled;
  4041. EnablePreviewDisplay(previewEnabled);
  4042. }
  4043. void OBSBasic::Nudge(int dist, MoveDir dir)
  4044. {
  4045. if (ui->preview->Locked())
  4046. return;
  4047. struct MoveInfo {
  4048. float dist;
  4049. MoveDir dir;
  4050. } info = {(float)dist, dir};
  4051. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  4052. {
  4053. if (obs_sceneitem_locked(item))
  4054. return true;
  4055. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  4056. struct vec2 dir;
  4057. struct vec2 pos;
  4058. vec2_set(&dir, 0.0f, 0.0f);
  4059. if (!obs_sceneitem_selected(item))
  4060. return true;
  4061. switch (info->dir) {
  4062. case MoveDir::Up: dir.y = -info->dist; break;
  4063. case MoveDir::Down: dir.y = info->dist; break;
  4064. case MoveDir::Left: dir.x = -info->dist; break;
  4065. case MoveDir::Right: dir.x = info->dist; break;
  4066. }
  4067. obs_sceneitem_get_pos(item, &pos);
  4068. vec2_add(&pos, &pos, &dir);
  4069. obs_sceneitem_set_pos(item, &pos);
  4070. return true;
  4071. };
  4072. obs_scene_enum_items(GetCurrentScene(), func, &info);
  4073. }
  4074. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4075. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4076. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4077. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4078. void OBSBasic::OpenProjector(obs_source_t *source, int monitor, bool window,
  4079. QString title)
  4080. {
  4081. /* seriously? 10 monitors? */
  4082. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4083. return;
  4084. bool isPreview = false;
  4085. if (source == nullptr)
  4086. isPreview = true;
  4087. if (!window) {
  4088. delete projectors[monitor];
  4089. projectors[monitor].clear();
  4090. RemoveSavedProjectors(monitor);
  4091. }
  4092. OBSProjector *projector = new OBSProjector(nullptr, source, !!window);
  4093. const char *name = obs_source_get_name(source);
  4094. if (!window) {
  4095. if (isPreview) {
  4096. previewProjectorArray.at((size_t)monitor) = 1;
  4097. } else {
  4098. projectorArray.at((size_t)monitor) = name;
  4099. }
  4100. }
  4101. if (!window) {
  4102. projector->Init(monitor, false, nullptr);
  4103. projectors[monitor] = projector;
  4104. } else {
  4105. projector->Init(monitor, true, title);
  4106. for (auto &projPtr : windowProjectors) {
  4107. if (!projPtr) {
  4108. projPtr = projector;
  4109. projector = nullptr;
  4110. }
  4111. }
  4112. if (projector)
  4113. windowProjectors.push_back(projector);
  4114. }
  4115. }
  4116. void OBSBasic::OpenPreviewProjector()
  4117. {
  4118. int monitor = sender()->property("monitor").toInt();
  4119. OpenProjector(nullptr, monitor, false);
  4120. }
  4121. void OBSBasic::OpenSourceProjector()
  4122. {
  4123. int monitor = sender()->property("monitor").toInt();
  4124. OBSSceneItem item = GetCurrentSceneItem();
  4125. if (!item)
  4126. return;
  4127. OpenProjector(obs_sceneitem_get_source(item), monitor, false);
  4128. }
  4129. void OBSBasic::OpenSceneProjector()
  4130. {
  4131. int monitor = sender()->property("monitor").toInt();
  4132. OBSScene scene = GetCurrentScene();
  4133. if (!scene)
  4134. return;
  4135. OpenProjector(obs_scene_get_source(scene), monitor, false);
  4136. }
  4137. void OBSBasic::OpenPreviewWindow()
  4138. {
  4139. int monitor = sender()->property("monitor").toInt();
  4140. QString title = QTStr("PreviewWindow");
  4141. OpenProjector(nullptr, monitor, true, title);
  4142. }
  4143. void OBSBasic::OpenSourceWindow()
  4144. {
  4145. int monitor = sender()->property("monitor").toInt();
  4146. OBSSceneItem item = GetCurrentSceneItem();
  4147. OBSSource source = obs_sceneitem_get_source(item);
  4148. QString text = QString::fromUtf8(obs_source_get_name(source));
  4149. QString title = QTStr("SourceWindow") + " - " + text;
  4150. if (!item)
  4151. return;
  4152. OpenProjector(obs_sceneitem_get_source(item), monitor, true, title);
  4153. }
  4154. void OBSBasic::OpenSceneWindow()
  4155. {
  4156. int monitor = sender()->property("monitor").toInt();
  4157. OBSScene scene = GetCurrentScene();
  4158. OBSSource source = obs_scene_get_source(scene);
  4159. QString text = QString::fromUtf8(obs_source_get_name(source));
  4160. QString title = QTStr("SceneWindow") + " - " + text;
  4161. if (!scene)
  4162. return;
  4163. OpenProjector(obs_scene_get_source(scene), monitor, true, title);
  4164. }
  4165. void OBSBasic::OpenSavedProjectors()
  4166. {
  4167. bool projectorSave = config_get_bool(GetGlobalConfig(),
  4168. "BasicWindow", "SaveProjectors");
  4169. if (projectorSave) {
  4170. for (size_t i = 0; i < projectorArray.size(); i++) {
  4171. if (projectorArray.at(i).empty() == false) {
  4172. OBSSource source = obs_get_source_by_name(
  4173. projectorArray.at(i).c_str());
  4174. if (!source) {
  4175. RemoveSavedProjectors((int)i);
  4176. obs_source_release(source);
  4177. continue;
  4178. }
  4179. OpenProjector(source, (int)i, false);
  4180. obs_source_release(source);
  4181. }
  4182. }
  4183. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  4184. if (previewProjectorArray.at(i) == 1) {
  4185. OpenProjector(nullptr, (int)i, false);
  4186. }
  4187. }
  4188. }
  4189. }
  4190. void OBSBasic::RemoveSavedProjectors(int monitor)
  4191. {
  4192. previewProjectorArray.at((size_t)monitor) = 0;
  4193. projectorArray.at((size_t)monitor) = "";
  4194. }
  4195. void OBSBasic::on_actionFullscreenInterface_triggered()
  4196. {
  4197. if (!fullscreenInterface)
  4198. showFullScreen();
  4199. else
  4200. showNormal();
  4201. fullscreenInterface = !fullscreenInterface;
  4202. }
  4203. void OBSBasic::UpdateTitleBar()
  4204. {
  4205. stringstream name;
  4206. const char *profile = config_get_string(App()->GlobalConfig(),
  4207. "Basic", "Profile");
  4208. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4209. "Basic", "SceneCollection");
  4210. name << "OBS ";
  4211. if (previewProgramMode)
  4212. name << "Studio ";
  4213. name << App()->GetVersionString();
  4214. if (App()->IsPortableMode())
  4215. name << " - Portable Mode";
  4216. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4217. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4218. setWindowTitle(QT_UTF8(name.str().c_str()));
  4219. }
  4220. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4221. {
  4222. char profiles_path[512];
  4223. const char *profile = config_get_string(App()->GlobalConfig(),
  4224. "Basic", "ProfileDir");
  4225. int ret;
  4226. if (!profile)
  4227. return -1;
  4228. if (!path)
  4229. return -1;
  4230. if (!file)
  4231. file = "";
  4232. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4233. if (ret <= 0)
  4234. return ret;
  4235. if (!*file)
  4236. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4237. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4238. }
  4239. void OBSBasic::on_resetUI_triggered()
  4240. {
  4241. restoreState(startingDockLayout);
  4242. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4243. int cx = width();
  4244. int cy = height();
  4245. int cx22_5 = cx * 225 / 1000;
  4246. int cx5 = cx * 5 / 100;
  4247. cy = cy * 225 / 1000;
  4248. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4249. QList<QDockWidget*> docks {
  4250. ui->scenesDock,
  4251. ui->sourcesDock,
  4252. ui->mixerDock,
  4253. ui->transitionsDock,
  4254. ui->controlsDock
  4255. };
  4256. QList<int> sizes {
  4257. cx22_5,
  4258. cx22_5,
  4259. mixerSize,
  4260. cx5,
  4261. cx5
  4262. };
  4263. ui->scenesDock->setVisible(true);
  4264. ui->sourcesDock->setVisible(true);
  4265. ui->mixerDock->setVisible(true);
  4266. ui->transitionsDock->setVisible(true);
  4267. ui->controlsDock->setVisible(true);
  4268. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4269. resizeDocks(docks, sizes, Qt::Horizontal);
  4270. #endif
  4271. }
  4272. void OBSBasic::on_lockUI_toggled(bool lock)
  4273. {
  4274. QDockWidget::DockWidgetFeatures features = lock
  4275. ? QDockWidget::NoDockWidgetFeatures
  4276. : QDockWidget::AllDockWidgetFeatures;
  4277. ui->scenesDock->setFeatures(features);
  4278. ui->sourcesDock->setFeatures(features);
  4279. ui->mixerDock->setFeatures(features);
  4280. ui->transitionsDock->setFeatures(features);
  4281. ui->controlsDock->setFeatures(features);
  4282. }
  4283. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4284. {
  4285. ui->sourcesToolbar->setVisible(visible);
  4286. ui->scenesToolbar->setVisible(visible);
  4287. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4288. "ShowListboxToolbars", visible);
  4289. }
  4290. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4291. {
  4292. ui->statusbar->setVisible(visible);
  4293. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4294. "ShowStatusBar", visible);
  4295. }
  4296. void OBSBasic::on_actionLockPreview_triggered()
  4297. {
  4298. ui->preview->ToggleLocked();
  4299. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4300. }
  4301. void OBSBasic::on_scalingMenu_aboutToShow()
  4302. {
  4303. obs_video_info ovi;
  4304. obs_get_video_info(&ovi);
  4305. QAction *action = ui->actionScaleCanvas;
  4306. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4307. text = text.arg(QString::number(ovi.base_width),
  4308. QString::number(ovi.base_height));
  4309. action->setText(text);
  4310. action = ui->actionScaleOutput;
  4311. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4312. text = text.arg(QString::number(ovi.output_width),
  4313. QString::number(ovi.output_height));
  4314. action->setText(text);
  4315. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4316. ovi.output_height == ovi.base_height));
  4317. UpdatePreviewScalingMenu();
  4318. }
  4319. void OBSBasic::on_actionScaleWindow_triggered()
  4320. {
  4321. ui->preview->SetFixedScaling(false);
  4322. ui->preview->ResetScrollingOffset();
  4323. emit ui->preview->DisplayResized();
  4324. }
  4325. void OBSBasic::on_actionScaleCanvas_triggered()
  4326. {
  4327. ui->preview->SetFixedScaling(true);
  4328. ui->preview->SetScalingLevel(0);
  4329. emit ui->preview->DisplayResized();
  4330. }
  4331. void OBSBasic::on_actionScaleOutput_triggered()
  4332. {
  4333. obs_video_info ovi;
  4334. obs_get_video_info(&ovi);
  4335. ui->preview->SetFixedScaling(true);
  4336. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4337. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4338. int32_t approxScalingLevel = int32_t(
  4339. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4340. ui->preview->SetScalingLevel(approxScalingLevel);
  4341. ui->preview->SetScalingAmount(scalingAmount);
  4342. emit ui->preview->DisplayResized();
  4343. }
  4344. void OBSBasic::SetShowing(bool showing)
  4345. {
  4346. if (!showing && isVisible()) {
  4347. config_set_string(App()->GlobalConfig(),
  4348. "BasicWindow", "geometry",
  4349. saveGeometry().toBase64().constData());
  4350. /* hide all visible child dialogs */
  4351. visDlgPositions.clear();
  4352. if (!visDialogs.isEmpty()) {
  4353. for (QDialog *dlg : visDialogs) {
  4354. visDlgPositions.append(dlg->pos());
  4355. dlg->hide();
  4356. }
  4357. }
  4358. if (showHide)
  4359. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4360. QTimer::singleShot(250, this, SLOT(hide()));
  4361. if (previewEnabled)
  4362. EnablePreviewDisplay(false);
  4363. setVisible(false);
  4364. } else if (showing && !isVisible()) {
  4365. if (showHide)
  4366. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4367. QTimer::singleShot(250, this, SLOT(show()));
  4368. if (previewEnabled)
  4369. EnablePreviewDisplay(true);
  4370. setVisible(true);
  4371. /* show all child dialogs that was visible earlier */
  4372. if (!visDialogs.isEmpty()) {
  4373. for (int i = 0; i < visDialogs.size(); ++i) {
  4374. QDialog *dlg = visDialogs[i];
  4375. dlg->move(visDlgPositions[i]);
  4376. dlg->show();
  4377. }
  4378. }
  4379. /* Unminimize window if it was hidden to tray instead of task
  4380. * bar. */
  4381. if (sysTrayMinimizeToTray()) {
  4382. Qt::WindowStates state;
  4383. state = windowState() & ~Qt::WindowMinimized;
  4384. state |= Qt::WindowActive;
  4385. setWindowState(state);
  4386. }
  4387. }
  4388. }
  4389. void OBSBasic::ToggleShowHide()
  4390. {
  4391. bool showing = isVisible();
  4392. if (showing) {
  4393. /* check for modal dialogs */
  4394. EnumDialogs();
  4395. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4396. return;
  4397. }
  4398. SetShowing(!showing);
  4399. }
  4400. void OBSBasic::SystemTrayInit()
  4401. {
  4402. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4403. this);
  4404. trayIcon->setToolTip("OBS Studio");
  4405. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4406. trayIcon);
  4407. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4408. trayIcon);
  4409. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4410. trayIcon);
  4411. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4412. trayIcon);
  4413. exit = new QAction(QTStr("Exit"),
  4414. trayIcon);
  4415. if (outputHandler && !outputHandler->replayBuffer)
  4416. sysTrayReplayBuffer->setEnabled(false);
  4417. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4418. this,
  4419. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4420. connect(showHide, SIGNAL(triggered()),
  4421. this, SLOT(ToggleShowHide()));
  4422. connect(sysTrayStream, SIGNAL(triggered()),
  4423. this, SLOT(on_streamButton_clicked()));
  4424. connect(sysTrayRecord, SIGNAL(triggered()),
  4425. this, SLOT(on_recordButton_clicked()));
  4426. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4427. this, &OBSBasic::ReplayBufferClicked);
  4428. connect(exit, SIGNAL(triggered()),
  4429. this, SLOT(close()));
  4430. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4431. AddProjectorMenuMonitors(previewProjector, this,
  4432. SLOT(OpenPreviewProjector()));
  4433. trayMenu = new QMenu;
  4434. trayMenu->addAction(showHide);
  4435. trayMenu->addMenu(previewProjector);
  4436. trayMenu->addAction(sysTrayStream);
  4437. trayMenu->addAction(sysTrayRecord);
  4438. trayMenu->addAction(sysTrayReplayBuffer);
  4439. trayMenu->addAction(exit);
  4440. trayIcon->setContextMenu(trayMenu);
  4441. }
  4442. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4443. {
  4444. if (reason == QSystemTrayIcon::Trigger)
  4445. ToggleShowHide();
  4446. }
  4447. void OBSBasic::SysTrayNotify(const QString &text,
  4448. QSystemTrayIcon::MessageIcon n)
  4449. {
  4450. if (QSystemTrayIcon::supportsMessages()) {
  4451. QSystemTrayIcon::MessageIcon icon =
  4452. QSystemTrayIcon::MessageIcon(n);
  4453. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4454. }
  4455. }
  4456. void OBSBasic::SystemTray(bool firstStarted)
  4457. {
  4458. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4459. return;
  4460. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4461. "BasicWindow", "SysTrayWhenStarted");
  4462. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4463. "BasicWindow", "SysTrayEnabled");
  4464. if (firstStarted)
  4465. SystemTrayInit();
  4466. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4467. trayIcon->hide();
  4468. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4469. || opt_minimize_tray) {
  4470. trayIcon->show();
  4471. if (firstStarted) {
  4472. QTimer::singleShot(50, this, SLOT(hide()));
  4473. EnablePreviewDisplay(false);
  4474. setVisible(false);
  4475. opt_minimize_tray = false;
  4476. }
  4477. } else if (sysTrayEnabled) {
  4478. trayIcon->show();
  4479. } else if (!sysTrayEnabled) {
  4480. trayIcon->hide();
  4481. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4482. trayIcon->hide();
  4483. }
  4484. if (isVisible())
  4485. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4486. else
  4487. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4488. }
  4489. bool OBSBasic::sysTrayMinimizeToTray()
  4490. {
  4491. return config_get_bool(GetGlobalConfig(),
  4492. "BasicWindow", "SysTrayMinimizeToTray");
  4493. }
  4494. void OBSBasic::on_actionCopySource_triggered()
  4495. {
  4496. on_actionCopyTransform_triggered();
  4497. OBSSceneItem item = GetCurrentSceneItem();
  4498. if (!item)
  4499. return;
  4500. OBSSource source = obs_sceneitem_get_source(item);
  4501. copyString = obs_source_get_name(source);
  4502. copyVisible = obs_sceneitem_visible(item);
  4503. ui->actionPasteRef->setEnabled(true);
  4504. ui->actionPasteDup->setEnabled(true);
  4505. }
  4506. void OBSBasic::on_actionPasteRef_triggered()
  4507. {
  4508. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4509. on_actionPasteTransform_triggered();
  4510. }
  4511. void OBSBasic::on_actionPasteDup_triggered()
  4512. {
  4513. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4514. on_actionPasteTransform_triggered();
  4515. }
  4516. void OBSBasic::on_actionCopyFilters_triggered()
  4517. {
  4518. OBSSceneItem item = GetCurrentSceneItem();
  4519. if (!item)
  4520. return;
  4521. OBSSource source = obs_sceneitem_get_source(item);
  4522. copyFiltersString = obs_source_get_name(source);
  4523. ui->actionPasteFilters->setEnabled(true);
  4524. }
  4525. void OBSBasic::on_actionPasteFilters_triggered()
  4526. {
  4527. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4528. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4529. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4530. if (source == dstSource)
  4531. return;
  4532. obs_source_copy_filters(dstSource, source);
  4533. }
  4534. void OBSBasic::on_autoConfigure_triggered()
  4535. {
  4536. AutoConfig test(this);
  4537. test.setModal(true);
  4538. test.show();
  4539. test.exec();
  4540. }
  4541. void OBSBasic::on_stats_triggered()
  4542. {
  4543. if (!stats.isNull()) {
  4544. stats->show();
  4545. stats->raise();
  4546. return;
  4547. }
  4548. OBSBasicStats *statsDlg;
  4549. statsDlg = new OBSBasicStats(nullptr);
  4550. statsDlg->show();
  4551. stats = statsDlg;
  4552. }