window-basic-main.cpp 136 KB

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