window-basic-main.cpp 138 KB

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