window-basic-main.cpp 203 KB

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