window-basic-main.cpp 178 KB

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