window-basic-main.cpp 130 KB

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