window-basic-main.cpp 137 KB

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