window-basic-main.cpp 179 KB

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