window-basic-main.cpp 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076
  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::EnumDialogs()
  2184. {
  2185. visDialogs.clear();
  2186. modalDialogs.clear();
  2187. visMsgBoxes.clear();
  2188. /* fill list of Visible dialogs and Modal dialogs */
  2189. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2190. for (QDialog *dialog : dialogs) {
  2191. if (dialog->isVisible())
  2192. visDialogs.append(dialog);
  2193. if (dialog->isModal())
  2194. modalDialogs.append(dialog);
  2195. }
  2196. /* fill list of Visible message boxes */
  2197. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2198. for (QMessageBox *msgbox : msgBoxes) {
  2199. if (msgbox->isVisible())
  2200. visMsgBoxes.append(msgbox);
  2201. }
  2202. }
  2203. void OBSBasic::ClearSceneData()
  2204. {
  2205. disableSaving++;
  2206. CloseDialogs();
  2207. ClearVolumeControls();
  2208. ClearListItems(ui->scenes);
  2209. ClearListItems(ui->sources);
  2210. ClearQuickTransitions();
  2211. ui->transitions->clear();
  2212. obs_set_output_source(0, nullptr);
  2213. obs_set_output_source(1, nullptr);
  2214. obs_set_output_source(2, nullptr);
  2215. obs_set_output_source(3, nullptr);
  2216. obs_set_output_source(4, nullptr);
  2217. obs_set_output_source(5, nullptr);
  2218. lastScene = nullptr;
  2219. swapScene = nullptr;
  2220. programScene = nullptr;
  2221. auto cb = [](void *unused, obs_source_t *source)
  2222. {
  2223. obs_source_remove(source);
  2224. UNUSED_PARAMETER(unused);
  2225. return true;
  2226. };
  2227. obs_enum_sources(cb, nullptr);
  2228. disableSaving--;
  2229. blog(LOG_INFO, "All scene data cleared");
  2230. blog(LOG_INFO, "------------------------------------------------");
  2231. }
  2232. void OBSBasic::closeEvent(QCloseEvent *event)
  2233. {
  2234. if (isVisible())
  2235. config_set_string(App()->GlobalConfig(),
  2236. "BasicWindow", "geometry",
  2237. saveGeometry().toBase64().constData());
  2238. if (outputHandler && outputHandler->Active()) {
  2239. SetShowing(true);
  2240. QMessageBox::StandardButton button = QMessageBox::question(
  2241. this, QTStr("ConfirmExit.Title"),
  2242. QTStr("ConfirmExit.Text"));
  2243. if (button == QMessageBox::No) {
  2244. event->ignore();
  2245. return;
  2246. }
  2247. }
  2248. QWidget::closeEvent(event);
  2249. if (!event->isAccepted())
  2250. return;
  2251. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2252. if (updateCheckThread)
  2253. updateCheckThread->wait();
  2254. if (logUploadThread)
  2255. logUploadThread->wait();
  2256. signalHandlers.clear();
  2257. SaveProjectNow();
  2258. if (api)
  2259. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2260. disableSaving++;
  2261. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2262. * sources, etc) so that all references are released before shutdown */
  2263. ClearSceneData();
  2264. }
  2265. void OBSBasic::changeEvent(QEvent *event)
  2266. {
  2267. if (event->type() == QEvent::WindowStateChange &&
  2268. isMinimized() &&
  2269. trayIcon->isVisible() &&
  2270. sysTrayMinimizeToTray()) {
  2271. ToggleShowHide();
  2272. }
  2273. }
  2274. void OBSBasic::on_actionShow_Recordings_triggered()
  2275. {
  2276. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2277. const char *path = strcmp(mode, "Advanced") ?
  2278. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2279. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2280. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2281. }
  2282. void OBSBasic::on_actionRemux_triggered()
  2283. {
  2284. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2285. const char *path = strcmp(mode, "Advanced") ?
  2286. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2287. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2288. OBSRemux remux(path, this);
  2289. remux.exec();
  2290. }
  2291. void OBSBasic::on_action_Settings_triggered()
  2292. {
  2293. OBSBasicSettings settings(this);
  2294. settings.exec();
  2295. SystemTray(false);
  2296. }
  2297. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2298. {
  2299. if (advAudioWindow != nullptr) {
  2300. advAudioWindow->raise();
  2301. return;
  2302. }
  2303. advAudioWindow = new OBSBasicAdvAudio(this);
  2304. advAudioWindow->show();
  2305. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2306. connect(advAudioWindow, SIGNAL(destroyed()),
  2307. this, SLOT(on_advAudioProps_destroyed()));
  2308. }
  2309. void OBSBasic::on_advAudioProps_clicked()
  2310. {
  2311. on_actionAdvAudioProperties_triggered();
  2312. }
  2313. void OBSBasic::on_advAudioProps_destroyed()
  2314. {
  2315. advAudioWindow = nullptr;
  2316. }
  2317. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2318. QListWidgetItem *prev)
  2319. {
  2320. obs_source_t *source = NULL;
  2321. if (sceneChanging)
  2322. return;
  2323. if (current) {
  2324. obs_scene_t *scene;
  2325. scene = GetOBSRef<OBSScene>(current);
  2326. source = obs_scene_get_source(scene);
  2327. }
  2328. SetCurrentScene(source);
  2329. UNUSED_PARAMETER(prev);
  2330. }
  2331. void OBSBasic::EditSceneName()
  2332. {
  2333. QListWidgetItem *item = ui->scenes->currentItem();
  2334. Qt::ItemFlags flags = item->flags();
  2335. item->setFlags(flags | Qt::ItemIsEditable);
  2336. ui->scenes->editItem(item);
  2337. item->setFlags(flags);
  2338. }
  2339. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2340. const char *slot)
  2341. {
  2342. QAction *action;
  2343. QList<QScreen*> screens = QGuiApplication::screens();
  2344. for (int i = 0; i < screens.size(); i++) {
  2345. QRect screenGeometry = screens[i]->geometry();
  2346. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2347. arg(QTStr("Display"),
  2348. QString::number(i),
  2349. QString::number((int)screenGeometry.width()),
  2350. QString::number((int)screenGeometry.height()),
  2351. QString::number((int)screenGeometry.x()),
  2352. QString::number((int)screenGeometry.y()));
  2353. action = parent->addAction(str, target, slot);
  2354. action->setProperty("monitor", i);
  2355. }
  2356. }
  2357. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2358. {
  2359. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2360. QPointer<QMenu> sceneProjectorMenu;
  2361. QMenu popup(this);
  2362. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2363. popup.addAction(QTStr("Add"),
  2364. this, SLOT(on_actionAddScene_triggered()));
  2365. if (item) {
  2366. popup.addSeparator();
  2367. popup.addAction(QTStr("Duplicate"),
  2368. this, SLOT(DuplicateSelectedScene()));
  2369. popup.addAction(QTStr("Rename"),
  2370. this, SLOT(EditSceneName()));
  2371. popup.addAction(QTStr("Remove"),
  2372. this, SLOT(RemoveSelectedScene()),
  2373. DeleteKeys.front());
  2374. popup.addSeparator();
  2375. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2376. this, SLOT(on_actionSceneUp_triggered()));
  2377. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2378. this, SLOT(on_actionSceneDown_triggered()));
  2379. order.addSeparator();
  2380. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2381. this, SLOT(MoveSceneToTop()));
  2382. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2383. this, SLOT(MoveSceneToBottom()));
  2384. popup.addMenu(&order);
  2385. popup.addSeparator();
  2386. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2387. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2388. SLOT(OpenSceneProjector()));
  2389. popup.addMenu(sceneProjectorMenu);
  2390. popup.addSeparator();
  2391. popup.addAction(QTStr("Filters"), this,
  2392. SLOT(OpenSceneFilters()));
  2393. }
  2394. popup.exec(QCursor::pos());
  2395. }
  2396. void OBSBasic::on_actionAddScene_triggered()
  2397. {
  2398. string name;
  2399. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2400. int i = 1;
  2401. QString placeHolderText = format.arg(i);
  2402. obs_source_t *source = nullptr;
  2403. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2404. obs_source_release(source);
  2405. placeHolderText = format.arg(++i);
  2406. }
  2407. bool accepted = NameDialog::AskForName(this,
  2408. QTStr("Basic.Main.AddSceneDlg.Title"),
  2409. QTStr("Basic.Main.AddSceneDlg.Text"),
  2410. name,
  2411. placeHolderText);
  2412. if (accepted) {
  2413. if (name.empty()) {
  2414. QMessageBox::information(this,
  2415. QTStr("NoNameEntered.Title"),
  2416. QTStr("NoNameEntered.Text"));
  2417. on_actionAddScene_triggered();
  2418. return;
  2419. }
  2420. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2421. if (source) {
  2422. QMessageBox::information(this,
  2423. QTStr("NameExists.Title"),
  2424. QTStr("NameExists.Text"));
  2425. obs_source_release(source);
  2426. on_actionAddScene_triggered();
  2427. return;
  2428. }
  2429. obs_scene_t *scene = obs_scene_create(name.c_str());
  2430. source = obs_scene_get_source(scene);
  2431. AddScene(source);
  2432. SetCurrentScene(source);
  2433. obs_scene_release(scene);
  2434. }
  2435. }
  2436. void OBSBasic::on_actionRemoveScene_triggered()
  2437. {
  2438. OBSScene scene = GetCurrentScene();
  2439. obs_source_t *source = obs_scene_get_source(scene);
  2440. if (source && QueryRemoveSource(source))
  2441. obs_source_remove(source);
  2442. }
  2443. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2444. {
  2445. int idx = ui->scenes->currentRow();
  2446. if (idx == -1 || idx == invalidIdx)
  2447. return;
  2448. sceneChanging = true;
  2449. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2450. if (!relative)
  2451. idx = 0;
  2452. ui->scenes->insertItem(idx + offset, item);
  2453. ui->scenes->setCurrentRow(idx + offset);
  2454. item->setSelected(true);
  2455. sceneChanging = false;
  2456. }
  2457. void OBSBasic::on_actionSceneUp_triggered()
  2458. {
  2459. ChangeSceneIndex(true, -1, 0);
  2460. }
  2461. void OBSBasic::on_actionSceneDown_triggered()
  2462. {
  2463. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2464. }
  2465. void OBSBasic::MoveSceneToTop()
  2466. {
  2467. ChangeSceneIndex(false, 0, 0);
  2468. }
  2469. void OBSBasic::MoveSceneToBottom()
  2470. {
  2471. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2472. ui->scenes->count() - 1);
  2473. }
  2474. void OBSBasic::on_sources_itemSelectionChanged()
  2475. {
  2476. SignalBlocker sourcesSignalBlocker(ui->sources);
  2477. auto updateItemSelection = [&]()
  2478. {
  2479. ignoreSelectionUpdate = true;
  2480. for (int i = 0; i < ui->sources->count(); i++)
  2481. {
  2482. QListWidgetItem *wItem = ui->sources->item(i);
  2483. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2484. obs_sceneitem_select(item, wItem->isSelected());
  2485. }
  2486. ignoreSelectionUpdate = false;
  2487. };
  2488. using updateItemSelection_t = decltype(updateItemSelection);
  2489. obs_scene_atomic_update(GetCurrentScene(),
  2490. [](void *data, obs_scene_t *)
  2491. {
  2492. (*static_cast<updateItemSelection_t*>(data))();
  2493. }, static_cast<void*>(&updateItemSelection));
  2494. }
  2495. void OBSBasic::EditSceneItemName()
  2496. {
  2497. QListWidgetItem *item = GetTopSelectedSourceItem();
  2498. Qt::ItemFlags flags = item->flags();
  2499. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2500. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2501. const char *name = obs_source_get_name(source);
  2502. item->setText(QT_UTF8(name));
  2503. item->setFlags(flags | Qt::ItemIsEditable);
  2504. ui->sources->removeItemWidget(item);
  2505. ui->sources->editItem(item);
  2506. item->setFlags(flags);
  2507. }
  2508. void OBSBasic::SetDeinterlacingMode()
  2509. {
  2510. QAction *action = reinterpret_cast<QAction*>(sender());
  2511. obs_deinterlace_mode mode =
  2512. (obs_deinterlace_mode)action->property("mode").toInt();
  2513. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2514. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2515. obs_source_set_deinterlace_mode(source, mode);
  2516. }
  2517. void OBSBasic::SetDeinterlacingOrder()
  2518. {
  2519. QAction *action = reinterpret_cast<QAction*>(sender());
  2520. obs_deinterlace_field_order order =
  2521. (obs_deinterlace_field_order)action->property("order").toInt();
  2522. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2523. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2524. obs_source_set_deinterlace_field_order(source, order);
  2525. }
  2526. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2527. {
  2528. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2529. obs_deinterlace_mode deinterlaceMode =
  2530. obs_source_get_deinterlace_mode(source);
  2531. obs_deinterlace_field_order deinterlaceOrder =
  2532. obs_source_get_deinterlace_field_order(source);
  2533. QAction *action;
  2534. #define ADD_MODE(name, mode) \
  2535. action = menu->addAction(QTStr("" name), this, \
  2536. SLOT(SetDeinterlacingMode())); \
  2537. action->setProperty("mode", (int)mode); \
  2538. action->setCheckable(true); \
  2539. action->setChecked(deinterlaceMode == mode);
  2540. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2541. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2542. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2543. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2544. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2545. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2546. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2547. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2548. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2549. #undef ADD_MODE
  2550. menu->addSeparator();
  2551. #define ADD_ORDER(name, order) \
  2552. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2553. SLOT(SetDeinterlacingOrder())); \
  2554. action->setProperty("order", (int)order); \
  2555. action->setCheckable(true); \
  2556. action->setChecked(deinterlaceOrder == order);
  2557. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2558. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2559. #undef ADD_ORDER
  2560. return menu;
  2561. }
  2562. void OBSBasic::SetScaleFilter()
  2563. {
  2564. QAction *action = reinterpret_cast<QAction*>(sender());
  2565. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2566. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2567. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2568. }
  2569. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2570. {
  2571. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2572. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2573. QAction *action;
  2574. #define ADD_MODE(name, mode) \
  2575. action = menu->addAction(QTStr("" name), this, \
  2576. SLOT(SetScaleFilter())); \
  2577. action->setProperty("mode", (int)mode); \
  2578. action->setCheckable(true); \
  2579. action->setChecked(scaleFilter == mode);
  2580. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2581. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2582. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2583. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2584. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2585. #undef ADD_MODE
  2586. return menu;
  2587. }
  2588. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2589. {
  2590. QMenu popup(this);
  2591. QPointer<QMenu> previewProjector;
  2592. QPointer<QMenu> sourceProjector;
  2593. if (preview) {
  2594. QAction *action = popup.addAction(
  2595. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2596. this, SLOT(TogglePreview()));
  2597. action->setCheckable(true);
  2598. action->setChecked(
  2599. obs_display_enabled(ui->preview->GetDisplay()));
  2600. if (IsPreviewProgramMode())
  2601. action->setEnabled(false);
  2602. popup.addAction(ui->actionLockPreview);
  2603. popup.addMenu(ui->scalingMenu);
  2604. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2605. AddProjectorMenuMonitors(previewProjector, this,
  2606. SLOT(OpenPreviewProjector()));
  2607. popup.addMenu(previewProjector);
  2608. popup.addSeparator();
  2609. }
  2610. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2611. if (addSourceMenu)
  2612. popup.addMenu(addSourceMenu);
  2613. if (item) {
  2614. if (addSourceMenu)
  2615. popup.addSeparator();
  2616. OBSSceneItem sceneItem = GetSceneItem(item);
  2617. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2618. uint32_t flags = obs_source_get_output_flags(source);
  2619. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2620. OBS_SOURCE_ASYNC_VIDEO;
  2621. QAction *action;
  2622. popup.addAction(QTStr("Rename"), this,
  2623. SLOT(EditSceneItemName()));
  2624. popup.addAction(QTStr("Remove"), this,
  2625. SLOT(on_actionRemoveSource_triggered()),
  2626. DeleteKeys.front());
  2627. popup.addSeparator();
  2628. popup.addMenu(ui->orderMenu);
  2629. popup.addMenu(ui->transformMenu);
  2630. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2631. AddProjectorMenuMonitors(sourceProjector, this,
  2632. SLOT(OpenSourceProjector()));
  2633. popup.addSeparator();
  2634. if (isAsyncVideo) {
  2635. popup.addMenu(AddDeinterlacingMenu(source));
  2636. popup.addSeparator();
  2637. }
  2638. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  2639. popup.addSeparator();
  2640. popup.addMenu(sourceProjector);
  2641. popup.addSeparator();
  2642. action = popup.addAction(QTStr("Interact"), this,
  2643. SLOT(on_actionInteract_triggered()));
  2644. action->setEnabled(obs_source_get_output_flags(source) &
  2645. OBS_SOURCE_INTERACTION);
  2646. popup.addAction(QTStr("Filters"), this,
  2647. SLOT(OpenFilters()));
  2648. popup.addAction(QTStr("Properties"), this,
  2649. SLOT(on_actionSourceProperties_triggered()));
  2650. }
  2651. popup.exec(QCursor::pos());
  2652. }
  2653. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  2654. {
  2655. if (ui->scenes->count())
  2656. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  2657. }
  2658. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  2659. {
  2660. if (!witem)
  2661. return;
  2662. OBSSceneItem item = GetSceneItem(witem);
  2663. OBSSource source = obs_sceneitem_get_source(item);
  2664. if (source)
  2665. CreatePropertiesWindow(source);
  2666. }
  2667. void OBSBasic::AddSource(const char *id)
  2668. {
  2669. if (id && *id) {
  2670. OBSBasicSourceSelect sourceSelect(this, id);
  2671. sourceSelect.exec();
  2672. if (sourceSelect.newSource)
  2673. CreatePropertiesWindow(sourceSelect.newSource);
  2674. }
  2675. }
  2676. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  2677. {
  2678. const char *type;
  2679. bool foundValues = false;
  2680. bool foundDeprecated = false;
  2681. size_t idx = 0;
  2682. QMenu *popup = new QMenu(QTStr("Add"), this);
  2683. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  2684. auto getActionAfter = [] (QMenu *menu, const QString &name)
  2685. {
  2686. QList<QAction*> actions = menu->actions();
  2687. for (QAction *menuAction : actions) {
  2688. if (menuAction->text().compare(name) >= 0)
  2689. return menuAction;
  2690. }
  2691. return (QAction*)nullptr;
  2692. };
  2693. auto addSource = [this, getActionAfter] (QMenu *popup,
  2694. const char *type, const char *name)
  2695. {
  2696. QString qname = QT_UTF8(name);
  2697. QAction *popupItem = new QAction(qname, this);
  2698. popupItem->setData(QT_UTF8(type));
  2699. connect(popupItem, SIGNAL(triggered(bool)),
  2700. this, SLOT(AddSourceFromAction()));
  2701. QAction *after = getActionAfter(popup, qname);
  2702. popup->insertAction(after, popupItem);
  2703. };
  2704. while (obs_enum_input_types(idx++, &type)) {
  2705. const char *name = obs_source_get_display_name(type);
  2706. uint32_t caps = obs_get_source_output_flags(type);
  2707. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  2708. addSource(popup, type, name);
  2709. } else {
  2710. addSource(deprecated, type, name);
  2711. foundDeprecated = true;
  2712. }
  2713. foundValues = true;
  2714. }
  2715. addSource(popup, "scene", Str("Basic.Scene"));
  2716. if (!foundDeprecated) {
  2717. delete deprecated;
  2718. deprecated = nullptr;
  2719. }
  2720. if (!foundValues) {
  2721. delete popup;
  2722. popup = nullptr;
  2723. } else if (foundDeprecated) {
  2724. popup->addMenu(deprecated);
  2725. }
  2726. return popup;
  2727. }
  2728. void OBSBasic::AddSourceFromAction()
  2729. {
  2730. QAction *action = qobject_cast<QAction*>(sender());
  2731. if (!action)
  2732. return;
  2733. AddSource(QT_TO_UTF8(action->data().toString()));
  2734. }
  2735. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  2736. {
  2737. if (!GetCurrentScene()) {
  2738. // Tell the user he needs a scene first (help beginners).
  2739. QMessageBox::information(this,
  2740. QTStr("Basic.Main.AddSourceHelp.Title"),
  2741. QTStr("Basic.Main.AddSourceHelp.Text"));
  2742. return;
  2743. }
  2744. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  2745. if (popup)
  2746. popup->exec(pos);
  2747. }
  2748. void OBSBasic::on_actionAddSource_triggered()
  2749. {
  2750. AddSourcePopupMenu(QCursor::pos());
  2751. }
  2752. void OBSBasic::on_actionRemoveSource_triggered()
  2753. {
  2754. vector<OBSSceneItem> items;
  2755. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  2756. {
  2757. vector<OBSSceneItem> &items =
  2758. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  2759. if (obs_sceneitem_selected(item))
  2760. items.emplace_back(item);
  2761. return true;
  2762. };
  2763. obs_scene_enum_items(GetCurrentScene(), func, &items);
  2764. if (!items.size())
  2765. return;
  2766. auto removeMultiple = [this] (size_t count)
  2767. {
  2768. QString text = QTStr("ConfirmRemove.TextMultiple")
  2769. .arg(QString::number(count));
  2770. QMessageBox remove_items(this);
  2771. remove_items.setText(text);
  2772. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  2773. QMessageBox::YesRole);
  2774. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  2775. remove_items.setIcon(QMessageBox::Question);
  2776. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2777. remove_items.exec();
  2778. return Yes == remove_items.clickedButton();
  2779. };
  2780. if (items.size() == 1) {
  2781. OBSSceneItem &item = items[0];
  2782. obs_source_t *source = obs_sceneitem_get_source(item);
  2783. if (source && QueryRemoveSource(source))
  2784. obs_sceneitem_remove(item);
  2785. } else {
  2786. if (removeMultiple(items.size())) {
  2787. for (auto &item : items)
  2788. obs_sceneitem_remove(item);
  2789. }
  2790. }
  2791. }
  2792. void OBSBasic::on_actionInteract_triggered()
  2793. {
  2794. OBSSceneItem item = GetCurrentSceneItem();
  2795. OBSSource source = obs_sceneitem_get_source(item);
  2796. if (source)
  2797. CreateInteractionWindow(source);
  2798. }
  2799. void OBSBasic::on_actionSourceProperties_triggered()
  2800. {
  2801. OBSSceneItem item = GetCurrentSceneItem();
  2802. OBSSource source = obs_sceneitem_get_source(item);
  2803. if (source)
  2804. CreatePropertiesWindow(source);
  2805. }
  2806. void OBSBasic::on_actionSourceUp_triggered()
  2807. {
  2808. OBSSceneItem item = GetCurrentSceneItem();
  2809. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  2810. }
  2811. void OBSBasic::on_actionSourceDown_triggered()
  2812. {
  2813. OBSSceneItem item = GetCurrentSceneItem();
  2814. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  2815. }
  2816. void OBSBasic::on_actionMoveUp_triggered()
  2817. {
  2818. OBSSceneItem item = GetCurrentSceneItem();
  2819. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  2820. }
  2821. void OBSBasic::on_actionMoveDown_triggered()
  2822. {
  2823. OBSSceneItem item = GetCurrentSceneItem();
  2824. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  2825. }
  2826. void OBSBasic::on_actionMoveToTop_triggered()
  2827. {
  2828. OBSSceneItem item = GetCurrentSceneItem();
  2829. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  2830. }
  2831. void OBSBasic::on_actionMoveToBottom_triggered()
  2832. {
  2833. OBSSceneItem item = GetCurrentSceneItem();
  2834. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  2835. }
  2836. static BPtr<char> ReadLogFile(const char *log)
  2837. {
  2838. char logDir[512];
  2839. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  2840. return nullptr;
  2841. string path = (char*)logDir;
  2842. path += "/";
  2843. path += log;
  2844. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  2845. if (!file)
  2846. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  2847. return file;
  2848. }
  2849. void OBSBasic::UploadLog(const char *file)
  2850. {
  2851. BPtr<char> fileString{ReadLogFile(file)};
  2852. if (!fileString)
  2853. return;
  2854. if (!*fileString)
  2855. return;
  2856. ui->menuLogFiles->setEnabled(false);
  2857. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  2858. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  2859. data_t content{obs_data_create(), data_deleter};
  2860. data_t files{obs_data_create(), data_deleter};
  2861. data_t request{obs_data_create(), data_deleter};
  2862. obs_data_set_string(content.get(), "content", fileString);
  2863. obs_data_set_obj(files.get(), file, content.get());
  2864. stringstream ss;
  2865. ss << "OBS " << App()->GetVersionString()
  2866. << " log file uploaded at " << CurrentDateTimeString();
  2867. obs_data_set_string(request.get(), "description", ss.str().c_str());
  2868. obs_data_set_bool(request.get(), "public", false);
  2869. obs_data_set_obj(request.get(), "files", files.get());
  2870. const char *json = obs_data_get_json(request.get());
  2871. if (!json) {
  2872. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  2873. return;
  2874. }
  2875. QBuffer *postData = new QBuffer();
  2876. postData->setData(json, (int) strlen(json));
  2877. if (logUploadThread) {
  2878. logUploadThread->wait();
  2879. delete logUploadThread;
  2880. }
  2881. RemoteTextThread *thread = new RemoteTextThread(
  2882. "https://api.github.com/gists",
  2883. "application/json", json);
  2884. logUploadThread = thread;
  2885. connect(thread, &RemoteTextThread::Result,
  2886. this, &OBSBasic::logUploadFinished);
  2887. logUploadThread->start();
  2888. }
  2889. void OBSBasic::on_actionShowLogs_triggered()
  2890. {
  2891. char logDir[512];
  2892. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  2893. return;
  2894. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  2895. QDesktopServices::openUrl(url);
  2896. }
  2897. void OBSBasic::on_actionUploadCurrentLog_triggered()
  2898. {
  2899. UploadLog(App()->GetCurrentLog());
  2900. }
  2901. void OBSBasic::on_actionUploadLastLog_triggered()
  2902. {
  2903. UploadLog(App()->GetLastLog());
  2904. }
  2905. void OBSBasic::on_actionViewCurrentLog_triggered()
  2906. {
  2907. char logDir[512];
  2908. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  2909. return;
  2910. const char* log = App()->GetCurrentLog();
  2911. string path = (char*)logDir;
  2912. path += "/";
  2913. path += log;
  2914. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  2915. QDesktopServices::openUrl(url);
  2916. }
  2917. void OBSBasic::on_actionCheckForUpdates_triggered()
  2918. {
  2919. CheckForUpdates();
  2920. }
  2921. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  2922. {
  2923. ui->menuLogFiles->setEnabled(true);
  2924. if (text.isEmpty()) {
  2925. QMessageBox::information(this,
  2926. QTStr("LogReturnDialog.ErrorUploadingLog"),
  2927. error);
  2928. return;
  2929. }
  2930. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  2931. QString logURL = obs_data_get_string(returnData, "html_url");
  2932. obs_data_release(returnData);
  2933. OBSLogReply logDialog(this, logURL);
  2934. logDialog.exec();
  2935. }
  2936. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  2937. obs_source_t *source, const string &name)
  2938. {
  2939. const char *prevName = obs_source_get_name(source);
  2940. if (name == prevName)
  2941. return;
  2942. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  2943. QListWidgetItem *listItem = listWidget->currentItem();
  2944. if (foundSource || name.empty()) {
  2945. listItem->setText(QT_UTF8(prevName));
  2946. if (foundSource) {
  2947. QMessageBox::information(parent,
  2948. QTStr("NameExists.Title"),
  2949. QTStr("NameExists.Text"));
  2950. } else if (name.empty()) {
  2951. QMessageBox::information(parent,
  2952. QTStr("NoNameEntered.Title"),
  2953. QTStr("NoNameEntered.Text"));
  2954. }
  2955. obs_source_release(foundSource);
  2956. } else {
  2957. listItem->setText(QT_UTF8(name.c_str()));
  2958. obs_source_set_name(source, name.c_str());
  2959. }
  2960. }
  2961. void OBSBasic::SceneNameEdited(QWidget *editor,
  2962. QAbstractItemDelegate::EndEditHint endHint)
  2963. {
  2964. OBSScene scene = GetCurrentScene();
  2965. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  2966. string text = QT_TO_UTF8(edit->text().trimmed());
  2967. if (!scene)
  2968. return;
  2969. obs_source_t *source = obs_scene_get_source(scene);
  2970. RenameListItem(this, ui->scenes, source, text);
  2971. if (api)
  2972. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2973. UNUSED_PARAMETER(endHint);
  2974. }
  2975. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  2976. QAbstractItemDelegate::EndEditHint endHint)
  2977. {
  2978. OBSSceneItem item = GetCurrentSceneItem();
  2979. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  2980. string text = QT_TO_UTF8(edit->text().trimmed());
  2981. if (!item)
  2982. return;
  2983. obs_source_t *source = obs_sceneitem_get_source(item);
  2984. RenameListItem(this, ui->sources, source, text);
  2985. QListWidgetItem *listItem = ui->sources->currentItem();
  2986. listItem->setText(QString());
  2987. SetupVisibilityItem(ui->sources, listItem, item);
  2988. UNUSED_PARAMETER(endHint);
  2989. }
  2990. void OBSBasic::OpenFilters()
  2991. {
  2992. OBSSceneItem item = GetCurrentSceneItem();
  2993. OBSSource source = obs_sceneitem_get_source(item);
  2994. CreateFiltersWindow(source);
  2995. }
  2996. void OBSBasic::OpenSceneFilters()
  2997. {
  2998. OBSScene scene = GetCurrentScene();
  2999. OBSSource source = obs_scene_get_source(scene);
  3000. CreateFiltersWindow(source);
  3001. }
  3002. #define RECORDING_START \
  3003. "==== Recording Start ==============================================="
  3004. #define RECORDING_STOP \
  3005. "==== Recording Stop ================================================"
  3006. #define REPLAY_BUFFER_START \
  3007. "==== Replay Buffer Start ==========================================="
  3008. #define REPLAY_BUFFER_STOP \
  3009. "==== Replay Buffer Stop ============================================"
  3010. #define STREAMING_START \
  3011. "==== Streaming Start ==============================================="
  3012. #define STREAMING_STOP \
  3013. "==== Streaming Stop ================================================"
  3014. void OBSBasic::StartStreaming()
  3015. {
  3016. if (outputHandler->StreamingActive())
  3017. return;
  3018. if (api)
  3019. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3020. SaveProject();
  3021. ui->streamButton->setEnabled(false);
  3022. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3023. if (sysTrayStream) {
  3024. sysTrayStream->setEnabled(false);
  3025. sysTrayStream->setText(ui->streamButton->text());
  3026. }
  3027. if (!outputHandler->StartStreaming(service)) {
  3028. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3029. ui->streamButton->setEnabled(true);
  3030. if (sysTrayStream) {
  3031. sysTrayStream->setText(ui->streamButton->text());
  3032. sysTrayStream->setEnabled(true);
  3033. }
  3034. }
  3035. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3036. "BasicWindow", "RecordWhenStreaming");
  3037. if (recordWhenStreaming)
  3038. StartRecording();
  3039. }
  3040. #ifdef _WIN32
  3041. static inline void UpdateProcessPriority()
  3042. {
  3043. const char *priority = config_get_string(App()->GlobalConfig(),
  3044. "General", "ProcessPriority");
  3045. if (priority && strcmp(priority, "Normal") != 0)
  3046. SetProcessPriority(priority);
  3047. }
  3048. static inline void ClearProcessPriority()
  3049. {
  3050. const char *priority = config_get_string(App()->GlobalConfig(),
  3051. "General", "ProcessPriority");
  3052. if (priority && strcmp(priority, "Normal") != 0)
  3053. SetProcessPriority("Normal");
  3054. }
  3055. #else
  3056. #define UpdateProcessPriority() do {} while(false)
  3057. #define ClearProcessPriority() do {} while(false)
  3058. #endif
  3059. inline void OBSBasic::OnActivate()
  3060. {
  3061. if (ui->profileMenu->isEnabled()) {
  3062. ui->profileMenu->setEnabled(false);
  3063. App()->IncrementSleepInhibition();
  3064. UpdateProcessPriority();
  3065. if (trayIcon)
  3066. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3067. }
  3068. }
  3069. inline void OBSBasic::OnDeactivate()
  3070. {
  3071. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3072. ui->profileMenu->setEnabled(true);
  3073. App()->DecrementSleepInhibition();
  3074. ClearProcessPriority();
  3075. if (trayIcon)
  3076. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3077. }
  3078. }
  3079. void OBSBasic::StopStreaming()
  3080. {
  3081. SaveProject();
  3082. if (outputHandler->StreamingActive())
  3083. outputHandler->StopStreaming(streamingStopping);
  3084. OnDeactivate();
  3085. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3086. "BasicWindow", "RecordWhenStreaming");
  3087. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3088. "BasicWindow", "KeepRecordingWhenStreamStops");
  3089. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3090. StopRecording();
  3091. }
  3092. void OBSBasic::ForceStopStreaming()
  3093. {
  3094. SaveProject();
  3095. if (outputHandler->StreamingActive())
  3096. outputHandler->StopStreaming(true);
  3097. OnDeactivate();
  3098. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3099. "BasicWindow", "RecordWhenStreaming");
  3100. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3101. "BasicWindow", "KeepRecordingWhenStreamStops");
  3102. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3103. StopRecording();
  3104. }
  3105. void OBSBasic::StreamDelayStarting(int sec)
  3106. {
  3107. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3108. ui->streamButton->setEnabled(true);
  3109. if (sysTrayStream) {
  3110. sysTrayStream->setText(ui->streamButton->text());
  3111. sysTrayStream->setEnabled(true);
  3112. }
  3113. if (!startStreamMenu.isNull())
  3114. startStreamMenu->deleteLater();
  3115. startStreamMenu = new QMenu();
  3116. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3117. this, SLOT(StopStreaming()));
  3118. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3119. this, SLOT(ForceStopStreaming()));
  3120. ui->streamButton->setMenu(startStreamMenu);
  3121. ui->statusbar->StreamDelayStarting(sec);
  3122. OnActivate();
  3123. }
  3124. void OBSBasic::StreamDelayStopping(int sec)
  3125. {
  3126. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3127. ui->streamButton->setEnabled(true);
  3128. if (sysTrayStream) {
  3129. sysTrayStream->setText(ui->streamButton->text());
  3130. sysTrayStream->setEnabled(true);
  3131. }
  3132. if (!startStreamMenu.isNull())
  3133. startStreamMenu->deleteLater();
  3134. startStreamMenu = new QMenu();
  3135. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3136. this, SLOT(StartStreaming()));
  3137. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3138. this, SLOT(ForceStopStreaming()));
  3139. ui->streamButton->setMenu(startStreamMenu);
  3140. ui->statusbar->StreamDelayStopping(sec);
  3141. }
  3142. void OBSBasic::StreamingStart()
  3143. {
  3144. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3145. ui->streamButton->setEnabled(true);
  3146. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3147. if (sysTrayStream) {
  3148. sysTrayStream->setText(ui->streamButton->text());
  3149. sysTrayStream->setEnabled(true);
  3150. }
  3151. if (api)
  3152. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3153. OnActivate();
  3154. blog(LOG_INFO, STREAMING_START);
  3155. }
  3156. void OBSBasic::StreamStopping()
  3157. {
  3158. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3159. if (sysTrayStream)
  3160. sysTrayStream->setText(ui->streamButton->text());
  3161. streamingStopping = true;
  3162. if (api)
  3163. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3164. }
  3165. void OBSBasic::StreamingStop(int code)
  3166. {
  3167. const char *errorMessage;
  3168. switch (code) {
  3169. case OBS_OUTPUT_BAD_PATH:
  3170. errorMessage = Str("Output.ConnectFail.BadPath");
  3171. break;
  3172. case OBS_OUTPUT_CONNECT_FAILED:
  3173. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  3174. break;
  3175. case OBS_OUTPUT_INVALID_STREAM:
  3176. errorMessage = Str("Output.ConnectFail.InvalidStream");
  3177. break;
  3178. default:
  3179. case OBS_OUTPUT_ERROR:
  3180. errorMessage = Str("Output.ConnectFail.Error");
  3181. break;
  3182. case OBS_OUTPUT_DISCONNECTED:
  3183. /* doesn't happen if output is set to reconnect. note that
  3184. * reconnects are handled in the output, not in the UI */
  3185. errorMessage = Str("Output.ConnectFail.Disconnected");
  3186. }
  3187. ui->statusbar->StreamStopped();
  3188. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3189. ui->streamButton->setEnabled(true);
  3190. if (sysTrayStream) {
  3191. sysTrayStream->setText(ui->streamButton->text());
  3192. sysTrayStream->setEnabled(true);
  3193. }
  3194. streamingStopping = false;
  3195. if (api)
  3196. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3197. OnDeactivate();
  3198. blog(LOG_INFO, STREAMING_STOP);
  3199. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3200. QMessageBox::information(this,
  3201. QTStr("Output.ConnectFail.Title"),
  3202. QT_UTF8(errorMessage));
  3203. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3204. SysTrayNotify(QT_UTF8(errorMessage), QSystemTrayIcon::Warning);
  3205. }
  3206. if (!startStreamMenu.isNull()) {
  3207. ui->streamButton->setMenu(nullptr);
  3208. startStreamMenu->deleteLater();
  3209. startStreamMenu = nullptr;
  3210. }
  3211. }
  3212. void OBSBasic::StartRecording()
  3213. {
  3214. if (outputHandler->RecordingActive())
  3215. return;
  3216. if (api)
  3217. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3218. SaveProject();
  3219. outputHandler->StartRecording();
  3220. }
  3221. void OBSBasic::RecordStopping()
  3222. {
  3223. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3224. if (sysTrayRecord)
  3225. sysTrayRecord->setText(ui->recordButton->text());
  3226. recordingStopping = true;
  3227. if (api)
  3228. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3229. }
  3230. void OBSBasic::StopRecording()
  3231. {
  3232. SaveProject();
  3233. if (outputHandler->RecordingActive())
  3234. outputHandler->StopRecording(recordingStopping);
  3235. OnDeactivate();
  3236. }
  3237. void OBSBasic::RecordingStart()
  3238. {
  3239. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3240. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3241. if (sysTrayRecord)
  3242. sysTrayRecord->setText(ui->recordButton->text());
  3243. recordingStopping = false;
  3244. if (api)
  3245. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3246. OnActivate();
  3247. blog(LOG_INFO, RECORDING_START);
  3248. }
  3249. void OBSBasic::RecordingStop(int code)
  3250. {
  3251. ui->statusbar->RecordingStopped();
  3252. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3253. if (sysTrayRecord)
  3254. sysTrayRecord->setText(ui->recordButton->text());
  3255. blog(LOG_INFO, RECORDING_STOP);
  3256. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3257. QMessageBox::information(this,
  3258. QTStr("Output.RecordFail.Title"),
  3259. QTStr("Output.RecordFail.Unsupported"));
  3260. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3261. QMessageBox::information(this,
  3262. QTStr("Output.RecordNoSpace.Title"),
  3263. QTStr("Output.RecordNoSpace.Msg"));
  3264. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3265. QMessageBox::information(this,
  3266. QTStr("Output.RecordError.Title"),
  3267. QTStr("Output.RecordError.Msg"));
  3268. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3269. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3270. QSystemTrayIcon::Warning);
  3271. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3272. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3273. QSystemTrayIcon::Warning);
  3274. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3275. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3276. QSystemTrayIcon::Warning);
  3277. }
  3278. if (api)
  3279. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3280. OnDeactivate();
  3281. }
  3282. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3283. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3284. void OBSBasic::StartReplayBuffer()
  3285. {
  3286. if (!outputHandler || !outputHandler->replayBuffer)
  3287. return;
  3288. if (outputHandler->ReplayBufferActive())
  3289. return;
  3290. obs_output_t *output = outputHandler->replayBuffer;
  3291. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3292. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3293. "ReplayBuffer.Save");
  3294. size_t count = obs_data_array_count(bindings);
  3295. obs_data_array_release(bindings);
  3296. obs_data_release(hotkeys);
  3297. if (!count) {
  3298. QMessageBox::information(this,
  3299. RP_NO_HOTKEY_TITLE,
  3300. RP_NO_HOTKEY_TEXT);
  3301. return;
  3302. }
  3303. if (api)
  3304. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3305. SaveProject();
  3306. outputHandler->StartReplayBuffer();
  3307. }
  3308. void OBSBasic::ReplayBufferStopping()
  3309. {
  3310. if (!outputHandler || !outputHandler->replayBuffer)
  3311. return;
  3312. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3313. if (sysTrayReplayBuffer)
  3314. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3315. replayBufferStopping = true;
  3316. if (api)
  3317. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3318. }
  3319. void OBSBasic::StopReplayBuffer()
  3320. {
  3321. if (!outputHandler || !outputHandler->replayBuffer)
  3322. return;
  3323. SaveProject();
  3324. if (outputHandler->ReplayBufferActive())
  3325. outputHandler->StopReplayBuffer(replayBufferStopping);
  3326. OnDeactivate();
  3327. }
  3328. void OBSBasic::ReplayBufferStart()
  3329. {
  3330. if (!outputHandler || !outputHandler->replayBuffer)
  3331. return;
  3332. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3333. if (sysTrayReplayBuffer)
  3334. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3335. replayBufferStopping = false;
  3336. if (api)
  3337. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3338. OnActivate();
  3339. blog(LOG_INFO, REPLAY_BUFFER_START);
  3340. }
  3341. void OBSBasic::ReplayBufferStop(int code)
  3342. {
  3343. if (!outputHandler || !outputHandler->replayBuffer)
  3344. return;
  3345. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3346. if (sysTrayReplayBuffer)
  3347. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3348. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3349. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3350. QMessageBox::information(this,
  3351. QTStr("Output.RecordFail.Title"),
  3352. QTStr("Output.RecordFail.Unsupported"));
  3353. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3354. QMessageBox::information(this,
  3355. QTStr("Output.RecordNoSpace.Title"),
  3356. QTStr("Output.RecordNoSpace.Msg"));
  3357. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3358. QMessageBox::information(this,
  3359. QTStr("Output.RecordError.Title"),
  3360. QTStr("Output.RecordError.Msg"));
  3361. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3362. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3363. QSystemTrayIcon::Warning);
  3364. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3365. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3366. QSystemTrayIcon::Warning);
  3367. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3368. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3369. QSystemTrayIcon::Warning);
  3370. }
  3371. if (api)
  3372. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3373. OnDeactivate();
  3374. }
  3375. void OBSBasic::on_streamButton_clicked()
  3376. {
  3377. if (outputHandler->StreamingActive()) {
  3378. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3379. "WarnBeforeStoppingStream");
  3380. if (confirm && isVisible()) {
  3381. QMessageBox::StandardButton button =
  3382. QMessageBox::question(this,
  3383. QTStr("ConfirmStop.Title"),
  3384. QTStr("ConfirmStop.Text"));
  3385. if (button == QMessageBox::No)
  3386. return;
  3387. }
  3388. StopStreaming();
  3389. } else {
  3390. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3391. "WarnBeforeStartingStream");
  3392. if (confirm && isVisible()) {
  3393. QMessageBox::StandardButton button =
  3394. QMessageBox::question(this,
  3395. QTStr("ConfirmStart.Title"),
  3396. QTStr("ConfirmStart.Text"));
  3397. if (button == QMessageBox::No)
  3398. return;
  3399. }
  3400. StartStreaming();
  3401. }
  3402. }
  3403. void OBSBasic::on_recordButton_clicked()
  3404. {
  3405. if (outputHandler->RecordingActive())
  3406. StopRecording();
  3407. else
  3408. StartRecording();
  3409. }
  3410. void OBSBasic::on_settingsButton_clicked()
  3411. {
  3412. on_action_Settings_triggered();
  3413. }
  3414. void OBSBasic::on_actionWebsite_triggered()
  3415. {
  3416. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3417. QDesktopServices::openUrl(url);
  3418. }
  3419. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3420. {
  3421. char path[512];
  3422. int ret = GetConfigPath(path, 512, "obs-studio");
  3423. if (ret <= 0)
  3424. return;
  3425. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3426. }
  3427. void OBSBasic::on_actionShowProfileFolder_triggered()
  3428. {
  3429. char path[512];
  3430. int ret = GetProfilePath(path, 512, "");
  3431. if (ret <= 0)
  3432. return;
  3433. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3434. }
  3435. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3436. {
  3437. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3438. QListWidgetItem *topItem = nullptr;
  3439. if (selectedItems.size() != 0)
  3440. topItem = selectedItems[0];
  3441. return topItem;
  3442. }
  3443. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3444. {
  3445. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3446. UNUSED_PARAMETER(pos);
  3447. }
  3448. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3449. const QPoint &pos)
  3450. {
  3451. QMenu popup(this);
  3452. QPointer<QMenu> previewProjector;
  3453. QAction *action = popup.addAction(
  3454. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3455. this, SLOT(TogglePreview()));
  3456. action->setCheckable(true);
  3457. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3458. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3459. AddProjectorMenuMonitors(previewProjector, this,
  3460. SLOT(OpenPreviewProjector()));
  3461. popup.addMenu(previewProjector);
  3462. popup.exec(QCursor::pos());
  3463. UNUSED_PARAMETER(pos);
  3464. }
  3465. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3466. {
  3467. CloseDialogs();
  3468. /* Make sure all dialogs are safely and successfully closed before
  3469. * switching the always on top mode due to the fact that windows all
  3470. * have to be recreated, so queue the actual toggle to happen after
  3471. * all events related to closing the dialogs have finished */
  3472. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3473. Qt::QueuedConnection);
  3474. }
  3475. void OBSBasic::ToggleAlwaysOnTop()
  3476. {
  3477. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3478. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3479. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3480. show();
  3481. }
  3482. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3483. {
  3484. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3485. if (strcmp(val, "10") == 0) {
  3486. num = 10;
  3487. den = 1;
  3488. } else if (strcmp(val, "20") == 0) {
  3489. num = 20;
  3490. den = 1;
  3491. } else if (strcmp(val, "25") == 0) {
  3492. num = 25;
  3493. den = 1;
  3494. } else if (strcmp(val, "29.97") == 0) {
  3495. num = 30000;
  3496. den = 1001;
  3497. } else if (strcmp(val, "48") == 0) {
  3498. num = 48;
  3499. den = 1;
  3500. } else if (strcmp(val, "59.94") == 0) {
  3501. num = 60000;
  3502. den = 1001;
  3503. } else if (strcmp(val, "60") == 0) {
  3504. num = 60;
  3505. den = 1;
  3506. } else {
  3507. num = 30;
  3508. den = 1;
  3509. }
  3510. }
  3511. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3512. {
  3513. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3514. den = 1;
  3515. }
  3516. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3517. {
  3518. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3519. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3520. }
  3521. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3522. {
  3523. num = 1000000000;
  3524. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3525. }
  3526. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3527. {
  3528. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3529. if (type == 1) //"Integer"
  3530. GetFPSInteger(num, den);
  3531. else if (type == 2) //"Fraction"
  3532. GetFPSFraction(num, den);
  3533. else if (false) //"Nanoseconds", currently not implemented
  3534. GetFPSNanoseconds(num, den);
  3535. else
  3536. GetFPSCommon(num, den);
  3537. }
  3538. config_t *OBSBasic::Config() const
  3539. {
  3540. return basicConfig;
  3541. }
  3542. void OBSBasic::on_actionEditTransform_triggered()
  3543. {
  3544. if (transformWindow)
  3545. transformWindow->close();
  3546. transformWindow = new OBSBasicTransform(this);
  3547. transformWindow->show();
  3548. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3549. }
  3550. static obs_transform_info copiedTransformInfo;
  3551. static obs_sceneitem_crop copiedCropInfo;
  3552. void OBSBasic::on_actionCopyTransform_triggered()
  3553. {
  3554. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3555. {
  3556. if (!obs_sceneitem_selected(item))
  3557. return true;
  3558. obs_sceneitem_defer_update_begin(item);
  3559. obs_sceneitem_get_info(item, &copiedTransformInfo);
  3560. obs_sceneitem_get_crop(item, &copiedCropInfo);
  3561. obs_sceneitem_defer_update_end(item);
  3562. UNUSED_PARAMETER(scene);
  3563. UNUSED_PARAMETER(param);
  3564. return true;
  3565. };
  3566. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3567. ui->actionPasteTransform->setEnabled(true);
  3568. }
  3569. void OBSBasic::on_actionPasteTransform_triggered()
  3570. {
  3571. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3572. {
  3573. if (!obs_sceneitem_selected(item))
  3574. return true;
  3575. obs_sceneitem_defer_update_begin(item);
  3576. obs_sceneitem_set_info(item, &copiedTransformInfo);
  3577. obs_sceneitem_set_crop(item, &copiedCropInfo);
  3578. obs_sceneitem_defer_update_end(item);
  3579. UNUSED_PARAMETER(scene);
  3580. UNUSED_PARAMETER(param);
  3581. return true;
  3582. };
  3583. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3584. }
  3585. void OBSBasic::on_actionResetTransform_triggered()
  3586. {
  3587. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3588. {
  3589. if (!obs_sceneitem_selected(item))
  3590. return true;
  3591. obs_sceneitem_defer_update_begin(item);
  3592. obs_transform_info info;
  3593. vec2_set(&info.pos, 0.0f, 0.0f);
  3594. vec2_set(&info.scale, 1.0f, 1.0f);
  3595. info.rot = 0.0f;
  3596. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  3597. info.bounds_type = OBS_BOUNDS_NONE;
  3598. info.bounds_alignment = OBS_ALIGN_CENTER;
  3599. vec2_set(&info.bounds, 0.0f, 0.0f);
  3600. obs_sceneitem_set_info(item, &info);
  3601. obs_sceneitem_crop crop = {};
  3602. obs_sceneitem_set_crop(item, &crop);
  3603. obs_sceneitem_defer_update_end(item);
  3604. UNUSED_PARAMETER(scene);
  3605. UNUSED_PARAMETER(param);
  3606. return true;
  3607. };
  3608. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3609. }
  3610. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  3611. {
  3612. matrix4 boxTransform;
  3613. obs_sceneitem_get_box_transform(item, &boxTransform);
  3614. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  3615. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  3616. auto GetMinPos = [&] (float x, float y)
  3617. {
  3618. vec3 pos;
  3619. vec3_set(&pos, x, y, 0.0f);
  3620. vec3_transform(&pos, &pos, &boxTransform);
  3621. vec3_min(&tl, &tl, &pos);
  3622. vec3_max(&br, &br, &pos);
  3623. };
  3624. GetMinPos(0.0f, 0.0f);
  3625. GetMinPos(1.0f, 0.0f);
  3626. GetMinPos(0.0f, 1.0f);
  3627. GetMinPos(1.0f, 1.0f);
  3628. }
  3629. static vec3 GetItemTL(obs_sceneitem_t *item)
  3630. {
  3631. vec3 tl, br;
  3632. GetItemBox(item, tl, br);
  3633. return tl;
  3634. }
  3635. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  3636. {
  3637. vec3 newTL;
  3638. vec2 pos;
  3639. obs_sceneitem_get_pos(item, &pos);
  3640. newTL = GetItemTL(item);
  3641. pos.x += tl.x - newTL.x;
  3642. pos.y += tl.y - newTL.y;
  3643. obs_sceneitem_set_pos(item, &pos);
  3644. }
  3645. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  3646. void *param)
  3647. {
  3648. if (!obs_sceneitem_selected(item))
  3649. return true;
  3650. float rot = *reinterpret_cast<float*>(param);
  3651. vec3 tl = GetItemTL(item);
  3652. rot += obs_sceneitem_get_rot(item);
  3653. if (rot >= 360.0f) rot -= 360.0f;
  3654. else if (rot <= -360.0f) rot += 360.0f;
  3655. obs_sceneitem_set_rot(item, rot);
  3656. SetItemTL(item, tl);
  3657. UNUSED_PARAMETER(scene);
  3658. UNUSED_PARAMETER(param);
  3659. return true;
  3660. };
  3661. void OBSBasic::on_actionRotate90CW_triggered()
  3662. {
  3663. float f90CW = 90.0f;
  3664. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  3665. }
  3666. void OBSBasic::on_actionRotate90CCW_triggered()
  3667. {
  3668. float f90CCW = -90.0f;
  3669. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  3670. }
  3671. void OBSBasic::on_actionRotate180_triggered()
  3672. {
  3673. float f180 = 180.0f;
  3674. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  3675. }
  3676. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  3677. void *param)
  3678. {
  3679. vec2 &mul = *reinterpret_cast<vec2*>(param);
  3680. if (!obs_sceneitem_selected(item))
  3681. return true;
  3682. vec3 tl = GetItemTL(item);
  3683. vec2 scale;
  3684. obs_sceneitem_get_scale(item, &scale);
  3685. vec2_mul(&scale, &scale, &mul);
  3686. obs_sceneitem_set_scale(item, &scale);
  3687. SetItemTL(item, tl);
  3688. UNUSED_PARAMETER(scene);
  3689. return true;
  3690. }
  3691. void OBSBasic::on_actionFlipHorizontal_triggered()
  3692. {
  3693. vec2 scale;
  3694. vec2_set(&scale, -1.0f, 1.0f);
  3695. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  3696. &scale);
  3697. }
  3698. void OBSBasic::on_actionFlipVertical_triggered()
  3699. {
  3700. vec2 scale;
  3701. vec2_set(&scale, 1.0f, -1.0f);
  3702. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  3703. &scale);
  3704. }
  3705. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  3706. void *param)
  3707. {
  3708. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  3709. if (!obs_sceneitem_selected(item))
  3710. return true;
  3711. obs_video_info ovi;
  3712. obs_get_video_info(&ovi);
  3713. obs_transform_info itemInfo;
  3714. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  3715. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  3716. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  3717. itemInfo.rot = 0.0f;
  3718. vec2_set(&itemInfo.bounds,
  3719. float(ovi.base_width), float(ovi.base_height));
  3720. itemInfo.bounds_type = boundsType;
  3721. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  3722. obs_sceneitem_set_info(item, &itemInfo);
  3723. UNUSED_PARAMETER(scene);
  3724. return true;
  3725. }
  3726. void OBSBasic::on_actionFitToScreen_triggered()
  3727. {
  3728. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  3729. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  3730. &boundsType);
  3731. }
  3732. void OBSBasic::on_actionStretchToScreen_triggered()
  3733. {
  3734. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  3735. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  3736. &boundsType);
  3737. }
  3738. void OBSBasic::on_actionCenterToScreen_triggered()
  3739. {
  3740. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3741. {
  3742. vec3 tl, br, itemCenter, screenCenter, offset;
  3743. obs_video_info ovi;
  3744. if (!obs_sceneitem_selected(item))
  3745. return true;
  3746. obs_get_video_info(&ovi);
  3747. vec3_set(&screenCenter, float(ovi.base_width),
  3748. float(ovi.base_height), 0.0f);
  3749. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  3750. GetItemBox(item, tl, br);
  3751. vec3_sub(&itemCenter, &br, &tl);
  3752. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  3753. vec3_add(&itemCenter, &itemCenter, &tl);
  3754. vec3_sub(&offset, &screenCenter, &itemCenter);
  3755. vec3_add(&tl, &tl, &offset);
  3756. SetItemTL(item, tl);
  3757. UNUSED_PARAMETER(scene);
  3758. UNUSED_PARAMETER(param);
  3759. return true;
  3760. };
  3761. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3762. }
  3763. void OBSBasic::EnablePreviewDisplay(bool enable)
  3764. {
  3765. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  3766. ui->preview->setVisible(enable);
  3767. ui->previewDisabledLabel->setVisible(!enable);
  3768. }
  3769. void OBSBasic::TogglePreview()
  3770. {
  3771. previewEnabled = !previewEnabled;
  3772. EnablePreviewDisplay(previewEnabled);
  3773. }
  3774. void OBSBasic::Nudge(int dist, MoveDir dir)
  3775. {
  3776. if (ui->preview->Locked())
  3777. return;
  3778. struct MoveInfo {
  3779. float dist;
  3780. MoveDir dir;
  3781. } info = {(float)dist, dir};
  3782. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  3783. {
  3784. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  3785. struct vec2 dir;
  3786. struct vec2 pos;
  3787. vec2_set(&dir, 0.0f, 0.0f);
  3788. if (!obs_sceneitem_selected(item))
  3789. return true;
  3790. switch (info->dir) {
  3791. case MoveDir::Up: dir.y = -info->dist; break;
  3792. case MoveDir::Down: dir.y = info->dist; break;
  3793. case MoveDir::Left: dir.x = -info->dist; break;
  3794. case MoveDir::Right: dir.x = info->dist; break;
  3795. }
  3796. obs_sceneitem_get_pos(item, &pos);
  3797. vec2_add(&pos, &pos, &dir);
  3798. obs_sceneitem_set_pos(item, &pos);
  3799. return true;
  3800. };
  3801. obs_scene_enum_items(GetCurrentScene(), func, &info);
  3802. }
  3803. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  3804. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  3805. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  3806. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  3807. void OBSBasic::OpenProjector(obs_source_t *source, int monitor)
  3808. {
  3809. /* seriously? 10 monitors? */
  3810. if (monitor > 9)
  3811. return;
  3812. delete projectors[monitor];
  3813. projectors[monitor].clear();
  3814. OBSProjector *projector = new OBSProjector(nullptr, source);
  3815. projector->Init(monitor);
  3816. projectors[monitor] = projector;
  3817. }
  3818. void OBSBasic::OpenPreviewProjector()
  3819. {
  3820. int monitor = sender()->property("monitor").toInt();
  3821. OpenProjector(nullptr, monitor);
  3822. }
  3823. void OBSBasic::OpenSourceProjector()
  3824. {
  3825. int monitor = sender()->property("monitor").toInt();
  3826. OBSSceneItem item = GetCurrentSceneItem();
  3827. if (!item)
  3828. return;
  3829. OpenProjector(obs_sceneitem_get_source(item), monitor);
  3830. }
  3831. void OBSBasic::OpenSceneProjector()
  3832. {
  3833. int monitor = sender()->property("monitor").toInt();
  3834. OBSScene scene = GetCurrentScene();
  3835. if (!scene)
  3836. return;
  3837. OpenProjector(obs_scene_get_source(scene), monitor);
  3838. }
  3839. void OBSBasic::UpdateTitleBar()
  3840. {
  3841. stringstream name;
  3842. const char *profile = config_get_string(App()->GlobalConfig(),
  3843. "Basic", "Profile");
  3844. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  3845. "Basic", "SceneCollection");
  3846. name << "OBS ";
  3847. if (previewProgramMode)
  3848. name << "Studio ";
  3849. name << App()->GetVersionString();
  3850. if (App()->IsPortableMode())
  3851. name << " - Portable Mode";
  3852. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  3853. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  3854. setWindowTitle(QT_UTF8(name.str().c_str()));
  3855. }
  3856. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  3857. {
  3858. char profiles_path[512];
  3859. const char *profile = config_get_string(App()->GlobalConfig(),
  3860. "Basic", "ProfileDir");
  3861. int ret;
  3862. if (!profile)
  3863. return -1;
  3864. if (!path)
  3865. return -1;
  3866. if (!file)
  3867. file = "";
  3868. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  3869. if (ret <= 0)
  3870. return ret;
  3871. if (!*file)
  3872. return snprintf(path, size, "%s/%s", profiles_path, profile);
  3873. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  3874. }
  3875. void OBSBasic::on_toggleSceneTransitions_toggled(bool visible)
  3876. {
  3877. ui->sceneTransitionsLabel->setVisible(visible);
  3878. ui->transitionsContainer->setVisible(visible);
  3879. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  3880. "ShowTransitions", visible);
  3881. }
  3882. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  3883. {
  3884. ui->sourcesToolbar->setVisible(visible);
  3885. ui->scenesToolbar->setVisible(visible);
  3886. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  3887. "ShowListboxToolbars", visible);
  3888. }
  3889. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  3890. {
  3891. ui->statusbar->setVisible(visible);
  3892. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  3893. "ShowStatusBar", visible);
  3894. }
  3895. void OBSBasic::on_actionLockPreview_triggered()
  3896. {
  3897. ui->preview->ToggleLocked();
  3898. ui->actionLockPreview->setChecked(ui->preview->Locked());
  3899. }
  3900. void OBSBasic::on_scalingMenu_aboutToShow()
  3901. {
  3902. obs_video_info ovi;
  3903. obs_get_video_info(&ovi);
  3904. QAction *action = ui->actionScaleCanvas;
  3905. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  3906. text = text.arg(QString::number(ovi.base_width),
  3907. QString::number(ovi.base_height));
  3908. action->setText(text);
  3909. action = ui->actionScaleOutput;
  3910. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  3911. text = text.arg(QString::number(ovi.output_width),
  3912. QString::number(ovi.output_height));
  3913. action->setText(text);
  3914. UpdatePreviewScalingMenu();
  3915. }
  3916. void OBSBasic::on_actionScaleWindow_triggered()
  3917. {
  3918. ui->preview->SetScaling(ScalingMode::Window);
  3919. ui->preview->ResetScrollingOffset();
  3920. emit ui->preview->DisplayResized();
  3921. }
  3922. void OBSBasic::on_actionScaleCanvas_triggered()
  3923. {
  3924. ui->preview->SetScaling(ScalingMode::Canvas);
  3925. emit ui->preview->DisplayResized();
  3926. }
  3927. void OBSBasic::on_actionScaleOutput_triggered()
  3928. {
  3929. ui->preview->SetScaling(ScalingMode::Output);
  3930. emit ui->preview->DisplayResized();
  3931. }
  3932. void OBSBasic::SetShowing(bool showing)
  3933. {
  3934. if (!showing && isVisible()) {
  3935. config_set_string(App()->GlobalConfig(),
  3936. "BasicWindow", "geometry",
  3937. saveGeometry().toBase64().constData());
  3938. /* hide all visible child dialogs */
  3939. visDlgPositions.clear();
  3940. if (!visDialogs.isEmpty()) {
  3941. for (QDialog *dlg : visDialogs) {
  3942. visDlgPositions.append(dlg->pos());
  3943. dlg->hide();
  3944. }
  3945. }
  3946. if (showHide)
  3947. showHide->setText(QTStr("Basic.SystemTray.Show"));
  3948. QTimer::singleShot(250, this, SLOT(hide()));
  3949. if (previewEnabled)
  3950. EnablePreviewDisplay(false);
  3951. setVisible(false);
  3952. } else if (showing && !isVisible()) {
  3953. if (showHide)
  3954. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  3955. QTimer::singleShot(250, this, SLOT(show()));
  3956. if (previewEnabled)
  3957. EnablePreviewDisplay(true);
  3958. setVisible(true);
  3959. /* show all child dialogs that was visible earlier */
  3960. if (!visDialogs.isEmpty()) {
  3961. for (int i = 0; i < visDialogs.size(); ++i) {
  3962. QDialog *dlg = visDialogs[i];
  3963. dlg->move(visDlgPositions[i]);
  3964. dlg->show();
  3965. }
  3966. }
  3967. /* Unminimize window if it was hidden to tray instead of task
  3968. * bar. */
  3969. if (sysTrayMinimizeToTray()) {
  3970. Qt::WindowStates state;
  3971. state = windowState() & ~Qt::WindowMinimized;
  3972. state |= Qt::WindowActive;
  3973. setWindowState(state);
  3974. }
  3975. }
  3976. }
  3977. void OBSBasic::ToggleShowHide()
  3978. {
  3979. bool showing = isVisible();
  3980. if (showing) {
  3981. /* check for modal dialogs */
  3982. EnumDialogs();
  3983. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  3984. return;
  3985. }
  3986. SetShowing(!showing);
  3987. }
  3988. void OBSBasic::SystemTrayInit()
  3989. {
  3990. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  3991. this);
  3992. trayIcon->setToolTip("OBS Studio");
  3993. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  3994. trayIcon);
  3995. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  3996. trayIcon);
  3997. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  3998. trayIcon);
  3999. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4000. trayIcon);
  4001. exit = new QAction(QTStr("Exit"),
  4002. trayIcon);
  4003. if (outputHandler && !outputHandler->replayBuffer)
  4004. sysTrayReplayBuffer->setEnabled(false);
  4005. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4006. this,
  4007. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4008. connect(showHide, SIGNAL(triggered()),
  4009. this, SLOT(ToggleShowHide()));
  4010. connect(sysTrayStream, SIGNAL(triggered()),
  4011. this, SLOT(on_streamButton_clicked()));
  4012. connect(sysTrayRecord, SIGNAL(triggered()),
  4013. this, SLOT(on_recordButton_clicked()));
  4014. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4015. this, &OBSBasic::ReplayBufferClicked);
  4016. connect(exit, SIGNAL(triggered()),
  4017. this, SLOT(close()));
  4018. trayMenu = new QMenu;
  4019. trayMenu->addAction(showHide);
  4020. trayMenu->addAction(sysTrayStream);
  4021. trayMenu->addAction(sysTrayRecord);
  4022. trayMenu->addAction(sysTrayReplayBuffer);
  4023. trayMenu->addAction(exit);
  4024. trayIcon->setContextMenu(trayMenu);
  4025. }
  4026. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4027. {
  4028. if (reason == QSystemTrayIcon::Trigger)
  4029. ToggleShowHide();
  4030. }
  4031. void OBSBasic::SysTrayNotify(const QString &text,
  4032. QSystemTrayIcon::MessageIcon n)
  4033. {
  4034. if (QSystemTrayIcon::supportsMessages()) {
  4035. QSystemTrayIcon::MessageIcon icon =
  4036. QSystemTrayIcon::MessageIcon(n);
  4037. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4038. }
  4039. }
  4040. void OBSBasic::SystemTray(bool firstStarted)
  4041. {
  4042. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4043. return;
  4044. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4045. "BasicWindow", "SysTrayWhenStarted");
  4046. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4047. "BasicWindow", "SysTrayEnabled");
  4048. if (firstStarted)
  4049. SystemTrayInit();
  4050. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4051. trayIcon->hide();
  4052. } else if (sysTrayWhenStarted && sysTrayEnabled) {
  4053. trayIcon->show();
  4054. if (firstStarted) {
  4055. QTimer::singleShot(50, this, SLOT(hide()));
  4056. EnablePreviewDisplay(false);
  4057. setVisible(false);
  4058. }
  4059. } else if (sysTrayEnabled) {
  4060. trayIcon->show();
  4061. } else if (!sysTrayEnabled) {
  4062. trayIcon->hide();
  4063. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4064. trayIcon->hide();
  4065. }
  4066. if (isVisible())
  4067. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4068. else
  4069. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4070. }
  4071. bool OBSBasic::sysTrayMinimizeToTray()
  4072. {
  4073. return config_get_bool(GetGlobalConfig(),
  4074. "BasicWindow", "SysTrayMinimizeToTray");
  4075. }