window-basic-main.cpp 200 KB

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