window-basic-main.cpp 138 KB

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