window-basic-main.cpp 145 KB

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