window-basic-main.cpp 187 KB

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