window-basic-main.cpp 188 KB

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