window-basic-main.cpp 147 KB

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