window-basic-main.cpp 202 KB

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