window-basic-main.cpp 153 KB

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