window-basic-main.cpp 188 KB

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