window-basic-main.cpp 187 KB

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