window-basic-main.cpp 202 KB

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