window-basic-main.cpp 203 KB

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