window-basic-main.cpp 164 KB

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