window-basic-main.cpp 180 KB

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