window-basic-main.cpp 136 KB

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