window-basic-main.cpp 202 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624
  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. }
  1797. void OBSBasic::ClearHotkeys()
  1798. {
  1799. obs_hotkey_pair_unregister(streamingHotkeys);
  1800. obs_hotkey_pair_unregister(recordingHotkeys);
  1801. obs_hotkey_pair_unregister(pauseHotkeys);
  1802. obs_hotkey_pair_unregister(replayBufHotkeys);
  1803. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  1804. obs_hotkey_unregister(forceStreamingStopHotkey);
  1805. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1806. obs_hotkey_unregister(transitionHotkey);
  1807. }
  1808. OBSBasic::~OBSBasic()
  1809. {
  1810. if (updateCheckThread && updateCheckThread->isRunning())
  1811. updateCheckThread->wait();
  1812. delete multiviewProjectorMenu;
  1813. delete previewProjector;
  1814. delete studioProgramProjector;
  1815. delete previewProjectorSource;
  1816. delete previewProjectorMain;
  1817. delete sourceProjector;
  1818. delete sceneProjectorMenu;
  1819. delete scaleFilteringMenu;
  1820. delete colorMenu;
  1821. delete colorWidgetAction;
  1822. delete colorSelect;
  1823. delete deinterlaceMenu;
  1824. delete perSceneTransitionMenu;
  1825. delete shortcutFilter;
  1826. delete trayMenu;
  1827. delete programOptions;
  1828. delete program;
  1829. /* XXX: any obs data must be released before calling obs_shutdown.
  1830. * currently, we can't automate this with C++ RAII because of the
  1831. * delicate nature of obs_shutdown needing to be freed before the UI
  1832. * can be freed, and we have no control over the destruction order of
  1833. * the Qt UI stuff, so we have to manually clear any references to
  1834. * libobs. */
  1835. delete cpuUsageTimer;
  1836. os_cpu_usage_info_destroy(cpuUsageInfo);
  1837. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1838. ClearHotkeys();
  1839. service = nullptr;
  1840. outputHandler.reset();
  1841. if (interaction)
  1842. delete interaction;
  1843. if (properties)
  1844. delete properties;
  1845. if (filters)
  1846. delete filters;
  1847. if (transformWindow)
  1848. delete transformWindow;
  1849. if (advAudioWindow)
  1850. delete advAudioWindow;
  1851. if (about)
  1852. delete about;
  1853. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1854. OBSBasic::RenderMain, this);
  1855. obs_enter_graphics();
  1856. gs_vertexbuffer_destroy(box);
  1857. gs_vertexbuffer_destroy(boxLeft);
  1858. gs_vertexbuffer_destroy(boxTop);
  1859. gs_vertexbuffer_destroy(boxRight);
  1860. gs_vertexbuffer_destroy(boxBottom);
  1861. gs_vertexbuffer_destroy(circle);
  1862. obs_leave_graphics();
  1863. /* When shutting down, sometimes source references can get in to the
  1864. * event queue, and if we don't forcibly process those events they
  1865. * won't get processed until after obs_shutdown has been called. I
  1866. * really wish there were a more elegant way to deal with this via C++,
  1867. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1868. * normal C++ behavior for your data to be freed in the order that you
  1869. * expect or want it to. */
  1870. QApplication::sendPostedEvents(this);
  1871. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1872. LIBOBS_API_VER);
  1873. #if OBS_RELEASE_CANDIDATE > 0
  1874. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  1875. OBS_RELEASE_CANDIDATE_VER);
  1876. #endif
  1877. bool alwaysOnTop = IsAlwaysOnTop(this);
  1878. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1879. previewEnabled);
  1880. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1881. alwaysOnTop);
  1882. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1883. "SceneDuplicationMode", sceneDuplicationMode);
  1884. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  1885. swapScenesMode);
  1886. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1887. "EditPropertiesMode", editPropertiesMode);
  1888. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1889. "PreviewProgramMode", IsPreviewProgramMode());
  1890. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  1891. ui->lockUI->isChecked());
  1892. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1893. #ifdef _WIN32
  1894. uint32_t winVer = GetWindowsVersion();
  1895. if (winVer > 0 && winVer < 0x602) {
  1896. bool disableAero =
  1897. config_get_bool(basicConfig, "Video", "DisableAero");
  1898. if (disableAero) {
  1899. SetAeroEnabled(true);
  1900. }
  1901. }
  1902. #endif
  1903. #ifdef BROWSER_AVAILABLE
  1904. DestroyPanelCookieManager();
  1905. delete cef;
  1906. cef = nullptr;
  1907. #endif
  1908. }
  1909. void OBSBasic::SaveProjectNow()
  1910. {
  1911. if (disableSaving)
  1912. return;
  1913. projectChanged = true;
  1914. SaveProjectDeferred();
  1915. }
  1916. void OBSBasic::SaveProject()
  1917. {
  1918. if (disableSaving)
  1919. return;
  1920. projectChanged = true;
  1921. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1922. Qt::QueuedConnection);
  1923. }
  1924. void OBSBasic::SaveProjectDeferred()
  1925. {
  1926. if (disableSaving)
  1927. return;
  1928. if (!projectChanged)
  1929. return;
  1930. projectChanged = false;
  1931. const char *sceneCollection = config_get_string(
  1932. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1933. char savePath[512];
  1934. char fileName[512];
  1935. int ret;
  1936. if (!sceneCollection)
  1937. return;
  1938. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1939. sceneCollection);
  1940. if (ret <= 0)
  1941. return;
  1942. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1943. if (ret <= 0)
  1944. return;
  1945. Save(savePath);
  1946. }
  1947. OBSSource OBSBasic::GetProgramSource()
  1948. {
  1949. return OBSGetStrongRef(programScene);
  1950. }
  1951. OBSScene OBSBasic::GetCurrentScene()
  1952. {
  1953. QListWidgetItem *item = ui->scenes->currentItem();
  1954. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1955. }
  1956. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1957. {
  1958. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1959. }
  1960. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1961. {
  1962. return ui->sources->Get(GetTopSelectedSourceItem());
  1963. }
  1964. void OBSBasic::UpdatePreviewScalingMenu()
  1965. {
  1966. bool fixedScaling = ui->preview->IsFixedScaling();
  1967. float scalingAmount = ui->preview->GetScalingAmount();
  1968. if (!fixedScaling) {
  1969. ui->actionScaleWindow->setChecked(true);
  1970. ui->actionScaleCanvas->setChecked(false);
  1971. ui->actionScaleOutput->setChecked(false);
  1972. return;
  1973. }
  1974. obs_video_info ovi;
  1975. obs_get_video_info(&ovi);
  1976. ui->actionScaleWindow->setChecked(false);
  1977. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1978. ui->actionScaleOutput->setChecked(scalingAmount ==
  1979. float(ovi.output_width) /
  1980. float(ovi.base_width));
  1981. }
  1982. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1983. {
  1984. if (interaction)
  1985. interaction->close();
  1986. interaction = new OBSBasicInteraction(this, source);
  1987. interaction->Init();
  1988. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1989. }
  1990. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1991. {
  1992. if (properties)
  1993. properties->close();
  1994. properties = new OBSBasicProperties(this, source);
  1995. properties->Init();
  1996. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1997. }
  1998. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1999. {
  2000. if (filters)
  2001. filters->close();
  2002. filters = new OBSBasicFilters(this, source);
  2003. filters->Init();
  2004. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2005. }
  2006. /* Qt callbacks for invokeMethod */
  2007. void OBSBasic::AddScene(OBSSource source)
  2008. {
  2009. const char *name = obs_source_get_name(source);
  2010. obs_scene_t *scene = obs_scene_from_source(source);
  2011. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2012. SetOBSRef(item, OBSScene(scene));
  2013. ui->scenes->addItem(item);
  2014. obs_hotkey_register_source(
  2015. source, "OBSBasic.SelectScene",
  2016. Str("Basic.Hotkeys.SelectScene"),
  2017. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2018. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2019. App()->GetMainWindow());
  2020. auto potential_source =
  2021. static_cast<obs_source_t *>(data);
  2022. auto source = obs_source_get_ref(potential_source);
  2023. if (source && pressed)
  2024. main->SetCurrentScene(source);
  2025. obs_source_release(source);
  2026. },
  2027. static_cast<obs_source_t *>(source));
  2028. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2029. SignalContainer<OBSScene> container;
  2030. container.ref = scene;
  2031. container.handlers.assign({
  2032. std::make_shared<OBSSignal>(handler, "item_add",
  2033. OBSBasic::SceneItemAdded, this),
  2034. std::make_shared<OBSSignal>(handler, "item_select",
  2035. OBSBasic::SceneItemSelected, this),
  2036. std::make_shared<OBSSignal>(handler, "item_deselect",
  2037. OBSBasic::SceneItemDeselected,
  2038. this),
  2039. std::make_shared<OBSSignal>(handler, "reorder",
  2040. OBSBasic::SceneReordered, this),
  2041. });
  2042. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2043. QVariant::fromValue(container));
  2044. /* if the scene already has items (a duplicated scene) add them */
  2045. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2046. AddSceneItem(item);
  2047. };
  2048. using addSceneItem_t = decltype(addSceneItem);
  2049. obs_scene_enum_items(
  2050. scene,
  2051. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2052. addSceneItem_t *func;
  2053. func = reinterpret_cast<addSceneItem_t *>(param);
  2054. (*func)(item);
  2055. return true;
  2056. },
  2057. &addSceneItem);
  2058. SaveProject();
  2059. if (!disableSaving) {
  2060. obs_source_t *source = obs_scene_get_source(scene);
  2061. blog(LOG_INFO, "User added scene '%s'",
  2062. obs_source_get_name(source));
  2063. OBSProjector::UpdateMultiviewProjectors();
  2064. }
  2065. if (api)
  2066. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2067. }
  2068. void OBSBasic::RemoveScene(OBSSource source)
  2069. {
  2070. obs_scene_t *scene = obs_scene_from_source(source);
  2071. QListWidgetItem *sel = nullptr;
  2072. int count = ui->scenes->count();
  2073. for (int i = 0; i < count; i++) {
  2074. auto item = ui->scenes->item(i);
  2075. auto cur_scene = GetOBSRef<OBSScene>(item);
  2076. if (cur_scene != scene)
  2077. continue;
  2078. sel = item;
  2079. break;
  2080. }
  2081. if (sel != nullptr) {
  2082. if (sel == ui->scenes->currentItem())
  2083. ui->sources->Clear();
  2084. delete sel;
  2085. }
  2086. SaveProject();
  2087. if (!disableSaving) {
  2088. blog(LOG_INFO, "User Removed scene '%s'",
  2089. obs_source_get_name(source));
  2090. OBSProjector::UpdateMultiviewProjectors();
  2091. }
  2092. if (api)
  2093. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2094. }
  2095. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2096. {
  2097. obs_sceneitem_t *selectedItem =
  2098. reinterpret_cast<obs_sceneitem_t *>(param);
  2099. if (obs_sceneitem_is_group(item))
  2100. obs_sceneitem_group_enum_items(item, select_one, param);
  2101. obs_sceneitem_select(item, (selectedItem == item));
  2102. UNUSED_PARAMETER(scene);
  2103. return true;
  2104. }
  2105. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2106. {
  2107. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2108. if (GetCurrentScene() == scene)
  2109. ui->sources->Add(item);
  2110. SaveProject();
  2111. if (!disableSaving) {
  2112. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2113. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2114. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2115. obs_source_get_name(itemSource),
  2116. obs_source_get_id(itemSource),
  2117. obs_source_get_name(sceneSource));
  2118. obs_scene_enum_items(scene, select_one,
  2119. (obs_sceneitem_t *)item);
  2120. }
  2121. }
  2122. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2123. {
  2124. if (source) {
  2125. obs_scene_t *scene = obs_scene_from_source(source);
  2126. const char *name = obs_source_get_name(source);
  2127. if (!scene)
  2128. return;
  2129. QList<QListWidgetItem *> items =
  2130. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2131. if (items.count()) {
  2132. sceneChanging = true;
  2133. ui->scenes->setCurrentItem(items.first());
  2134. sceneChanging = false;
  2135. OBSScene curScene =
  2136. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2137. if (api && scene != curScene)
  2138. api->on_event(
  2139. OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2140. }
  2141. }
  2142. }
  2143. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2144. const QString &prevName)
  2145. {
  2146. QList<QListWidgetItem *> items =
  2147. listWidget->findItems(prevName, Qt::MatchExactly);
  2148. for (int i = 0; i < items.count(); i++)
  2149. items[i]->setText(newName);
  2150. }
  2151. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2152. QString prevName)
  2153. {
  2154. RenameListValues(ui->scenes, newName, prevName);
  2155. for (size_t i = 0; i < volumes.size(); i++) {
  2156. if (volumes[i]->GetName().compare(prevName) == 0)
  2157. volumes[i]->SetName(newName);
  2158. }
  2159. OBSProjector::RenameProjector(prevName, newName);
  2160. SaveProject();
  2161. obs_scene_t *scene = obs_scene_from_source(source);
  2162. if (scene)
  2163. OBSProjector::UpdateMultiviewProjectors();
  2164. }
  2165. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  2166. {
  2167. SignalBlocker sourcesSignalBlocker(ui->sources);
  2168. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  2169. return;
  2170. ui->sources->SelectItem(item, select);
  2171. }
  2172. static inline bool SourceMixerHidden(obs_source_t *source)
  2173. {
  2174. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2175. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2176. obs_data_release(priv_settings);
  2177. return hidden;
  2178. }
  2179. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2180. {
  2181. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2182. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2183. obs_data_release(priv_settings);
  2184. }
  2185. void OBSBasic::GetAudioSourceFilters()
  2186. {
  2187. QAction *action = reinterpret_cast<QAction *>(sender());
  2188. VolControl *vol = action->property("volControl").value<VolControl *>();
  2189. obs_source_t *source = vol->GetSource();
  2190. CreateFiltersWindow(source);
  2191. }
  2192. void OBSBasic::GetAudioSourceProperties()
  2193. {
  2194. QAction *action = reinterpret_cast<QAction *>(sender());
  2195. VolControl *vol = action->property("volControl").value<VolControl *>();
  2196. obs_source_t *source = vol->GetSource();
  2197. CreatePropertiesWindow(source);
  2198. }
  2199. void OBSBasic::HideAudioControl()
  2200. {
  2201. QAction *action = reinterpret_cast<QAction *>(sender());
  2202. VolControl *vol = action->property("volControl").value<VolControl *>();
  2203. obs_source_t *source = vol->GetSource();
  2204. if (!SourceMixerHidden(source)) {
  2205. SetSourceMixerHidden(source, true);
  2206. DeactivateAudioSource(source);
  2207. }
  2208. }
  2209. void OBSBasic::UnhideAllAudioControls()
  2210. {
  2211. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2212. {
  2213. if (!obs_source_active(source))
  2214. return true;
  2215. if (!SourceMixerHidden(source))
  2216. return true;
  2217. SetSourceMixerHidden(source, false);
  2218. ActivateAudioSource(source);
  2219. return true;
  2220. };
  2221. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2222. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2223. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2224. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2225. }
  2226. void OBSBasic::ToggleHideMixer()
  2227. {
  2228. OBSSceneItem item = GetCurrentSceneItem();
  2229. OBSSource source = obs_sceneitem_get_source(item);
  2230. if (!SourceMixerHidden(source)) {
  2231. SetSourceMixerHidden(source, true);
  2232. DeactivateAudioSource(source);
  2233. } else {
  2234. SetSourceMixerHidden(source, false);
  2235. ActivateAudioSource(source);
  2236. }
  2237. }
  2238. void OBSBasic::MixerRenameSource()
  2239. {
  2240. QAction *action = reinterpret_cast<QAction *>(sender());
  2241. VolControl *vol = action->property("volControl").value<VolControl *>();
  2242. OBSSource source = vol->GetSource();
  2243. const char *prevName = obs_source_get_name(source);
  2244. for (;;) {
  2245. string name;
  2246. bool accepted = NameDialog::AskForName(
  2247. this, QTStr("Basic.Main.MixerRename.Title"),
  2248. QTStr("Basic.Main.MixerRename.Text"), name,
  2249. QT_UTF8(prevName));
  2250. if (!accepted)
  2251. return;
  2252. if (name.empty()) {
  2253. OBSMessageBox::warning(this,
  2254. QTStr("NoNameEntered.Title"),
  2255. QTStr("NoNameEntered.Text"));
  2256. continue;
  2257. }
  2258. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2259. obs_source_release(sourceTest);
  2260. if (sourceTest) {
  2261. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2262. QTStr("NameExists.Text"));
  2263. continue;
  2264. }
  2265. obs_source_set_name(source, name.c_str());
  2266. break;
  2267. }
  2268. }
  2269. void OBSBasic::VolControlContextMenu()
  2270. {
  2271. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2272. /* ------------------- */
  2273. QAction hideAction(QTStr("Hide"), this);
  2274. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2275. QAction mixerRenameAction(QTStr("Rename"), this);
  2276. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2277. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2278. QAction filtersAction(QTStr("Filters"), this);
  2279. QAction propertiesAction(QTStr("Properties"), this);
  2280. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2281. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2282. toggleControlLayoutAction.setCheckable(true);
  2283. toggleControlLayoutAction.setChecked(config_get_bool(
  2284. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2285. /* ------------------- */
  2286. connect(&hideAction, &QAction::triggered, this,
  2287. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2288. connect(&unhideAllAction, &QAction::triggered, this,
  2289. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2290. connect(&mixerRenameAction, &QAction::triggered, this,
  2291. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2292. connect(&copyFiltersAction, &QAction::triggered, this,
  2293. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2294. connect(&pasteFiltersAction, &QAction::triggered, this,
  2295. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2296. connect(&filtersAction, &QAction::triggered, this,
  2297. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2298. connect(&propertiesAction, &QAction::triggered, this,
  2299. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2300. connect(&advPropAction, &QAction::triggered, this,
  2301. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2302. Qt::DirectConnection);
  2303. /* ------------------- */
  2304. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2305. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2306. /* ------------------- */
  2307. hideAction.setProperty("volControl",
  2308. QVariant::fromValue<VolControl *>(vol));
  2309. mixerRenameAction.setProperty("volControl",
  2310. QVariant::fromValue<VolControl *>(vol));
  2311. copyFiltersAction.setProperty("volControl",
  2312. QVariant::fromValue<VolControl *>(vol));
  2313. pasteFiltersAction.setProperty("volControl",
  2314. QVariant::fromValue<VolControl *>(vol));
  2315. filtersAction.setProperty("volControl",
  2316. QVariant::fromValue<VolControl *>(vol));
  2317. propertiesAction.setProperty("volControl",
  2318. QVariant::fromValue<VolControl *>(vol));
  2319. /* ------------------- */
  2320. if (copyFiltersString == nullptr)
  2321. pasteFiltersAction.setEnabled(false);
  2322. else
  2323. pasteFiltersAction.setEnabled(true);
  2324. QMenu popup;
  2325. popup.addAction(&unhideAllAction);
  2326. popup.addAction(&hideAction);
  2327. popup.addAction(&mixerRenameAction);
  2328. popup.addSeparator();
  2329. popup.addAction(&copyFiltersAction);
  2330. popup.addAction(&pasteFiltersAction);
  2331. popup.addSeparator();
  2332. popup.addAction(&toggleControlLayoutAction);
  2333. popup.addSeparator();
  2334. popup.addAction(&filtersAction);
  2335. popup.addAction(&propertiesAction);
  2336. popup.addAction(&advPropAction);
  2337. popup.exec(QCursor::pos());
  2338. }
  2339. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2340. {
  2341. StackedMixerAreaContextMenuRequested();
  2342. }
  2343. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2344. {
  2345. StackedMixerAreaContextMenuRequested();
  2346. }
  2347. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2348. {
  2349. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2350. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2351. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2352. toggleControlLayoutAction.setCheckable(true);
  2353. toggleControlLayoutAction.setChecked(config_get_bool(
  2354. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2355. /* ------------------- */
  2356. connect(&unhideAllAction, &QAction::triggered, this,
  2357. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2358. connect(&advPropAction, &QAction::triggered, this,
  2359. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2360. Qt::DirectConnection);
  2361. /* ------------------- */
  2362. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2363. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2364. /* ------------------- */
  2365. QMenu popup;
  2366. popup.addAction(&unhideAllAction);
  2367. popup.addSeparator();
  2368. popup.addAction(&toggleControlLayoutAction);
  2369. popup.addSeparator();
  2370. popup.addAction(&advPropAction);
  2371. popup.exec(QCursor::pos());
  2372. }
  2373. void OBSBasic::ToggleMixerLayout(bool vertical)
  2374. {
  2375. if (vertical) {
  2376. ui->stackedMixerArea->setMinimumSize(180, 220);
  2377. ui->stackedMixerArea->setCurrentIndex(1);
  2378. } else {
  2379. ui->stackedMixerArea->setMinimumSize(220, 0);
  2380. ui->stackedMixerArea->setCurrentIndex(0);
  2381. }
  2382. }
  2383. void OBSBasic::ToggleVolControlLayout()
  2384. {
  2385. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2386. "VerticalVolControl");
  2387. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2388. vertical);
  2389. ToggleMixerLayout(vertical);
  2390. // We need to store it so we can delete current and then add
  2391. // at the right order
  2392. vector<OBSSource> sources;
  2393. for (size_t i = 0; i != volumes.size(); i++)
  2394. sources.emplace_back(volumes[i]->GetSource());
  2395. ClearVolumeControls();
  2396. for (const auto &source : sources)
  2397. ActivateAudioSource(source);
  2398. }
  2399. void OBSBasic::ActivateAudioSource(OBSSource source)
  2400. {
  2401. if (SourceMixerHidden(source))
  2402. return;
  2403. if (!obs_source_audio_active(source))
  2404. return;
  2405. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2406. "VerticalVolControl");
  2407. VolControl *vol = new VolControl(source, true, vertical);
  2408. double meterDecayRate =
  2409. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2410. vol->SetMeterDecayRate(meterDecayRate);
  2411. uint32_t peakMeterTypeIdx =
  2412. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2413. enum obs_peak_meter_type peakMeterType;
  2414. switch (peakMeterTypeIdx) {
  2415. case 0:
  2416. peakMeterType = SAMPLE_PEAK_METER;
  2417. break;
  2418. case 1:
  2419. peakMeterType = TRUE_PEAK_METER;
  2420. break;
  2421. default:
  2422. peakMeterType = SAMPLE_PEAK_METER;
  2423. break;
  2424. }
  2425. vol->setPeakMeterType(peakMeterType);
  2426. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2427. connect(vol, &QWidget::customContextMenuRequested, this,
  2428. &OBSBasic::VolControlContextMenu);
  2429. connect(vol, &VolControl::ConfigClicked, this,
  2430. &OBSBasic::VolControlContextMenu);
  2431. InsertQObjectByName(volumes, vol);
  2432. for (auto volume : volumes) {
  2433. if (vertical)
  2434. ui->vVolControlLayout->addWidget(volume);
  2435. else
  2436. ui->hVolControlLayout->addWidget(volume);
  2437. }
  2438. }
  2439. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2440. {
  2441. for (size_t i = 0; i < volumes.size(); i++) {
  2442. if (volumes[i]->GetSource() == source) {
  2443. delete volumes[i];
  2444. volumes.erase(volumes.begin() + i);
  2445. break;
  2446. }
  2447. }
  2448. }
  2449. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2450. {
  2451. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2452. !obs_source_is_group(source)) {
  2453. int count = ui->scenes->count();
  2454. if (count == 1) {
  2455. OBSMessageBox::information(this,
  2456. QTStr("FinalScene.Title"),
  2457. QTStr("FinalScene.Text"));
  2458. return false;
  2459. }
  2460. }
  2461. const char *name = obs_source_get_name(source);
  2462. QString text = QTStr("ConfirmRemove.Text");
  2463. text.replace("$1", QT_UTF8(name));
  2464. QMessageBox remove_source(this);
  2465. remove_source.setText(text);
  2466. QAbstractButton *Yes =
  2467. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2468. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2469. remove_source.setIcon(QMessageBox::Question);
  2470. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2471. remove_source.exec();
  2472. return Yes == remove_source.clickedButton();
  2473. }
  2474. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2475. #ifdef UPDATE_SPARKLE
  2476. void init_sparkle_updater(bool update_to_undeployed);
  2477. void trigger_sparkle_update();
  2478. #endif
  2479. void OBSBasic::TimedCheckForUpdates()
  2480. {
  2481. if (!config_get_bool(App()->GlobalConfig(), "General",
  2482. "EnableAutoUpdates"))
  2483. return;
  2484. #ifdef UPDATE_SPARKLE
  2485. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2486. "UpdateToUndeployed"));
  2487. #elif _WIN32
  2488. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2489. "LastUpdateCheck");
  2490. uint32_t lastVersion =
  2491. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2492. if (lastVersion < LIBOBS_API_VER) {
  2493. lastUpdate = 0;
  2494. config_set_int(App()->GlobalConfig(), "General",
  2495. "LastUpdateCheck", 0);
  2496. }
  2497. long long t = (long long)time(nullptr);
  2498. long long secs = t - lastUpdate;
  2499. if (secs > UPDATE_CHECK_INTERVAL)
  2500. CheckForUpdates(false);
  2501. #endif
  2502. }
  2503. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2504. {
  2505. #ifdef UPDATE_SPARKLE
  2506. trigger_sparkle_update();
  2507. #elif _WIN32
  2508. ui->actionCheckForUpdates->setEnabled(false);
  2509. if (updateCheckThread && updateCheckThread->isRunning())
  2510. return;
  2511. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2512. updateCheckThread->start();
  2513. #endif
  2514. UNUSED_PARAMETER(manualUpdate);
  2515. }
  2516. void OBSBasic::updateCheckFinished()
  2517. {
  2518. ui->actionCheckForUpdates->setEnabled(true);
  2519. }
  2520. void OBSBasic::DuplicateSelectedScene()
  2521. {
  2522. OBSScene curScene = GetCurrentScene();
  2523. if (!curScene)
  2524. return;
  2525. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2526. QString format{obs_source_get_name(curSceneSource)};
  2527. format += " %1";
  2528. int i = 2;
  2529. QString placeHolderText = format.arg(i);
  2530. obs_source_t *source = nullptr;
  2531. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2532. obs_source_release(source);
  2533. placeHolderText = format.arg(++i);
  2534. }
  2535. for (;;) {
  2536. string name;
  2537. bool accepted = NameDialog::AskForName(
  2538. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2539. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2540. placeHolderText);
  2541. if (!accepted)
  2542. return;
  2543. if (name.empty()) {
  2544. OBSMessageBox::warning(this,
  2545. QTStr("NoNameEntered.Title"),
  2546. QTStr("NoNameEntered.Text"));
  2547. continue;
  2548. }
  2549. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2550. if (source) {
  2551. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2552. QTStr("NameExists.Text"));
  2553. obs_source_release(source);
  2554. continue;
  2555. }
  2556. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2557. OBS_SCENE_DUP_REFS);
  2558. source = obs_scene_get_source(scene);
  2559. SetCurrentScene(source, true);
  2560. obs_scene_release(scene);
  2561. break;
  2562. }
  2563. }
  2564. void OBSBasic::RemoveSelectedScene()
  2565. {
  2566. OBSScene scene = GetCurrentScene();
  2567. if (scene) {
  2568. obs_source_t *source = obs_scene_get_source(scene);
  2569. if (QueryRemoveSource(source)) {
  2570. obs_source_remove(source);
  2571. if (api)
  2572. api->on_event(
  2573. OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2574. }
  2575. }
  2576. }
  2577. void OBSBasic::RemoveSelectedSceneItem()
  2578. {
  2579. OBSSceneItem item = GetCurrentSceneItem();
  2580. if (item) {
  2581. obs_source_t *source = obs_sceneitem_get_source(item);
  2582. if (QueryRemoveSource(source))
  2583. obs_sceneitem_remove(item);
  2584. }
  2585. }
  2586. void OBSBasic::ReorderSources(OBSScene scene)
  2587. {
  2588. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2589. return;
  2590. ui->sources->ReorderItems();
  2591. SaveProject();
  2592. }
  2593. /* OBS Callbacks */
  2594. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2595. {
  2596. OBSBasic *window = static_cast<OBSBasic *>(data);
  2597. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2598. QMetaObject::invokeMethod(window, "ReorderSources",
  2599. Q_ARG(OBSScene, OBSScene(scene)));
  2600. }
  2601. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2602. {
  2603. OBSBasic *window = static_cast<OBSBasic *>(data);
  2604. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2605. QMetaObject::invokeMethod(window, "AddSceneItem",
  2606. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2607. }
  2608. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2609. {
  2610. OBSBasic *window = static_cast<OBSBasic *>(data);
  2611. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2612. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2613. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2614. Q_ARG(OBSScene, scene),
  2615. Q_ARG(OBSSceneItem, item), Q_ARG(bool, true));
  2616. }
  2617. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2618. {
  2619. OBSBasic *window = static_cast<OBSBasic *>(data);
  2620. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2621. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2622. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2623. Q_ARG(OBSScene, scene),
  2624. Q_ARG(OBSSceneItem, item),
  2625. Q_ARG(bool, false));
  2626. }
  2627. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2628. {
  2629. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2630. if (obs_scene_from_source(source) != NULL)
  2631. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2632. "AddScene", WaitConnection(),
  2633. Q_ARG(OBSSource, OBSSource(source)));
  2634. }
  2635. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2636. {
  2637. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2638. if (obs_scene_from_source(source) != NULL)
  2639. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2640. "RemoveScene",
  2641. Q_ARG(OBSSource, OBSSource(source)));
  2642. }
  2643. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2644. {
  2645. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2646. uint32_t flags = obs_source_get_output_flags(source);
  2647. if (flags & OBS_SOURCE_AUDIO)
  2648. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2649. "ActivateAudioSource",
  2650. Q_ARG(OBSSource, OBSSource(source)));
  2651. }
  2652. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2653. {
  2654. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2655. uint32_t flags = obs_source_get_output_flags(source);
  2656. if (flags & OBS_SOURCE_AUDIO)
  2657. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2658. "DeactivateAudioSource",
  2659. Q_ARG(OBSSource, OBSSource(source)));
  2660. }
  2661. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  2662. {
  2663. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2664. if (obs_source_active(source))
  2665. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2666. "ActivateAudioSource",
  2667. Q_ARG(OBSSource, OBSSource(source)));
  2668. }
  2669. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  2670. {
  2671. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2672. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2673. "DeactivateAudioSource",
  2674. Q_ARG(OBSSource, OBSSource(source)));
  2675. }
  2676. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2677. {
  2678. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2679. const char *newName = calldata_string(params, "new_name");
  2680. const char *prevName = calldata_string(params, "prev_name");
  2681. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2682. "RenameSources", Q_ARG(OBSSource, source),
  2683. Q_ARG(QString, QT_UTF8(newName)),
  2684. Q_ARG(QString, QT_UTF8(prevName)));
  2685. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2686. }
  2687. void OBSBasic::DrawBackdrop(float cx, float cy)
  2688. {
  2689. if (!box)
  2690. return;
  2691. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  2692. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2693. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2694. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2695. vec4 colorVal;
  2696. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2697. gs_effect_set_vec4(color, &colorVal);
  2698. gs_technique_begin(tech);
  2699. gs_technique_begin_pass(tech, 0);
  2700. gs_matrix_push();
  2701. gs_matrix_identity();
  2702. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2703. gs_load_vertexbuffer(box);
  2704. gs_draw(GS_TRISTRIP, 0, 0);
  2705. gs_matrix_pop();
  2706. gs_technique_end_pass(tech);
  2707. gs_technique_end(tech);
  2708. gs_load_vertexbuffer(nullptr);
  2709. GS_DEBUG_MARKER_END();
  2710. }
  2711. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2712. {
  2713. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  2714. OBSBasic *window = static_cast<OBSBasic *>(data);
  2715. obs_video_info ovi;
  2716. obs_get_video_info(&ovi);
  2717. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2718. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2719. gs_viewport_push();
  2720. gs_projection_push();
  2721. obs_display_t *display = window->ui->preview->GetDisplay();
  2722. uint32_t width, height;
  2723. obs_display_size(display, &width, &height);
  2724. float right = float(width) - window->previewX;
  2725. float bottom = float(height) - window->previewY;
  2726. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  2727. 100.0f);
  2728. window->ui->preview->DrawOverflow();
  2729. /* --------------------------------------- */
  2730. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2731. -100.0f, 100.0f);
  2732. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  2733. window->previewCY);
  2734. if (window->IsPreviewProgramMode()) {
  2735. window->DrawBackdrop(float(ovi.base_width),
  2736. float(ovi.base_height));
  2737. OBSScene scene = window->GetCurrentScene();
  2738. obs_source_t *source = obs_scene_get_source(scene);
  2739. if (source)
  2740. obs_source_video_render(source);
  2741. } else {
  2742. obs_render_main_texture_src_color_only();
  2743. }
  2744. gs_load_vertexbuffer(nullptr);
  2745. /* --------------------------------------- */
  2746. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  2747. 100.0f);
  2748. gs_reset_viewport();
  2749. window->ui->preview->DrawSceneEditing();
  2750. /* --------------------------------------- */
  2751. gs_projection_pop();
  2752. gs_viewport_pop();
  2753. GS_DEBUG_MARKER_END();
  2754. UNUSED_PARAMETER(cx);
  2755. UNUSED_PARAMETER(cy);
  2756. }
  2757. /* Main class functions */
  2758. obs_service_t *OBSBasic::GetService()
  2759. {
  2760. if (!service) {
  2761. service =
  2762. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  2763. obs_service_release(service);
  2764. }
  2765. return service;
  2766. }
  2767. void OBSBasic::SetService(obs_service_t *newService)
  2768. {
  2769. if (newService)
  2770. service = newService;
  2771. }
  2772. int OBSBasic::GetTransitionDuration()
  2773. {
  2774. return ui->transitionDuration->value();
  2775. }
  2776. bool OBSBasic::StreamingActive() const
  2777. {
  2778. if (!outputHandler)
  2779. return false;
  2780. return outputHandler->StreamingActive();
  2781. }
  2782. bool OBSBasic::Active() const
  2783. {
  2784. if (!outputHandler)
  2785. return false;
  2786. return outputHandler->Active();
  2787. }
  2788. #ifdef _WIN32
  2789. #define IS_WIN32 1
  2790. #else
  2791. #define IS_WIN32 0
  2792. #endif
  2793. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2794. {
  2795. return obs_reset_video(ovi);
  2796. }
  2797. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2798. {
  2799. const char *scaleTypeStr =
  2800. config_get_string(basicConfig, "Video", "ScaleType");
  2801. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2802. return OBS_SCALE_BILINEAR;
  2803. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2804. return OBS_SCALE_LANCZOS;
  2805. else if (astrcmpi(scaleTypeStr, "area") == 0)
  2806. return OBS_SCALE_AREA;
  2807. else
  2808. return OBS_SCALE_BICUBIC;
  2809. }
  2810. static inline enum video_format GetVideoFormatFromName(const char *name)
  2811. {
  2812. if (astrcmpi(name, "I420") == 0)
  2813. return VIDEO_FORMAT_I420;
  2814. else if (astrcmpi(name, "NV12") == 0)
  2815. return VIDEO_FORMAT_NV12;
  2816. else if (astrcmpi(name, "I444") == 0)
  2817. return VIDEO_FORMAT_I444;
  2818. #if 0 //currently unsupported
  2819. else if (astrcmpi(name, "YVYU") == 0)
  2820. return VIDEO_FORMAT_YVYU;
  2821. else if (astrcmpi(name, "YUY2") == 0)
  2822. return VIDEO_FORMAT_YUY2;
  2823. else if (astrcmpi(name, "UYVY") == 0)
  2824. return VIDEO_FORMAT_UYVY;
  2825. #endif
  2826. else
  2827. return VIDEO_FORMAT_RGBA;
  2828. }
  2829. void OBSBasic::ResetUI()
  2830. {
  2831. bool studioPortraitLayout = config_get_bool(
  2832. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  2833. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2834. "StudioModeLabels");
  2835. if (studioPortraitLayout)
  2836. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2837. else
  2838. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2839. if (previewProgramMode)
  2840. ui->previewLabel->setHidden(!labels);
  2841. if (programLabel)
  2842. programLabel->setHidden(!labels);
  2843. }
  2844. int OBSBasic::ResetVideo()
  2845. {
  2846. if (outputHandler && outputHandler->Active())
  2847. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2848. ProfileScope("OBSBasic::ResetVideo");
  2849. struct obs_video_info ovi;
  2850. int ret;
  2851. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2852. const char *colorFormat =
  2853. config_get_string(basicConfig, "Video", "ColorFormat");
  2854. const char *colorSpace =
  2855. config_get_string(basicConfig, "Video", "ColorSpace");
  2856. const char *colorRange =
  2857. config_get_string(basicConfig, "Video", "ColorRange");
  2858. ovi.graphics_module = App()->GetRenderModule();
  2859. ovi.base_width =
  2860. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  2861. ovi.base_height =
  2862. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  2863. ovi.output_width =
  2864. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  2865. ovi.output_height =
  2866. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  2867. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2868. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ? VIDEO_CS_601
  2869. : VIDEO_CS_709;
  2870. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  2871. : VIDEO_RANGE_PARTIAL;
  2872. ovi.adapter =
  2873. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  2874. ovi.gpu_conversion = true;
  2875. ovi.scale_type = GetScaleType(basicConfig);
  2876. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2877. ovi.base_width = 1920;
  2878. ovi.base_height = 1080;
  2879. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2880. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2881. }
  2882. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2883. ovi.output_width = ovi.base_width;
  2884. ovi.output_height = ovi.base_height;
  2885. config_set_uint(basicConfig, "Video", "OutputCX",
  2886. ovi.base_width);
  2887. config_set_uint(basicConfig, "Video", "OutputCY",
  2888. ovi.base_height);
  2889. }
  2890. ret = AttemptToResetVideo(&ovi);
  2891. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2892. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2893. blog(LOG_WARNING, "Tried to reset when "
  2894. "already active");
  2895. return ret;
  2896. }
  2897. /* Try OpenGL if DirectX fails on windows */
  2898. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2899. blog(LOG_WARNING,
  2900. "Failed to initialize obs video (%d) "
  2901. "with graphics_module='%s', retrying "
  2902. "with graphics_module='%s'",
  2903. ret, ovi.graphics_module, DL_OPENGL);
  2904. ovi.graphics_module = DL_OPENGL;
  2905. ret = AttemptToResetVideo(&ovi);
  2906. }
  2907. } else if (ret == OBS_VIDEO_SUCCESS) {
  2908. ResizePreview(ovi.base_width, ovi.base_height);
  2909. if (program)
  2910. ResizeProgram(ovi.base_width, ovi.base_height);
  2911. }
  2912. if (ret == OBS_VIDEO_SUCCESS) {
  2913. OBSBasicStats::InitializeValues();
  2914. OBSProjector::UpdateMultiviewProjectors();
  2915. }
  2916. return ret;
  2917. }
  2918. bool OBSBasic::ResetAudio()
  2919. {
  2920. ProfileScope("OBSBasic::ResetAudio");
  2921. struct obs_audio_info ai;
  2922. ai.samples_per_sec =
  2923. config_get_uint(basicConfig, "Audio", "SampleRate");
  2924. const char *channelSetupStr =
  2925. config_get_string(basicConfig, "Audio", "ChannelSetup");
  2926. if (strcmp(channelSetupStr, "Mono") == 0)
  2927. ai.speakers = SPEAKERS_MONO;
  2928. else if (strcmp(channelSetupStr, "2.1") == 0)
  2929. ai.speakers = SPEAKERS_2POINT1;
  2930. else if (strcmp(channelSetupStr, "4.0") == 0)
  2931. ai.speakers = SPEAKERS_4POINT0;
  2932. else if (strcmp(channelSetupStr, "4.1") == 0)
  2933. ai.speakers = SPEAKERS_4POINT1;
  2934. else if (strcmp(channelSetupStr, "5.1") == 0)
  2935. ai.speakers = SPEAKERS_5POINT1;
  2936. else if (strcmp(channelSetupStr, "7.1") == 0)
  2937. ai.speakers = SPEAKERS_7POINT1;
  2938. else
  2939. ai.speakers = SPEAKERS_STEREO;
  2940. return obs_reset_audio(&ai);
  2941. }
  2942. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2943. const char *deviceDesc, int channel)
  2944. {
  2945. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2946. obs_source_t *source;
  2947. obs_data_t *settings;
  2948. source = obs_get_output_source(channel);
  2949. if (source) {
  2950. if (disable) {
  2951. obs_set_output_source(channel, nullptr);
  2952. } else {
  2953. settings = obs_source_get_settings(source);
  2954. const char *oldId =
  2955. obs_data_get_string(settings, "device_id");
  2956. if (strcmp(oldId, deviceId) != 0) {
  2957. obs_data_set_string(settings, "device_id",
  2958. deviceId);
  2959. obs_source_update(source, settings);
  2960. }
  2961. obs_data_release(settings);
  2962. }
  2963. obs_source_release(source);
  2964. } else if (!disable) {
  2965. settings = obs_data_create();
  2966. obs_data_set_string(settings, "device_id", deviceId);
  2967. source = obs_source_create(sourceId, deviceDesc, settings,
  2968. nullptr);
  2969. obs_data_release(settings);
  2970. obs_set_output_source(channel, source);
  2971. obs_source_release(source);
  2972. }
  2973. }
  2974. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2975. {
  2976. QSize targetSize;
  2977. bool isFixedScaling;
  2978. obs_video_info ovi;
  2979. /* resize preview panel to fix to the top section of the window */
  2980. targetSize = GetPixelSize(ui->preview);
  2981. isFixedScaling = ui->preview->IsFixedScaling();
  2982. obs_get_video_info(&ovi);
  2983. if (isFixedScaling) {
  2984. previewScale = ui->preview->GetScalingAmount();
  2985. GetCenterPosFromFixedScale(
  2986. int(cx), int(cy),
  2987. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2988. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  2989. previewY, previewScale);
  2990. previewX += ui->preview->GetScrollX();
  2991. previewY += ui->preview->GetScrollY();
  2992. } else {
  2993. GetScaleAndCenterPos(int(cx), int(cy),
  2994. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2995. targetSize.height() -
  2996. PREVIEW_EDGE_SIZE * 2,
  2997. previewX, previewY, previewScale);
  2998. }
  2999. previewX += float(PREVIEW_EDGE_SIZE);
  3000. previewY += float(PREVIEW_EDGE_SIZE);
  3001. }
  3002. void OBSBasic::CloseDialogs()
  3003. {
  3004. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3005. if (!childDialogs.isEmpty()) {
  3006. for (int i = 0; i < childDialogs.size(); ++i) {
  3007. childDialogs.at(i)->close();
  3008. }
  3009. }
  3010. for (QPointer<QWidget> &projector : windowProjectors) {
  3011. delete projector;
  3012. projector.clear();
  3013. }
  3014. for (QPointer<QWidget> &projector : projectors) {
  3015. delete projector;
  3016. projector.clear();
  3017. }
  3018. if (!stats.isNull())
  3019. stats->close(); //call close to save Stats geometry
  3020. if (!remux.isNull())
  3021. remux->close();
  3022. }
  3023. void OBSBasic::EnumDialogs()
  3024. {
  3025. visDialogs.clear();
  3026. modalDialogs.clear();
  3027. visMsgBoxes.clear();
  3028. /* fill list of Visible dialogs and Modal dialogs */
  3029. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3030. for (QDialog *dialog : dialogs) {
  3031. if (dialog->isVisible())
  3032. visDialogs.append(dialog);
  3033. if (dialog->isModal())
  3034. modalDialogs.append(dialog);
  3035. }
  3036. /* fill list of Visible message boxes */
  3037. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3038. for (QMessageBox *msgbox : msgBoxes) {
  3039. if (msgbox->isVisible())
  3040. visMsgBoxes.append(msgbox);
  3041. }
  3042. }
  3043. void OBSBasic::ClearSceneData()
  3044. {
  3045. disableSaving++;
  3046. CloseDialogs();
  3047. ClearVolumeControls();
  3048. ClearListItems(ui->scenes);
  3049. ui->sources->Clear();
  3050. ClearQuickTransitions();
  3051. ui->transitions->clear();
  3052. obs_set_output_source(0, nullptr);
  3053. obs_set_output_source(1, nullptr);
  3054. obs_set_output_source(2, nullptr);
  3055. obs_set_output_source(3, nullptr);
  3056. obs_set_output_source(4, nullptr);
  3057. obs_set_output_source(5, nullptr);
  3058. lastScene = nullptr;
  3059. swapScene = nullptr;
  3060. programScene = nullptr;
  3061. auto cb = [](void *unused, obs_source_t *source) {
  3062. obs_source_remove(source);
  3063. UNUSED_PARAMETER(unused);
  3064. return true;
  3065. };
  3066. obs_enum_sources(cb, nullptr);
  3067. if (api)
  3068. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3069. disableSaving--;
  3070. blog(LOG_INFO, "All scene data cleared");
  3071. blog(LOG_INFO, "------------------------------------------------");
  3072. }
  3073. void OBSBasic::closeEvent(QCloseEvent *event)
  3074. {
  3075. /* Do not close window if inside of a temporary event loop because we
  3076. * could be inside of an Auth::LoadUI call. Keep trying once per
  3077. * second until we've exit any known sub-loops. */
  3078. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3079. QTimer::singleShot(1000, this, SLOT(close()));
  3080. event->ignore();
  3081. return;
  3082. }
  3083. if (isVisible())
  3084. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3085. "geometry",
  3086. saveGeometry().toBase64().constData());
  3087. if (outputHandler && outputHandler->Active()) {
  3088. SetShowing(true);
  3089. QMessageBox::StandardButton button = OBSMessageBox::question(
  3090. this, QTStr("ConfirmExit.Title"),
  3091. QTStr("ConfirmExit.Text"));
  3092. if (button == QMessageBox::No) {
  3093. event->ignore();
  3094. return;
  3095. }
  3096. }
  3097. QWidget::closeEvent(event);
  3098. if (!event->isAccepted())
  3099. return;
  3100. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3101. if (introCheckThread)
  3102. introCheckThread->wait();
  3103. if (updateCheckThread)
  3104. updateCheckThread->wait();
  3105. if (logUploadThread)
  3106. logUploadThread->wait();
  3107. signalHandlers.clear();
  3108. Auth::Save();
  3109. SaveProjectNow();
  3110. auth.reset();
  3111. delete extraBrowsers;
  3112. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3113. saveState().toBase64().constData());
  3114. #ifdef BROWSER_AVAILABLE
  3115. SaveExtraBrowserDocks();
  3116. ClearExtraBrowserDocks();
  3117. #endif
  3118. if (api)
  3119. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3120. disableSaving++;
  3121. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3122. * sources, etc) so that all references are released before shutdown */
  3123. ClearSceneData();
  3124. App()->quit();
  3125. }
  3126. void OBSBasic::changeEvent(QEvent *event)
  3127. {
  3128. if (event->type() == QEvent::WindowStateChange && isMinimized() &&
  3129. trayIcon && trayIcon->isVisible() && sysTrayMinimizeToTray()) {
  3130. ToggleShowHide();
  3131. }
  3132. }
  3133. void OBSBasic::on_actionShow_Recordings_triggered()
  3134. {
  3135. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3136. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3137. const char *adv_path =
  3138. strcmp(type, "Standard")
  3139. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3140. : config_get_string(basicConfig, "AdvOut",
  3141. "RecFilePath");
  3142. const char *path = strcmp(mode, "Advanced")
  3143. ? config_get_string(basicConfig,
  3144. "SimpleOutput",
  3145. "FilePath")
  3146. : adv_path;
  3147. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3148. }
  3149. void OBSBasic::on_actionRemux_triggered()
  3150. {
  3151. if (!remux.isNull()) {
  3152. remux->show();
  3153. remux->raise();
  3154. return;
  3155. }
  3156. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3157. const char *path = strcmp(mode, "Advanced")
  3158. ? config_get_string(basicConfig,
  3159. "SimpleOutput",
  3160. "FilePath")
  3161. : config_get_string(basicConfig, "AdvOut",
  3162. "RecFilePath");
  3163. OBSRemux *remuxDlg;
  3164. remuxDlg = new OBSRemux(path, this);
  3165. remuxDlg->show();
  3166. remux = remuxDlg;
  3167. }
  3168. void OBSBasic::on_action_Settings_triggered()
  3169. {
  3170. static bool settings_already_executing = false;
  3171. /* Do not load settings window if inside of a temporary event loop
  3172. * because we could be inside of an Auth::LoadUI call. Keep trying
  3173. * once per second until we've exit any known sub-loops. */
  3174. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3175. QTimer::singleShot(1000, this,
  3176. SLOT(on_action_Settings_triggered()));
  3177. return;
  3178. }
  3179. if (settings_already_executing) {
  3180. return;
  3181. }
  3182. settings_already_executing = true;
  3183. OBSBasicSettings settings(this);
  3184. settings.exec();
  3185. SystemTray(false);
  3186. settings_already_executing = false;
  3187. }
  3188. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3189. {
  3190. if (advAudioWindow != nullptr) {
  3191. advAudioWindow->raise();
  3192. return;
  3193. }
  3194. advAudioWindow = new OBSBasicAdvAudio(this);
  3195. advAudioWindow->show();
  3196. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3197. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3198. SLOT(on_advAudioProps_destroyed()));
  3199. }
  3200. void OBSBasic::on_advAudioProps_clicked()
  3201. {
  3202. on_actionAdvAudioProperties_triggered();
  3203. }
  3204. void OBSBasic::on_advAudioProps_destroyed()
  3205. {
  3206. advAudioWindow = nullptr;
  3207. }
  3208. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3209. QListWidgetItem *prev)
  3210. {
  3211. obs_source_t *source = NULL;
  3212. if (sceneChanging)
  3213. return;
  3214. if (current) {
  3215. obs_scene_t *scene;
  3216. scene = GetOBSRef<OBSScene>(current);
  3217. source = obs_scene_get_source(scene);
  3218. }
  3219. SetCurrentScene(source);
  3220. if (api)
  3221. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3222. UNUSED_PARAMETER(prev);
  3223. }
  3224. void OBSBasic::EditSceneName()
  3225. {
  3226. QListWidgetItem *item = ui->scenes->currentItem();
  3227. Qt::ItemFlags flags = item->flags();
  3228. item->setFlags(flags | Qt::ItemIsEditable);
  3229. ui->scenes->editItem(item);
  3230. item->setFlags(flags);
  3231. }
  3232. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3233. const char *slot)
  3234. {
  3235. QAction *action;
  3236. QList<QScreen *> screens = QGuiApplication::screens();
  3237. for (int i = 0; i < screens.size(); i++) {
  3238. QRect screenGeometry = screens[i]->geometry();
  3239. QString str =
  3240. QString("%1 %2: %3x%4 @ %5,%6")
  3241. .arg(QTStr("Display"), QString::number(i + 1),
  3242. QString::number(screenGeometry.width()),
  3243. QString::number(screenGeometry.height()),
  3244. QString::number(screenGeometry.x()),
  3245. QString::number(screenGeometry.y()));
  3246. action = parent->addAction(str, target, slot);
  3247. action->setProperty("monitor", i);
  3248. }
  3249. }
  3250. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3251. {
  3252. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3253. QMenu popup(this);
  3254. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3255. popup.addAction(QTStr("Add"), this,
  3256. SLOT(on_actionAddScene_triggered()));
  3257. if (item) {
  3258. QAction *pasteFilters =
  3259. new QAction(QTStr("Paste.Filters"), this);
  3260. pasteFilters->setEnabled(copyFiltersString);
  3261. connect(pasteFilters, SIGNAL(triggered()), this,
  3262. SLOT(ScenePasteFilters()));
  3263. popup.addSeparator();
  3264. popup.addAction(QTStr("Duplicate"), this,
  3265. SLOT(DuplicateSelectedScene()));
  3266. popup.addAction(QTStr("Copy.Filters"), this,
  3267. SLOT(SceneCopyFilters()));
  3268. popup.addAction(pasteFilters);
  3269. popup.addSeparator();
  3270. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3271. popup.addAction(QTStr("Remove"), this,
  3272. SLOT(RemoveSelectedScene()));
  3273. popup.addSeparator();
  3274. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3275. SLOT(on_actionSceneUp_triggered()));
  3276. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3277. this, SLOT(on_actionSceneDown_triggered()));
  3278. order.addSeparator();
  3279. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3280. this, SLOT(MoveSceneToTop()));
  3281. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3282. this, SLOT(MoveSceneToBottom()));
  3283. popup.addMenu(&order);
  3284. popup.addSeparator();
  3285. delete sceneProjectorMenu;
  3286. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3287. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3288. SLOT(OpenSceneProjector()));
  3289. popup.addMenu(sceneProjectorMenu);
  3290. QAction *sceneWindow = popup.addAction(
  3291. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3292. popup.addAction(sceneWindow);
  3293. popup.addSeparator();
  3294. popup.addAction(QTStr("Filters"), this,
  3295. SLOT(OpenSceneFilters()));
  3296. popup.addSeparator();
  3297. delete perSceneTransitionMenu;
  3298. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3299. popup.addMenu(perSceneTransitionMenu);
  3300. /* ---------------------- */
  3301. QAction *multiviewAction =
  3302. popup.addAction(QTStr("ShowInMultiview"));
  3303. OBSSource source = GetCurrentSceneSource();
  3304. OBSData data = obs_source_get_private_settings(source);
  3305. obs_data_release(data);
  3306. obs_data_set_default_bool(data, "show_in_multiview", true);
  3307. bool show = obs_data_get_bool(data, "show_in_multiview");
  3308. multiviewAction->setCheckable(true);
  3309. multiviewAction->setChecked(show);
  3310. auto showInMultiview = [](OBSData data) {
  3311. bool show =
  3312. obs_data_get_bool(data, "show_in_multiview");
  3313. obs_data_set_bool(data, "show_in_multiview", !show);
  3314. OBSProjector::UpdateMultiviewProjectors();
  3315. };
  3316. connect(multiviewAction, &QAction::triggered,
  3317. std::bind(showInMultiview, data));
  3318. }
  3319. popup.exec(QCursor::pos());
  3320. }
  3321. void OBSBasic::on_actionAddScene_triggered()
  3322. {
  3323. string name;
  3324. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3325. int i = 2;
  3326. QString placeHolderText = format.arg(i);
  3327. obs_source_t *source = nullptr;
  3328. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3329. obs_source_release(source);
  3330. placeHolderText = format.arg(++i);
  3331. }
  3332. bool accepted = NameDialog::AskForName(
  3333. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3334. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  3335. if (accepted) {
  3336. if (name.empty()) {
  3337. OBSMessageBox::warning(this,
  3338. QTStr("NoNameEntered.Title"),
  3339. QTStr("NoNameEntered.Text"));
  3340. on_actionAddScene_triggered();
  3341. return;
  3342. }
  3343. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3344. if (source) {
  3345. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3346. QTStr("NameExists.Text"));
  3347. obs_source_release(source);
  3348. on_actionAddScene_triggered();
  3349. return;
  3350. }
  3351. obs_scene_t *scene = obs_scene_create(name.c_str());
  3352. source = obs_scene_get_source(scene);
  3353. SetCurrentScene(source);
  3354. obs_scene_release(scene);
  3355. }
  3356. }
  3357. void OBSBasic::on_actionRemoveScene_triggered()
  3358. {
  3359. OBSScene scene = GetCurrentScene();
  3360. obs_source_t *source = obs_scene_get_source(scene);
  3361. if (source && QueryRemoveSource(source))
  3362. obs_source_remove(source);
  3363. }
  3364. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3365. {
  3366. int idx = ui->scenes->currentRow();
  3367. if (idx == -1 || idx == invalidIdx)
  3368. return;
  3369. sceneChanging = true;
  3370. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3371. if (!relative)
  3372. idx = 0;
  3373. ui->scenes->insertItem(idx + offset, item);
  3374. ui->scenes->setCurrentRow(idx + offset);
  3375. item->setSelected(true);
  3376. sceneChanging = false;
  3377. OBSProjector::UpdateMultiviewProjectors();
  3378. }
  3379. void OBSBasic::on_actionSceneUp_triggered()
  3380. {
  3381. ChangeSceneIndex(true, -1, 0);
  3382. }
  3383. void OBSBasic::on_actionSceneDown_triggered()
  3384. {
  3385. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3386. }
  3387. void OBSBasic::MoveSceneToTop()
  3388. {
  3389. ChangeSceneIndex(false, 0, 0);
  3390. }
  3391. void OBSBasic::MoveSceneToBottom()
  3392. {
  3393. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3394. ui->scenes->count() - 1);
  3395. }
  3396. void OBSBasic::EditSceneItemName()
  3397. {
  3398. int idx = GetTopSelectedSourceItem();
  3399. ui->sources->Edit(idx);
  3400. }
  3401. void OBSBasic::SetDeinterlacingMode()
  3402. {
  3403. QAction *action = reinterpret_cast<QAction *>(sender());
  3404. obs_deinterlace_mode mode =
  3405. (obs_deinterlace_mode)action->property("mode").toInt();
  3406. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3407. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3408. obs_source_set_deinterlace_mode(source, mode);
  3409. }
  3410. void OBSBasic::SetDeinterlacingOrder()
  3411. {
  3412. QAction *action = reinterpret_cast<QAction *>(sender());
  3413. obs_deinterlace_field_order order =
  3414. (obs_deinterlace_field_order)action->property("order").toInt();
  3415. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3416. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3417. obs_source_set_deinterlace_field_order(source, order);
  3418. }
  3419. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3420. {
  3421. obs_deinterlace_mode deinterlaceMode =
  3422. obs_source_get_deinterlace_mode(source);
  3423. obs_deinterlace_field_order deinterlaceOrder =
  3424. obs_source_get_deinterlace_field_order(source);
  3425. QAction *action;
  3426. #define ADD_MODE(name, mode) \
  3427. action = menu->addAction(QTStr("" name), this, \
  3428. SLOT(SetDeinterlacingMode())); \
  3429. action->setProperty("mode", (int)mode); \
  3430. action->setCheckable(true); \
  3431. action->setChecked(deinterlaceMode == mode);
  3432. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3433. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3434. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3435. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3436. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3437. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3438. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3439. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3440. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3441. #undef ADD_MODE
  3442. menu->addSeparator();
  3443. #define ADD_ORDER(name, order) \
  3444. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3445. SLOT(SetDeinterlacingOrder())); \
  3446. action->setProperty("order", (int)order); \
  3447. action->setCheckable(true); \
  3448. action->setChecked(deinterlaceOrder == order);
  3449. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3450. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3451. #undef ADD_ORDER
  3452. return menu;
  3453. }
  3454. void OBSBasic::SetScaleFilter()
  3455. {
  3456. QAction *action = reinterpret_cast<QAction *>(sender());
  3457. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3458. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3459. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3460. }
  3461. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3462. {
  3463. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3464. QAction *action;
  3465. #define ADD_MODE(name, mode) \
  3466. action = \
  3467. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  3468. action->setProperty("mode", (int)mode); \
  3469. action->setCheckable(true); \
  3470. action->setChecked(scaleFilter == mode);
  3471. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3472. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3473. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3474. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3475. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3476. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3477. #undef ADD_MODE
  3478. return menu;
  3479. }
  3480. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  3481. QWidgetAction *widgetAction,
  3482. ColorSelect *select,
  3483. obs_sceneitem_t *item)
  3484. {
  3485. QAction *action;
  3486. menu->setStyleSheet(QString(
  3487. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  3488. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  3489. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  3490. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  3491. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  3492. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  3493. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  3494. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3495. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3496. obs_data_release(privData);
  3497. obs_data_set_default_int(privData, "color-preset", 0);
  3498. int preset = obs_data_get_int(privData, "color-preset");
  3499. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  3500. action->setCheckable(true);
  3501. action->setProperty("bgColor", 0);
  3502. action->setChecked(preset == 0);
  3503. action = menu->addAction(QTStr("CustomColor"), this,
  3504. +SLOT(ColorChange()));
  3505. action->setCheckable(true);
  3506. action->setProperty("bgColor", 1);
  3507. action->setChecked(preset == 1);
  3508. menu->addSeparator();
  3509. widgetAction->setDefaultWidget(select);
  3510. for (int i = 1; i < 9; i++) {
  3511. stringstream button;
  3512. button << "preset" << i;
  3513. QPushButton *colorButton =
  3514. select->findChild<QPushButton *>(button.str().c_str());
  3515. if (preset == i + 1)
  3516. colorButton->setStyleSheet("border: 2px solid black");
  3517. colorButton->setProperty("bgColor", i);
  3518. select->connect(colorButton, SIGNAL(released()), this,
  3519. SLOT(ColorChange()));
  3520. }
  3521. menu->addAction(widgetAction);
  3522. return menu;
  3523. }
  3524. ColorSelect::ColorSelect(QWidget *parent)
  3525. : QWidget(parent), ui(new Ui::ColorSelect)
  3526. {
  3527. ui->setupUi(this);
  3528. }
  3529. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3530. {
  3531. QMenu popup(this);
  3532. delete previewProjectorSource;
  3533. delete sourceProjector;
  3534. delete scaleFilteringMenu;
  3535. delete colorMenu;
  3536. delete colorWidgetAction;
  3537. delete colorSelect;
  3538. delete deinterlaceMenu;
  3539. if (preview) {
  3540. QAction *action = popup.addAction(
  3541. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  3542. SLOT(TogglePreview()));
  3543. action->setCheckable(true);
  3544. action->setChecked(
  3545. obs_display_enabled(ui->preview->GetDisplay()));
  3546. if (IsPreviewProgramMode())
  3547. action->setEnabled(false);
  3548. popup.addAction(ui->actionLockPreview);
  3549. popup.addMenu(ui->scalingMenu);
  3550. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3551. AddProjectorMenuMonitors(previewProjectorSource, this,
  3552. SLOT(OpenPreviewProjector()));
  3553. popup.addMenu(previewProjectorSource);
  3554. QAction *previewWindow =
  3555. popup.addAction(QTStr("PreviewWindow"), this,
  3556. SLOT(OpenPreviewWindow()));
  3557. popup.addAction(previewWindow);
  3558. popup.addSeparator();
  3559. }
  3560. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3561. if (addSourceMenu)
  3562. popup.addMenu(addSourceMenu);
  3563. ui->actionCopyFilters->setEnabled(false);
  3564. ui->actionCopySource->setEnabled(false);
  3565. if (ui->sources->MultipleBaseSelected()) {
  3566. popup.addSeparator();
  3567. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  3568. SLOT(GroupSelectedItems()));
  3569. } else if (ui->sources->GroupsSelected()) {
  3570. popup.addSeparator();
  3571. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  3572. SLOT(UngroupSelectedGroups()));
  3573. }
  3574. popup.addSeparator();
  3575. popup.addAction(ui->actionCopySource);
  3576. popup.addAction(ui->actionPasteRef);
  3577. popup.addAction(ui->actionPasteDup);
  3578. popup.addSeparator();
  3579. popup.addSeparator();
  3580. popup.addAction(ui->actionCopyFilters);
  3581. popup.addAction(ui->actionPasteFilters);
  3582. popup.addSeparator();
  3583. if (idx != -1) {
  3584. if (addSourceMenu)
  3585. popup.addSeparator();
  3586. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3587. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3588. uint32_t flags = obs_source_get_output_flags(source);
  3589. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3590. OBS_SOURCE_ASYNC_VIDEO;
  3591. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  3592. QAction *action;
  3593. colorMenu = new QMenu(QTStr("ChangeBG"));
  3594. colorWidgetAction = new QWidgetAction(colorMenu);
  3595. colorSelect = new ColorSelect(colorMenu);
  3596. popup.addMenu(AddBackgroundColorMenu(
  3597. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  3598. popup.addAction(QTStr("Rename"), this,
  3599. SLOT(EditSceneItemName()));
  3600. popup.addAction(QTStr("Remove"), this,
  3601. SLOT(on_actionRemoveSource_triggered()));
  3602. popup.addSeparator();
  3603. popup.addMenu(ui->orderMenu);
  3604. popup.addMenu(ui->transformMenu);
  3605. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3606. AddProjectorMenuMonitors(sourceProjector, this,
  3607. SLOT(OpenSourceProjector()));
  3608. QAction *sourceWindow = popup.addAction(
  3609. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  3610. popup.addAction(sourceWindow);
  3611. popup.addSeparator();
  3612. if (hasAudio) {
  3613. QAction *actionHideMixer =
  3614. popup.addAction(QTStr("HideMixer"), this,
  3615. SLOT(ToggleHideMixer()));
  3616. actionHideMixer->setCheckable(true);
  3617. actionHideMixer->setChecked(SourceMixerHidden(source));
  3618. }
  3619. if (isAsyncVideo) {
  3620. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3621. popup.addMenu(
  3622. AddDeinterlacingMenu(deinterlaceMenu, source));
  3623. popup.addSeparator();
  3624. }
  3625. QAction *resizeOutput =
  3626. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  3627. SLOT(ResizeOutputSizeOfSource()));
  3628. int width = obs_source_get_width(source);
  3629. int height = obs_source_get_height(source);
  3630. resizeOutput->setEnabled(!obs_video_active());
  3631. if (width == 0 || height == 0)
  3632. resizeOutput->setEnabled(false);
  3633. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3634. popup.addMenu(
  3635. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3636. popup.addSeparator();
  3637. popup.addMenu(sourceProjector);
  3638. popup.addAction(sourceWindow);
  3639. popup.addSeparator();
  3640. action = popup.addAction(QTStr("Interact"), this,
  3641. SLOT(on_actionInteract_triggered()));
  3642. action->setEnabled(obs_source_get_output_flags(source) &
  3643. OBS_SOURCE_INTERACTION);
  3644. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  3645. popup.addAction(QTStr("Properties"), this,
  3646. SLOT(on_actionSourceProperties_triggered()));
  3647. ui->actionCopyFilters->setEnabled(true);
  3648. ui->actionCopySource->setEnabled(true);
  3649. } else {
  3650. ui->actionPasteFilters->setEnabled(false);
  3651. }
  3652. popup.exec(QCursor::pos());
  3653. }
  3654. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3655. {
  3656. if (ui->scenes->count()) {
  3657. QModelIndex idx = ui->sources->indexAt(pos);
  3658. CreateSourcePopupMenu(idx.row(), false);
  3659. }
  3660. }
  3661. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3662. {
  3663. if (!witem)
  3664. return;
  3665. if (IsPreviewProgramMode()) {
  3666. bool doubleClickSwitch =
  3667. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  3668. "TransitionOnDoubleClick");
  3669. if (doubleClickSwitch) {
  3670. OBSScene scene = GetCurrentScene();
  3671. if (scene)
  3672. SetCurrentScene(scene, false, true);
  3673. }
  3674. }
  3675. }
  3676. void OBSBasic::AddSource(const char *id)
  3677. {
  3678. if (id && *id) {
  3679. OBSBasicSourceSelect sourceSelect(this, id);
  3680. sourceSelect.exec();
  3681. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3682. CreatePropertiesWindow(sourceSelect.newSource);
  3683. }
  3684. }
  3685. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3686. {
  3687. const char *type;
  3688. bool foundValues = false;
  3689. bool foundDeprecated = false;
  3690. size_t idx = 0;
  3691. QMenu *popup = new QMenu(QTStr("Add"), this);
  3692. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3693. auto getActionAfter = [](QMenu *menu, const QString &name) {
  3694. QList<QAction *> actions = menu->actions();
  3695. for (QAction *menuAction : actions) {
  3696. if (menuAction->text().compare(name) >= 0)
  3697. return menuAction;
  3698. }
  3699. return (QAction *)nullptr;
  3700. };
  3701. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  3702. const char *name) {
  3703. QString qname = QT_UTF8(name);
  3704. QAction *popupItem = new QAction(qname, this);
  3705. popupItem->setData(QT_UTF8(type));
  3706. connect(popupItem, SIGNAL(triggered(bool)), this,
  3707. SLOT(AddSourceFromAction()));
  3708. QAction *after = getActionAfter(popup, qname);
  3709. popup->insertAction(after, popupItem);
  3710. };
  3711. while (obs_enum_input_types(idx++, &type)) {
  3712. const char *name = obs_source_get_display_name(type);
  3713. uint32_t caps = obs_get_source_output_flags(type);
  3714. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3715. continue;
  3716. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3717. addSource(popup, type, name);
  3718. } else {
  3719. addSource(deprecated, type, name);
  3720. foundDeprecated = true;
  3721. }
  3722. foundValues = true;
  3723. }
  3724. addSource(popup, "scene", Str("Basic.Scene"));
  3725. popup->addSeparator();
  3726. QAction *addGroup = new QAction(QTStr("Group"), this);
  3727. addGroup->setData(QT_UTF8("group"));
  3728. connect(addGroup, SIGNAL(triggered(bool)), this,
  3729. SLOT(AddSourceFromAction()));
  3730. popup->addAction(addGroup);
  3731. if (!foundDeprecated) {
  3732. delete deprecated;
  3733. deprecated = nullptr;
  3734. }
  3735. if (!foundValues) {
  3736. delete popup;
  3737. popup = nullptr;
  3738. } else if (foundDeprecated) {
  3739. popup->addSeparator();
  3740. popup->addMenu(deprecated);
  3741. }
  3742. return popup;
  3743. }
  3744. void OBSBasic::AddSourceFromAction()
  3745. {
  3746. QAction *action = qobject_cast<QAction *>(sender());
  3747. if (!action)
  3748. return;
  3749. AddSource(QT_TO_UTF8(action->data().toString()));
  3750. }
  3751. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3752. {
  3753. if (!GetCurrentScene()) {
  3754. // Tell the user he needs a scene first (help beginners).
  3755. OBSMessageBox::information(
  3756. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  3757. QTStr("Basic.Main.AddSourceHelp.Text"));
  3758. return;
  3759. }
  3760. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3761. if (popup)
  3762. popup->exec(pos);
  3763. }
  3764. void OBSBasic::on_actionAddSource_triggered()
  3765. {
  3766. AddSourcePopupMenu(QCursor::pos());
  3767. }
  3768. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3769. {
  3770. vector<OBSSceneItem> &items =
  3771. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  3772. if (obs_sceneitem_selected(item)) {
  3773. items.emplace_back(item);
  3774. } else if (obs_sceneitem_is_group(item)) {
  3775. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3776. }
  3777. return true;
  3778. };
  3779. void OBSBasic::on_actionRemoveSource_triggered()
  3780. {
  3781. vector<OBSSceneItem> items;
  3782. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3783. if (!items.size())
  3784. return;
  3785. auto removeMultiple = [this](size_t count) {
  3786. QString text = QTStr("ConfirmRemove.TextMultiple")
  3787. .arg(QString::number(count));
  3788. QMessageBox remove_items(this);
  3789. remove_items.setText(text);
  3790. QAbstractButton *Yes = remove_items.addButton(
  3791. QTStr("Yes"), QMessageBox::YesRole);
  3792. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3793. remove_items.setIcon(QMessageBox::Question);
  3794. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3795. remove_items.exec();
  3796. return Yes == remove_items.clickedButton();
  3797. };
  3798. if (items.size() == 1) {
  3799. OBSSceneItem &item = items[0];
  3800. obs_source_t *source = obs_sceneitem_get_source(item);
  3801. if (source && QueryRemoveSource(source))
  3802. obs_sceneitem_remove(item);
  3803. } else {
  3804. if (removeMultiple(items.size())) {
  3805. for (auto &item : items)
  3806. obs_sceneitem_remove(item);
  3807. }
  3808. }
  3809. }
  3810. void OBSBasic::on_actionInteract_triggered()
  3811. {
  3812. OBSSceneItem item = GetCurrentSceneItem();
  3813. OBSSource source = obs_sceneitem_get_source(item);
  3814. if (source)
  3815. CreateInteractionWindow(source);
  3816. }
  3817. void OBSBasic::on_actionSourceProperties_triggered()
  3818. {
  3819. OBSSceneItem item = GetCurrentSceneItem();
  3820. OBSSource source = obs_sceneitem_get_source(item);
  3821. if (source)
  3822. CreatePropertiesWindow(source);
  3823. }
  3824. void OBSBasic::on_actionSourceUp_triggered()
  3825. {
  3826. OBSSceneItem item = GetCurrentSceneItem();
  3827. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3828. }
  3829. void OBSBasic::on_actionSourceDown_triggered()
  3830. {
  3831. OBSSceneItem item = GetCurrentSceneItem();
  3832. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3833. }
  3834. void OBSBasic::on_actionMoveUp_triggered()
  3835. {
  3836. OBSSceneItem item = GetCurrentSceneItem();
  3837. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3838. }
  3839. void OBSBasic::on_actionMoveDown_triggered()
  3840. {
  3841. OBSSceneItem item = GetCurrentSceneItem();
  3842. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3843. }
  3844. void OBSBasic::on_actionMoveToTop_triggered()
  3845. {
  3846. OBSSceneItem item = GetCurrentSceneItem();
  3847. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3848. }
  3849. void OBSBasic::on_actionMoveToBottom_triggered()
  3850. {
  3851. OBSSceneItem item = GetCurrentSceneItem();
  3852. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3853. }
  3854. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3855. {
  3856. char logDir[512];
  3857. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3858. return nullptr;
  3859. string path = logDir;
  3860. path += "/";
  3861. path += log;
  3862. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3863. if (!file)
  3864. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3865. return file;
  3866. }
  3867. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3868. {
  3869. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3870. if (!fileString)
  3871. return;
  3872. if (!*fileString)
  3873. return;
  3874. ui->menuLogFiles->setEnabled(false);
  3875. stringstream ss;
  3876. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  3877. << CurrentDateTimeString() << "\n\n"
  3878. << fileString;
  3879. if (logUploadThread) {
  3880. logUploadThread->wait();
  3881. }
  3882. RemoteTextThread *thread =
  3883. new RemoteTextThread("https://obsproject.com/logs/upload",
  3884. "text/plain", ss.str().c_str());
  3885. logUploadThread.reset(thread);
  3886. connect(thread, &RemoteTextThread::Result, this,
  3887. &OBSBasic::logUploadFinished);
  3888. logUploadThread->start();
  3889. }
  3890. void OBSBasic::on_actionShowLogs_triggered()
  3891. {
  3892. char logDir[512];
  3893. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3894. return;
  3895. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3896. QDesktopServices::openUrl(url);
  3897. }
  3898. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3899. {
  3900. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3901. }
  3902. void OBSBasic::on_actionUploadLastLog_triggered()
  3903. {
  3904. UploadLog("obs-studio/logs", App()->GetLastLog());
  3905. }
  3906. void OBSBasic::on_actionViewCurrentLog_triggered()
  3907. {
  3908. char logDir[512];
  3909. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3910. return;
  3911. const char *log = App()->GetCurrentLog();
  3912. string path = logDir;
  3913. path += "/";
  3914. path += log;
  3915. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3916. QDesktopServices::openUrl(url);
  3917. }
  3918. void OBSBasic::on_actionShowCrashLogs_triggered()
  3919. {
  3920. char logDir[512];
  3921. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  3922. return;
  3923. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3924. QDesktopServices::openUrl(url);
  3925. }
  3926. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  3927. {
  3928. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  3929. }
  3930. void OBSBasic::on_actionCheckForUpdates_triggered()
  3931. {
  3932. CheckForUpdates(true);
  3933. }
  3934. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3935. {
  3936. ui->menuLogFiles->setEnabled(true);
  3937. if (text.isEmpty()) {
  3938. OBSMessageBox::critical(
  3939. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  3940. error);
  3941. return;
  3942. }
  3943. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3944. string resURL = obs_data_get_string(returnData, "url");
  3945. QString logURL = resURL.c_str();
  3946. obs_data_release(returnData);
  3947. OBSLogReply logDialog(this, logURL);
  3948. logDialog.exec();
  3949. }
  3950. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3951. obs_source_t *source, const string &name)
  3952. {
  3953. const char *prevName = obs_source_get_name(source);
  3954. if (name == prevName)
  3955. return;
  3956. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3957. QListWidgetItem *listItem = listWidget->currentItem();
  3958. if (foundSource || name.empty()) {
  3959. listItem->setText(QT_UTF8(prevName));
  3960. if (foundSource) {
  3961. OBSMessageBox::warning(parent,
  3962. QTStr("NameExists.Title"),
  3963. QTStr("NameExists.Text"));
  3964. } else if (name.empty()) {
  3965. OBSMessageBox::warning(parent,
  3966. QTStr("NoNameEntered.Title"),
  3967. QTStr("NoNameEntered.Text"));
  3968. }
  3969. obs_source_release(foundSource);
  3970. } else {
  3971. listItem->setText(QT_UTF8(name.c_str()));
  3972. obs_source_set_name(source, name.c_str());
  3973. }
  3974. }
  3975. void OBSBasic::SceneNameEdited(QWidget *editor,
  3976. QAbstractItemDelegate::EndEditHint endHint)
  3977. {
  3978. OBSScene scene = GetCurrentScene();
  3979. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  3980. string text = QT_TO_UTF8(edit->text().trimmed());
  3981. if (!scene)
  3982. return;
  3983. obs_source_t *source = obs_scene_get_source(scene);
  3984. RenameListItem(this, ui->scenes, source, text);
  3985. if (api)
  3986. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3987. UNUSED_PARAMETER(endHint);
  3988. }
  3989. void OBSBasic::OpenFilters()
  3990. {
  3991. OBSSceneItem item = GetCurrentSceneItem();
  3992. OBSSource source = obs_sceneitem_get_source(item);
  3993. CreateFiltersWindow(source);
  3994. }
  3995. void OBSBasic::OpenSceneFilters()
  3996. {
  3997. OBSScene scene = GetCurrentScene();
  3998. OBSSource source = obs_scene_get_source(scene);
  3999. CreateFiltersWindow(source);
  4000. }
  4001. #define RECORDING_START \
  4002. "==== Recording Start ==============================================="
  4003. #define RECORDING_STOP \
  4004. "==== Recording Stop ================================================"
  4005. #define REPLAY_BUFFER_START \
  4006. "==== Replay Buffer Start ==========================================="
  4007. #define REPLAY_BUFFER_STOP \
  4008. "==== Replay Buffer Stop ============================================"
  4009. #define STREAMING_START \
  4010. "==== Streaming Start ==============================================="
  4011. #define STREAMING_STOP \
  4012. "==== Streaming Stop ================================================"
  4013. void OBSBasic::StartStreaming()
  4014. {
  4015. if (outputHandler->StreamingActive())
  4016. return;
  4017. if (disableOutputsRef)
  4018. return;
  4019. if (api)
  4020. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4021. SaveProject();
  4022. ui->streamButton->setEnabled(false);
  4023. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4024. if (sysTrayStream) {
  4025. sysTrayStream->setEnabled(false);
  4026. sysTrayStream->setText(ui->streamButton->text());
  4027. }
  4028. if (!outputHandler->StartStreaming(service)) {
  4029. QString message =
  4030. !outputHandler->lastError.empty()
  4031. ? QTStr(outputHandler->lastError.c_str())
  4032. : QTStr("Output.StartFailedGeneric");
  4033. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4034. ui->streamButton->setEnabled(true);
  4035. ui->streamButton->setChecked(false);
  4036. if (sysTrayStream) {
  4037. sysTrayStream->setText(ui->streamButton->text());
  4038. sysTrayStream->setEnabled(true);
  4039. }
  4040. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
  4041. message);
  4042. return;
  4043. }
  4044. bool recordWhenStreaming = config_get_bool(
  4045. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4046. if (recordWhenStreaming)
  4047. StartRecording();
  4048. bool replayBufferWhileStreaming = config_get_bool(
  4049. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4050. if (replayBufferWhileStreaming)
  4051. StartReplayBuffer();
  4052. }
  4053. #ifdef _WIN32
  4054. static inline void UpdateProcessPriority()
  4055. {
  4056. const char *priority = config_get_string(App()->GlobalConfig(),
  4057. "General", "ProcessPriority");
  4058. if (priority && strcmp(priority, "Normal") != 0)
  4059. SetProcessPriority(priority);
  4060. }
  4061. static inline void ClearProcessPriority()
  4062. {
  4063. const char *priority = config_get_string(App()->GlobalConfig(),
  4064. "General", "ProcessPriority");
  4065. if (priority && strcmp(priority, "Normal") != 0)
  4066. SetProcessPriority("Normal");
  4067. }
  4068. #else
  4069. #define UpdateProcessPriority() \
  4070. do { \
  4071. } while (false)
  4072. #define ClearProcessPriority() \
  4073. do { \
  4074. } while (false)
  4075. #endif
  4076. inline void OBSBasic::OnActivate()
  4077. {
  4078. if (ui->profileMenu->isEnabled()) {
  4079. ui->profileMenu->setEnabled(false);
  4080. ui->autoConfigure->setEnabled(false);
  4081. App()->IncrementSleepInhibition();
  4082. UpdateProcessPriority();
  4083. if (trayIcon)
  4084. trayIcon->setIcon(QIcon::fromTheme(
  4085. "obs-tray-active",
  4086. QIcon(":/res/images/tray_active.png")));
  4087. }
  4088. }
  4089. inline void OBSBasic::OnDeactivate()
  4090. {
  4091. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4092. ui->profileMenu->setEnabled(true);
  4093. ui->autoConfigure->setEnabled(true);
  4094. App()->DecrementSleepInhibition();
  4095. ClearProcessPriority();
  4096. if (trayIcon)
  4097. trayIcon->setIcon(QIcon::fromTheme(
  4098. "obs-tray", QIcon(":/res/images/obs.png")));
  4099. }
  4100. }
  4101. void OBSBasic::StopStreaming()
  4102. {
  4103. SaveProject();
  4104. if (outputHandler->StreamingActive())
  4105. outputHandler->StopStreaming(streamingStopping);
  4106. OnDeactivate();
  4107. bool recordWhenStreaming = config_get_bool(
  4108. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4109. bool keepRecordingWhenStreamStops =
  4110. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4111. "KeepRecordingWhenStreamStops");
  4112. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4113. StopRecording();
  4114. bool replayBufferWhileStreaming = config_get_bool(
  4115. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4116. bool keepReplayBufferStreamStops =
  4117. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4118. "KeepReplayBufferStreamStops");
  4119. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4120. StopReplayBuffer();
  4121. }
  4122. void OBSBasic::ForceStopStreaming()
  4123. {
  4124. SaveProject();
  4125. if (outputHandler->StreamingActive())
  4126. outputHandler->StopStreaming(true);
  4127. OnDeactivate();
  4128. bool recordWhenStreaming = config_get_bool(
  4129. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4130. bool keepRecordingWhenStreamStops =
  4131. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4132. "KeepRecordingWhenStreamStops");
  4133. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4134. StopRecording();
  4135. bool replayBufferWhileStreaming = config_get_bool(
  4136. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4137. bool keepReplayBufferStreamStops =
  4138. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4139. "KeepReplayBufferStreamStops");
  4140. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4141. StopReplayBuffer();
  4142. }
  4143. void OBSBasic::StreamDelayStarting(int sec)
  4144. {
  4145. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4146. ui->streamButton->setEnabled(true);
  4147. ui->streamButton->setChecked(true);
  4148. if (sysTrayStream) {
  4149. sysTrayStream->setText(ui->streamButton->text());
  4150. sysTrayStream->setEnabled(true);
  4151. }
  4152. if (!startStreamMenu.isNull())
  4153. startStreamMenu->deleteLater();
  4154. startStreamMenu = new QMenu();
  4155. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  4156. SLOT(StopStreaming()));
  4157. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4158. SLOT(ForceStopStreaming()));
  4159. ui->streamButton->setMenu(startStreamMenu);
  4160. ui->statusbar->StreamDelayStarting(sec);
  4161. OnActivate();
  4162. }
  4163. void OBSBasic::StreamDelayStopping(int sec)
  4164. {
  4165. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4166. ui->streamButton->setEnabled(true);
  4167. ui->streamButton->setChecked(false);
  4168. if (sysTrayStream) {
  4169. sysTrayStream->setText(ui->streamButton->text());
  4170. sysTrayStream->setEnabled(true);
  4171. }
  4172. if (!startStreamMenu.isNull())
  4173. startStreamMenu->deleteLater();
  4174. startStreamMenu = new QMenu();
  4175. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  4176. SLOT(StartStreaming()));
  4177. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4178. SLOT(ForceStopStreaming()));
  4179. ui->streamButton->setMenu(startStreamMenu);
  4180. ui->statusbar->StreamDelayStopping(sec);
  4181. if (api)
  4182. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4183. }
  4184. void OBSBasic::StreamingStart()
  4185. {
  4186. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4187. ui->streamButton->setEnabled(true);
  4188. ui->streamButton->setChecked(true);
  4189. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4190. if (sysTrayStream) {
  4191. sysTrayStream->setText(ui->streamButton->text());
  4192. sysTrayStream->setEnabled(true);
  4193. }
  4194. if (api)
  4195. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4196. OnActivate();
  4197. blog(LOG_INFO, STREAMING_START);
  4198. }
  4199. void OBSBasic::StreamStopping()
  4200. {
  4201. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4202. if (sysTrayStream)
  4203. sysTrayStream->setText(ui->streamButton->text());
  4204. streamingStopping = true;
  4205. if (api)
  4206. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4207. }
  4208. void OBSBasic::StreamingStop(int code, QString last_error)
  4209. {
  4210. const char *errorDescription = "";
  4211. DStr errorMessage;
  4212. bool use_last_error = false;
  4213. bool encode_error = false;
  4214. switch (code) {
  4215. case OBS_OUTPUT_BAD_PATH:
  4216. errorDescription = Str("Output.ConnectFail.BadPath");
  4217. break;
  4218. case OBS_OUTPUT_CONNECT_FAILED:
  4219. use_last_error = true;
  4220. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4221. break;
  4222. case OBS_OUTPUT_INVALID_STREAM:
  4223. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4224. break;
  4225. case OBS_OUTPUT_ENCODE_ERROR:
  4226. encode_error = true;
  4227. break;
  4228. default:
  4229. case OBS_OUTPUT_ERROR:
  4230. use_last_error = true;
  4231. errorDescription = Str("Output.ConnectFail.Error");
  4232. break;
  4233. case OBS_OUTPUT_DISCONNECTED:
  4234. /* doesn't happen if output is set to reconnect. note that
  4235. * reconnects are handled in the output, not in the UI */
  4236. use_last_error = true;
  4237. errorDescription = Str("Output.ConnectFail.Disconnected");
  4238. }
  4239. if (use_last_error && !last_error.isEmpty())
  4240. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4241. QT_TO_UTF8(last_error));
  4242. else
  4243. dstr_copy(errorMessage, errorDescription);
  4244. ui->statusbar->StreamStopped();
  4245. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4246. ui->streamButton->setEnabled(true);
  4247. ui->streamButton->setChecked(false);
  4248. if (sysTrayStream) {
  4249. sysTrayStream->setText(ui->streamButton->text());
  4250. sysTrayStream->setEnabled(true);
  4251. }
  4252. streamingStopping = false;
  4253. if (api)
  4254. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4255. OnDeactivate();
  4256. blog(LOG_INFO, STREAMING_STOP);
  4257. if (encode_error) {
  4258. OBSMessageBox::information(
  4259. this, QTStr("Output.StreamEncodeError.Title"),
  4260. QTStr("Output.StreamEncodeError.Msg"));
  4261. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4262. OBSMessageBox::information(this,
  4263. QTStr("Output.ConnectFail.Title"),
  4264. QT_UTF8(errorMessage));
  4265. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4266. SysTrayNotify(QT_UTF8(errorDescription),
  4267. QSystemTrayIcon::Warning);
  4268. }
  4269. if (!startStreamMenu.isNull()) {
  4270. ui->streamButton->setMenu(nullptr);
  4271. startStreamMenu->deleteLater();
  4272. startStreamMenu = nullptr;
  4273. }
  4274. }
  4275. void OBSBasic::AutoRemux()
  4276. {
  4277. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4278. bool advanced = astrcmpi(mode, "Advanced") == 0;
  4279. const char *path = !advanced ? config_get_string(basicConfig,
  4280. "SimpleOutput",
  4281. "FilePath")
  4282. : config_get_string(basicConfig, "AdvOut",
  4283. "RecFilePath");
  4284. /* do not save if using FFmpeg output in advanced output mode */
  4285. if (advanced) {
  4286. const char *type =
  4287. config_get_string(basicConfig, "AdvOut", "RecType");
  4288. if (astrcmpi(type, "FFmpeg") == 0) {
  4289. return;
  4290. }
  4291. }
  4292. QString input;
  4293. input += path;
  4294. input += "/";
  4295. input += remuxFilename.c_str();
  4296. QFileInfo fi(remuxFilename.c_str());
  4297. /* do not remux if lossless */
  4298. if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
  4299. return;
  4300. }
  4301. QString output;
  4302. output += path;
  4303. output += "/";
  4304. output += fi.completeBaseName();
  4305. output += ".mp4";
  4306. OBSRemux *remux = new OBSRemux(path, this, true);
  4307. remux->show();
  4308. remux->AutoRemux(input, output);
  4309. }
  4310. void OBSBasic::StartRecording()
  4311. {
  4312. if (outputHandler->RecordingActive())
  4313. return;
  4314. if (disableOutputsRef)
  4315. return;
  4316. if (LowDiskSpace()) {
  4317. DiskSpaceMessage();
  4318. ui->recordButton->setChecked(false);
  4319. return;
  4320. }
  4321. if (api)
  4322. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4323. SaveProject();
  4324. if (!outputHandler->StartRecording())
  4325. ui->recordButton->setChecked(false);
  4326. }
  4327. void OBSBasic::RecordStopping()
  4328. {
  4329. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4330. if (sysTrayRecord)
  4331. sysTrayRecord->setText(ui->recordButton->text());
  4332. recordingStopping = true;
  4333. if (api)
  4334. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4335. }
  4336. void OBSBasic::StopRecording()
  4337. {
  4338. SaveProject();
  4339. if (outputHandler->RecordingActive())
  4340. outputHandler->StopRecording(recordingStopping);
  4341. OnDeactivate();
  4342. }
  4343. void OBSBasic::RecordingStart()
  4344. {
  4345. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4346. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4347. ui->recordButton->setChecked(true);
  4348. if (sysTrayRecord)
  4349. sysTrayRecord->setText(ui->recordButton->text());
  4350. recordingStopping = false;
  4351. if (api)
  4352. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4353. if (!diskFullTimer->isActive())
  4354. diskFullTimer->start(1000);
  4355. OnActivate();
  4356. UpdatePause();
  4357. blog(LOG_INFO, RECORDING_START);
  4358. }
  4359. void OBSBasic::RecordingStop(int code, QString last_error)
  4360. {
  4361. ui->statusbar->RecordingStopped();
  4362. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4363. ui->recordButton->setChecked(false);
  4364. if (sysTrayRecord)
  4365. sysTrayRecord->setText(ui->recordButton->text());
  4366. blog(LOG_INFO, RECORDING_STOP);
  4367. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4368. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4369. QTStr("Output.RecordFail.Unsupported"));
  4370. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  4371. OBSMessageBox::warning(
  4372. this, QTStr("Output.RecordError.Title"),
  4373. QTStr("Output.RecordError.EncodeErrorMsg"));
  4374. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4375. OBSMessageBox::warning(this,
  4376. QTStr("Output.RecordNoSpace.Title"),
  4377. QTStr("Output.RecordNoSpace.Msg"));
  4378. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4379. const char *errorDescription;
  4380. DStr errorMessage;
  4381. bool use_last_error = true;
  4382. errorDescription = Str("Output.RecordError.Msg");
  4383. if (use_last_error && !last_error.isEmpty())
  4384. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4385. QT_TO_UTF8(last_error));
  4386. else
  4387. dstr_copy(errorMessage, errorDescription);
  4388. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4389. QT_UTF8(errorMessage));
  4390. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4391. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4392. QSystemTrayIcon::Warning);
  4393. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4394. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4395. QSystemTrayIcon::Warning);
  4396. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4397. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4398. QSystemTrayIcon::Warning);
  4399. }
  4400. if (api)
  4401. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4402. if (diskFullTimer->isActive())
  4403. diskFullTimer->stop();
  4404. if (remuxAfterRecord)
  4405. AutoRemux();
  4406. OnDeactivate();
  4407. UpdatePause(false);
  4408. }
  4409. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4410. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4411. extern volatile bool recording_paused;
  4412. extern volatile bool replaybuf_active;
  4413. void OBSBasic::ShowReplayBufferPauseWarning()
  4414. {
  4415. auto msgBox = []() {
  4416. QMessageBox msgbox(App()->GetMainWindow());
  4417. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  4418. "PauseWarning.Title"));
  4419. msgbox.setText(QTStr("Output.ReplayBuffer."
  4420. "PauseWarning.Text"));
  4421. msgbox.setIcon(QMessageBox::Icon::Information);
  4422. msgbox.addButton(QMessageBox::Ok);
  4423. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  4424. msgbox.setCheckBox(cb);
  4425. msgbox.exec();
  4426. if (cb->isChecked()) {
  4427. config_set_bool(App()->GlobalConfig(), "General",
  4428. "WarnedAboutReplayBufferPausing", true);
  4429. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  4430. }
  4431. };
  4432. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  4433. "WarnedAboutReplayBufferPausing");
  4434. if (!warned) {
  4435. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  4436. Q_ARG(VoidFunc, msgBox));
  4437. }
  4438. }
  4439. void OBSBasic::StartReplayBuffer()
  4440. {
  4441. if (!outputHandler || !outputHandler->replayBuffer)
  4442. return;
  4443. if (outputHandler->ReplayBufferActive())
  4444. return;
  4445. if (disableOutputsRef)
  4446. return;
  4447. if (!NoSourcesConfirmation()) {
  4448. replayBufferButton->setChecked(false);
  4449. return;
  4450. }
  4451. if (LowDiskSpace()) {
  4452. DiskSpaceMessage();
  4453. replayBufferButton->setChecked(false);
  4454. return;
  4455. }
  4456. obs_output_t *output = outputHandler->replayBuffer;
  4457. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4458. obs_data_array_t *bindings =
  4459. obs_data_get_array(hotkeys, "ReplayBuffer.Save");
  4460. size_t count = obs_data_array_count(bindings);
  4461. obs_data_array_release(bindings);
  4462. obs_data_release(hotkeys);
  4463. if (!count) {
  4464. OBSMessageBox::information(this, RP_NO_HOTKEY_TITLE,
  4465. RP_NO_HOTKEY_TEXT);
  4466. replayBufferButton->setChecked(false);
  4467. return;
  4468. }
  4469. if (api)
  4470. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4471. SaveProject();
  4472. if (!outputHandler->StartReplayBuffer()) {
  4473. replayBufferButton->setChecked(false);
  4474. } else if (os_atomic_load_bool(&recording_paused)) {
  4475. ShowReplayBufferPauseWarning();
  4476. }
  4477. }
  4478. void OBSBasic::ReplayBufferStopping()
  4479. {
  4480. if (!outputHandler || !outputHandler->replayBuffer)
  4481. return;
  4482. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4483. if (sysTrayReplayBuffer)
  4484. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4485. replayBufferStopping = true;
  4486. if (api)
  4487. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4488. }
  4489. void OBSBasic::StopReplayBuffer()
  4490. {
  4491. if (!outputHandler || !outputHandler->replayBuffer)
  4492. return;
  4493. SaveProject();
  4494. if (outputHandler->ReplayBufferActive())
  4495. outputHandler->StopReplayBuffer(replayBufferStopping);
  4496. OnDeactivate();
  4497. }
  4498. void OBSBasic::ReplayBufferStart()
  4499. {
  4500. if (!outputHandler || !outputHandler->replayBuffer)
  4501. return;
  4502. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4503. replayBufferButton->setChecked(true);
  4504. if (sysTrayReplayBuffer)
  4505. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4506. replayBufferStopping = false;
  4507. if (api)
  4508. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4509. OnActivate();
  4510. blog(LOG_INFO, REPLAY_BUFFER_START);
  4511. }
  4512. void OBSBasic::ReplayBufferSave()
  4513. {
  4514. if (!outputHandler || !outputHandler->replayBuffer)
  4515. return;
  4516. if (!outputHandler->ReplayBufferActive())
  4517. return;
  4518. calldata_t cd = {0};
  4519. proc_handler_t *ph =
  4520. obs_output_get_proc_handler(outputHandler->replayBuffer);
  4521. proc_handler_call(ph, "save", &cd);
  4522. calldata_free(&cd);
  4523. }
  4524. void OBSBasic::ReplayBufferStop(int code)
  4525. {
  4526. if (!outputHandler || !outputHandler->replayBuffer)
  4527. return;
  4528. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4529. replayBufferButton->setChecked(false);
  4530. if (sysTrayReplayBuffer)
  4531. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4532. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4533. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4534. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4535. QTStr("Output.RecordFail.Unsupported"));
  4536. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4537. OBSMessageBox::warning(this,
  4538. QTStr("Output.RecordNoSpace.Title"),
  4539. QTStr("Output.RecordNoSpace.Msg"));
  4540. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4541. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4542. QTStr("Output.RecordError.Msg"));
  4543. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4544. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4545. QSystemTrayIcon::Warning);
  4546. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4547. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4548. QSystemTrayIcon::Warning);
  4549. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4550. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4551. QSystemTrayIcon::Warning);
  4552. }
  4553. if (api)
  4554. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4555. OnDeactivate();
  4556. }
  4557. bool OBSBasic::NoSourcesConfirmation()
  4558. {
  4559. if (CountVideoSources() == 0 && isVisible()) {
  4560. QString msg;
  4561. msg = QTStr("NoSources.Text");
  4562. msg += "\n\n";
  4563. msg += QTStr("NoSources.Text.AddSource");
  4564. QMessageBox messageBox(this);
  4565. messageBox.setWindowTitle(QTStr("NoSources.Title"));
  4566. messageBox.setText(msg);
  4567. QAbstractButton *Yes = messageBox.addButton(
  4568. QTStr("Yes"), QMessageBox::YesRole);
  4569. messageBox.addButton(QTStr("No"), QMessageBox::NoRole);
  4570. messageBox.setIcon(QMessageBox::Question);
  4571. messageBox.exec();
  4572. if (messageBox.clickedButton() != Yes)
  4573. return false;
  4574. }
  4575. return true;
  4576. }
  4577. void OBSBasic::on_streamButton_clicked()
  4578. {
  4579. if (outputHandler->StreamingActive()) {
  4580. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4581. "WarnBeforeStoppingStream");
  4582. if (confirm && isVisible()) {
  4583. QMessageBox::StandardButton button =
  4584. OBSMessageBox::question(
  4585. this, QTStr("ConfirmStop.Title"),
  4586. QTStr("ConfirmStop.Text"));
  4587. if (button == QMessageBox::No) {
  4588. ui->streamButton->setChecked(true);
  4589. return;
  4590. }
  4591. }
  4592. StopStreaming();
  4593. } else {
  4594. if (!NoSourcesConfirmation()) {
  4595. ui->streamButton->setChecked(false);
  4596. return;
  4597. }
  4598. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4599. "WarnBeforeStartingStream");
  4600. obs_data_t *settings = obs_service_get_settings(service);
  4601. bool bwtest = obs_data_get_bool(settings, "bwtest");
  4602. obs_data_release(settings);
  4603. if (bwtest && isVisible()) {
  4604. QMessageBox::StandardButton button =
  4605. OBSMessageBox::question(
  4606. this, QTStr("ConfirmBWTest.Title"),
  4607. QTStr("ConfirmBWTest.Text"));
  4608. if (button == QMessageBox::No) {
  4609. ui->streamButton->setChecked(false);
  4610. return;
  4611. }
  4612. } else if (confirm && isVisible()) {
  4613. QMessageBox::StandardButton button =
  4614. OBSMessageBox::question(
  4615. this, QTStr("ConfirmStart.Title"),
  4616. QTStr("ConfirmStart.Text"));
  4617. if (button == QMessageBox::No) {
  4618. ui->streamButton->setChecked(false);
  4619. return;
  4620. }
  4621. }
  4622. StartStreaming();
  4623. }
  4624. }
  4625. void OBSBasic::on_recordButton_clicked()
  4626. {
  4627. if (outputHandler->RecordingActive()) {
  4628. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4629. "WarnBeforeStoppingRecord");
  4630. if (confirm && isVisible()) {
  4631. QMessageBox::StandardButton button =
  4632. OBSMessageBox::question(
  4633. this, QTStr("ConfirmStopRecord.Title"),
  4634. QTStr("ConfirmStopRecord.Text"));
  4635. if (button == QMessageBox::No) {
  4636. ui->recordButton->setChecked(true);
  4637. return;
  4638. }
  4639. }
  4640. StopRecording();
  4641. } else {
  4642. if (!NoSourcesConfirmation()) {
  4643. ui->recordButton->setChecked(false);
  4644. return;
  4645. }
  4646. StartRecording();
  4647. }
  4648. }
  4649. void OBSBasic::on_settingsButton_clicked()
  4650. {
  4651. on_action_Settings_triggered();
  4652. }
  4653. void OBSBasic::on_actionHelpPortal_triggered()
  4654. {
  4655. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4656. QDesktopServices::openUrl(url);
  4657. }
  4658. void OBSBasic::on_actionWebsite_triggered()
  4659. {
  4660. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4661. QDesktopServices::openUrl(url);
  4662. }
  4663. void OBSBasic::on_actionDiscord_triggered()
  4664. {
  4665. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4666. QDesktopServices::openUrl(url);
  4667. }
  4668. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4669. {
  4670. char path[512];
  4671. int ret = GetConfigPath(path, 512, "obs-studio");
  4672. if (ret <= 0)
  4673. return;
  4674. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4675. }
  4676. void OBSBasic::on_actionShowProfileFolder_triggered()
  4677. {
  4678. char path[512];
  4679. int ret = GetProfilePath(path, 512, "");
  4680. if (ret <= 0)
  4681. return;
  4682. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4683. }
  4684. int OBSBasic::GetTopSelectedSourceItem()
  4685. {
  4686. QModelIndexList selectedItems =
  4687. ui->sources->selectionModel()->selectedIndexes();
  4688. return selectedItems.count() ? selectedItems[0].row() : -1;
  4689. }
  4690. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4691. {
  4692. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4693. UNUSED_PARAMETER(pos);
  4694. }
  4695. void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
  4696. {
  4697. QMenu popup(this);
  4698. QPointer<QMenu> studioProgramProjector;
  4699. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  4700. AddProjectorMenuMonitors(studioProgramProjector, this,
  4701. SLOT(OpenStudioProgramProjector()));
  4702. popup.addMenu(studioProgramProjector);
  4703. QAction *studioProgramWindow =
  4704. popup.addAction(QTStr("StudioProgramWindow"), this,
  4705. SLOT(OpenStudioProgramWindow()));
  4706. popup.addAction(studioProgramWindow);
  4707. popup.exec(QCursor::pos());
  4708. }
  4709. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  4710. {
  4711. QMenu popup(this);
  4712. delete previewProjectorMain;
  4713. QAction *action =
  4714. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4715. this, SLOT(TogglePreview()));
  4716. action->setCheckable(true);
  4717. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4718. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4719. AddProjectorMenuMonitors(previewProjectorMain, this,
  4720. SLOT(OpenPreviewProjector()));
  4721. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  4722. SLOT(OpenPreviewWindow()));
  4723. popup.addMenu(previewProjectorMain);
  4724. popup.addAction(previewWindow);
  4725. popup.exec(QCursor::pos());
  4726. UNUSED_PARAMETER(pos);
  4727. }
  4728. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4729. {
  4730. #ifndef _WIN32
  4731. /* Make sure all dialogs are safely and successfully closed before
  4732. * switching the always on top mode due to the fact that windows all
  4733. * have to be recreated, so queue the actual toggle to happen after
  4734. * all events related to closing the dialogs have finished */
  4735. CloseDialogs();
  4736. #endif
  4737. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4738. Qt::QueuedConnection);
  4739. }
  4740. void OBSBasic::ToggleAlwaysOnTop()
  4741. {
  4742. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4743. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4744. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4745. show();
  4746. }
  4747. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4748. {
  4749. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4750. if (strcmp(val, "10") == 0) {
  4751. num = 10;
  4752. den = 1;
  4753. } else if (strcmp(val, "20") == 0) {
  4754. num = 20;
  4755. den = 1;
  4756. } else if (strcmp(val, "24 NTSC") == 0) {
  4757. num = 24000;
  4758. den = 1001;
  4759. } else if (strcmp(val, "25 PAL") == 0) {
  4760. num = 25;
  4761. den = 1;
  4762. } else if (strcmp(val, "29.97") == 0) {
  4763. num = 30000;
  4764. den = 1001;
  4765. } else if (strcmp(val, "48") == 0) {
  4766. num = 48;
  4767. den = 1;
  4768. } else if (strcmp(val, "50 PAL") == 0) {
  4769. num = 50;
  4770. den = 1;
  4771. } else if (strcmp(val, "59.94") == 0) {
  4772. num = 60000;
  4773. den = 1001;
  4774. } else if (strcmp(val, "60") == 0) {
  4775. num = 60;
  4776. den = 1;
  4777. } else {
  4778. num = 30;
  4779. den = 1;
  4780. }
  4781. }
  4782. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4783. {
  4784. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4785. den = 1;
  4786. }
  4787. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4788. {
  4789. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4790. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4791. }
  4792. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4793. {
  4794. num = 1000000000;
  4795. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4796. }
  4797. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4798. {
  4799. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4800. if (type == 1) //"Integer"
  4801. GetFPSInteger(num, den);
  4802. else if (type == 2) //"Fraction"
  4803. GetFPSFraction(num, den);
  4804. else if (false) //"Nanoseconds", currently not implemented
  4805. GetFPSNanoseconds(num, den);
  4806. else
  4807. GetFPSCommon(num, den);
  4808. }
  4809. config_t *OBSBasic::Config() const
  4810. {
  4811. return basicConfig;
  4812. }
  4813. void OBSBasic::on_actionEditTransform_triggered()
  4814. {
  4815. if (transformWindow)
  4816. transformWindow->close();
  4817. transformWindow = new OBSBasicTransform(this);
  4818. transformWindow->show();
  4819. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4820. }
  4821. static obs_transform_info copiedTransformInfo;
  4822. static obs_sceneitem_crop copiedCropInfo;
  4823. void OBSBasic::on_actionCopyTransform_triggered()
  4824. {
  4825. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  4826. if (!obs_sceneitem_selected(item))
  4827. return true;
  4828. obs_sceneitem_defer_update_begin(item);
  4829. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4830. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4831. obs_sceneitem_defer_update_end(item);
  4832. UNUSED_PARAMETER(scene);
  4833. UNUSED_PARAMETER(param);
  4834. return true;
  4835. };
  4836. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4837. ui->actionPasteTransform->setEnabled(true);
  4838. }
  4839. void OBSBasic::on_actionPasteTransform_triggered()
  4840. {
  4841. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  4842. if (!obs_sceneitem_selected(item))
  4843. return true;
  4844. obs_sceneitem_defer_update_begin(item);
  4845. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4846. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4847. obs_sceneitem_defer_update_end(item);
  4848. UNUSED_PARAMETER(scene);
  4849. UNUSED_PARAMETER(param);
  4850. return true;
  4851. };
  4852. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4853. }
  4854. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4855. {
  4856. if (obs_sceneitem_is_group(item))
  4857. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  4858. if (!obs_sceneitem_selected(item))
  4859. return true;
  4860. obs_sceneitem_defer_update_begin(item);
  4861. obs_transform_info info;
  4862. vec2_set(&info.pos, 0.0f, 0.0f);
  4863. vec2_set(&info.scale, 1.0f, 1.0f);
  4864. info.rot = 0.0f;
  4865. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4866. info.bounds_type = OBS_BOUNDS_NONE;
  4867. info.bounds_alignment = OBS_ALIGN_CENTER;
  4868. vec2_set(&info.bounds, 0.0f, 0.0f);
  4869. obs_sceneitem_set_info(item, &info);
  4870. obs_sceneitem_crop crop = {};
  4871. obs_sceneitem_set_crop(item, &crop);
  4872. obs_sceneitem_defer_update_end(item);
  4873. UNUSED_PARAMETER(scene);
  4874. UNUSED_PARAMETER(param);
  4875. return true;
  4876. }
  4877. void OBSBasic::on_actionResetTransform_triggered()
  4878. {
  4879. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  4880. }
  4881. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4882. {
  4883. matrix4 boxTransform;
  4884. obs_sceneitem_get_box_transform(item, &boxTransform);
  4885. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4886. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4887. auto GetMinPos = [&](float x, float y) {
  4888. vec3 pos;
  4889. vec3_set(&pos, x, y, 0.0f);
  4890. vec3_transform(&pos, &pos, &boxTransform);
  4891. vec3_min(&tl, &tl, &pos);
  4892. vec3_max(&br, &br, &pos);
  4893. };
  4894. GetMinPos(0.0f, 0.0f);
  4895. GetMinPos(1.0f, 0.0f);
  4896. GetMinPos(0.0f, 1.0f);
  4897. GetMinPos(1.0f, 1.0f);
  4898. }
  4899. static vec3 GetItemTL(obs_sceneitem_t *item)
  4900. {
  4901. vec3 tl, br;
  4902. GetItemBox(item, tl, br);
  4903. return tl;
  4904. }
  4905. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4906. {
  4907. vec3 newTL;
  4908. vec2 pos;
  4909. obs_sceneitem_get_pos(item, &pos);
  4910. newTL = GetItemTL(item);
  4911. pos.x += tl.x - newTL.x;
  4912. pos.y += tl.y - newTL.y;
  4913. obs_sceneitem_set_pos(item, &pos);
  4914. }
  4915. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4916. void *param)
  4917. {
  4918. if (obs_sceneitem_is_group(item))
  4919. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  4920. param);
  4921. if (!obs_sceneitem_selected(item))
  4922. return true;
  4923. float rot = *reinterpret_cast<float *>(param);
  4924. vec3 tl = GetItemTL(item);
  4925. rot += obs_sceneitem_get_rot(item);
  4926. if (rot >= 360.0f)
  4927. rot -= 360.0f;
  4928. else if (rot <= -360.0f)
  4929. rot += 360.0f;
  4930. obs_sceneitem_set_rot(item, rot);
  4931. obs_sceneitem_force_update_transform(item);
  4932. SetItemTL(item, tl);
  4933. UNUSED_PARAMETER(scene);
  4934. return true;
  4935. };
  4936. void OBSBasic::on_actionRotate90CW_triggered()
  4937. {
  4938. float f90CW = 90.0f;
  4939. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4940. }
  4941. void OBSBasic::on_actionRotate90CCW_triggered()
  4942. {
  4943. float f90CCW = -90.0f;
  4944. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4945. }
  4946. void OBSBasic::on_actionRotate180_triggered()
  4947. {
  4948. float f180 = 180.0f;
  4949. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4950. }
  4951. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4952. void *param)
  4953. {
  4954. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  4955. if (obs_sceneitem_is_group(item))
  4956. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  4957. param);
  4958. if (!obs_sceneitem_selected(item))
  4959. return true;
  4960. vec3 tl = GetItemTL(item);
  4961. vec2 scale;
  4962. obs_sceneitem_get_scale(item, &scale);
  4963. vec2_mul(&scale, &scale, &mul);
  4964. obs_sceneitem_set_scale(item, &scale);
  4965. obs_sceneitem_force_update_transform(item);
  4966. SetItemTL(item, tl);
  4967. UNUSED_PARAMETER(scene);
  4968. return true;
  4969. }
  4970. void OBSBasic::on_actionFlipHorizontal_triggered()
  4971. {
  4972. vec2 scale;
  4973. vec2_set(&scale, -1.0f, 1.0f);
  4974. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4975. &scale);
  4976. }
  4977. void OBSBasic::on_actionFlipVertical_triggered()
  4978. {
  4979. vec2 scale;
  4980. vec2_set(&scale, 1.0f, -1.0f);
  4981. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4982. &scale);
  4983. }
  4984. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4985. void *param)
  4986. {
  4987. obs_bounds_type boundsType =
  4988. *reinterpret_cast<obs_bounds_type *>(param);
  4989. if (obs_sceneitem_is_group(item))
  4990. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  4991. param);
  4992. if (!obs_sceneitem_selected(item))
  4993. return true;
  4994. obs_video_info ovi;
  4995. obs_get_video_info(&ovi);
  4996. obs_transform_info itemInfo;
  4997. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4998. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4999. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  5000. itemInfo.rot = 0.0f;
  5001. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  5002. float(ovi.base_height));
  5003. itemInfo.bounds_type = boundsType;
  5004. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  5005. obs_sceneitem_set_info(item, &itemInfo);
  5006. UNUSED_PARAMETER(scene);
  5007. return true;
  5008. }
  5009. void OBSBasic::on_actionFitToScreen_triggered()
  5010. {
  5011. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  5012. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5013. &boundsType);
  5014. }
  5015. void OBSBasic::on_actionStretchToScreen_triggered()
  5016. {
  5017. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  5018. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5019. &boundsType);
  5020. }
  5021. enum class CenterType {
  5022. Scene,
  5023. Vertical,
  5024. Horizontal,
  5025. };
  5026. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5027. {
  5028. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  5029. vec3 tl, br, itemCenter, screenCenter, offset;
  5030. obs_video_info ovi;
  5031. obs_transform_info oti;
  5032. if (obs_sceneitem_is_group(item))
  5033. obs_sceneitem_group_enum_items(item, center_to_scene,
  5034. &centerType);
  5035. if (!obs_sceneitem_selected(item))
  5036. return true;
  5037. obs_get_video_info(&ovi);
  5038. obs_sceneitem_get_info(item, &oti);
  5039. if (centerType == CenterType::Scene)
  5040. vec3_set(&screenCenter, float(ovi.base_width),
  5041. float(ovi.base_height), 0.0f);
  5042. else if (centerType == CenterType::Vertical)
  5043. vec3_set(&screenCenter, float(oti.bounds.x),
  5044. float(ovi.base_height), 0.0f);
  5045. else if (centerType == CenterType::Horizontal)
  5046. vec3_set(&screenCenter, float(ovi.base_width),
  5047. float(oti.bounds.y), 0.0f);
  5048. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  5049. GetItemBox(item, tl, br);
  5050. vec3_sub(&itemCenter, &br, &tl);
  5051. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  5052. vec3_add(&itemCenter, &itemCenter, &tl);
  5053. vec3_sub(&offset, &screenCenter, &itemCenter);
  5054. vec3_add(&tl, &tl, &offset);
  5055. if (centerType == CenterType::Vertical)
  5056. tl.x = oti.pos.x;
  5057. else if (centerType == CenterType::Horizontal)
  5058. tl.y = oti.pos.y;
  5059. SetItemTL(item, tl);
  5060. return true;
  5061. };
  5062. void OBSBasic::on_actionCenterToScreen_triggered()
  5063. {
  5064. CenterType centerType = CenterType::Scene;
  5065. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5066. }
  5067. void OBSBasic::on_actionVerticalCenter_triggered()
  5068. {
  5069. CenterType centerType = CenterType::Vertical;
  5070. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5071. }
  5072. void OBSBasic::on_actionHorizontalCenter_triggered()
  5073. {
  5074. CenterType centerType = CenterType::Horizontal;
  5075. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5076. }
  5077. void OBSBasic::EnablePreviewDisplay(bool enable)
  5078. {
  5079. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  5080. ui->preview->setVisible(enable);
  5081. ui->previewDisabledWidget->setVisible(!enable);
  5082. }
  5083. void OBSBasic::TogglePreview()
  5084. {
  5085. previewEnabled = !previewEnabled;
  5086. EnablePreviewDisplay(previewEnabled);
  5087. }
  5088. void OBSBasic::EnablePreview()
  5089. {
  5090. if (previewProgramMode)
  5091. return;
  5092. previewEnabled = true;
  5093. EnablePreviewDisplay(true);
  5094. }
  5095. void OBSBasic::DisablePreview()
  5096. {
  5097. if (previewProgramMode)
  5098. return;
  5099. previewEnabled = false;
  5100. EnablePreviewDisplay(false);
  5101. }
  5102. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5103. {
  5104. if (obs_sceneitem_locked(item))
  5105. return true;
  5106. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  5107. struct vec2 pos;
  5108. if (!obs_sceneitem_selected(item)) {
  5109. if (obs_sceneitem_is_group(item)) {
  5110. struct vec3 offset3;
  5111. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5112. struct matrix4 matrix;
  5113. obs_sceneitem_get_draw_transform(item, &matrix);
  5114. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5115. matrix4_inv(&matrix, &matrix);
  5116. vec3_transform(&offset3, &offset3, &matrix);
  5117. struct vec2 new_offset;
  5118. vec2_set(&new_offset, offset3.x, offset3.y);
  5119. obs_sceneitem_group_enum_items(item, nudge_callback,
  5120. &new_offset);
  5121. }
  5122. return true;
  5123. }
  5124. obs_sceneitem_get_pos(item, &pos);
  5125. vec2_add(&pos, &pos, &offset);
  5126. obs_sceneitem_set_pos(item, &pos);
  5127. return true;
  5128. }
  5129. void OBSBasic::Nudge(int dist, MoveDir dir)
  5130. {
  5131. if (ui->preview->Locked())
  5132. return;
  5133. struct vec2 offset;
  5134. vec2_set(&offset, 0.0f, 0.0f);
  5135. switch (dir) {
  5136. case MoveDir::Up:
  5137. offset.y = (float)-dist;
  5138. break;
  5139. case MoveDir::Down:
  5140. offset.y = (float)dist;
  5141. break;
  5142. case MoveDir::Left:
  5143. offset.x = (float)-dist;
  5144. break;
  5145. case MoveDir::Right:
  5146. offset.x = (float)dist;
  5147. break;
  5148. }
  5149. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5150. }
  5151. void OBSBasic::NudgeUp()
  5152. {
  5153. Nudge(1, MoveDir::Up);
  5154. }
  5155. void OBSBasic::NudgeDown()
  5156. {
  5157. Nudge(1, MoveDir::Down);
  5158. }
  5159. void OBSBasic::NudgeLeft()
  5160. {
  5161. Nudge(1, MoveDir::Left);
  5162. }
  5163. void OBSBasic::NudgeRight()
  5164. {
  5165. Nudge(1, MoveDir::Right);
  5166. }
  5167. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5168. QString title, ProjectorType type)
  5169. {
  5170. /* seriously? 10 monitors? */
  5171. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5172. return nullptr;
  5173. OBSProjector *projector =
  5174. new OBSProjector(nullptr, source, monitor, title, type);
  5175. if (monitor < 0) {
  5176. for (auto &projPtr : windowProjectors) {
  5177. if (!projPtr) {
  5178. projPtr = projector;
  5179. projector = nullptr;
  5180. }
  5181. }
  5182. if (projector)
  5183. windowProjectors.push_back(projector);
  5184. } else {
  5185. delete projectors[monitor];
  5186. projectors[monitor].clear();
  5187. projectors[monitor] = projector;
  5188. }
  5189. return projector;
  5190. }
  5191. void OBSBasic::OpenStudioProgramProjector()
  5192. {
  5193. int monitor = sender()->property("monitor").toInt();
  5194. OpenProjector(nullptr, monitor, nullptr, ProjectorType::StudioProgram);
  5195. }
  5196. void OBSBasic::OpenPreviewProjector()
  5197. {
  5198. int monitor = sender()->property("monitor").toInt();
  5199. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Preview);
  5200. }
  5201. void OBSBasic::OpenSourceProjector()
  5202. {
  5203. int monitor = sender()->property("monitor").toInt();
  5204. OBSSceneItem item = GetCurrentSceneItem();
  5205. if (!item)
  5206. return;
  5207. OpenProjector(obs_sceneitem_get_source(item), monitor, nullptr,
  5208. ProjectorType::Source);
  5209. }
  5210. void OBSBasic::OpenMultiviewProjector()
  5211. {
  5212. int monitor = sender()->property("monitor").toInt();
  5213. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Multiview);
  5214. }
  5215. void OBSBasic::OpenSceneProjector()
  5216. {
  5217. int monitor = sender()->property("monitor").toInt();
  5218. OBSScene scene = GetCurrentScene();
  5219. if (!scene)
  5220. return;
  5221. OpenProjector(obs_scene_get_source(scene), monitor, nullptr,
  5222. ProjectorType::Scene);
  5223. }
  5224. void OBSBasic::OpenStudioProgramWindow()
  5225. {
  5226. OpenProjector(nullptr, -1, QTStr("StudioProgramWindow"),
  5227. ProjectorType::StudioProgram);
  5228. }
  5229. void OBSBasic::OpenPreviewWindow()
  5230. {
  5231. OpenProjector(nullptr, -1, QTStr("PreviewWindow"),
  5232. ProjectorType::Preview);
  5233. }
  5234. void OBSBasic::OpenSourceWindow()
  5235. {
  5236. OBSSceneItem item = GetCurrentSceneItem();
  5237. if (!item)
  5238. return;
  5239. OBSSource source = obs_sceneitem_get_source(item);
  5240. QString title = QString::fromUtf8(obs_source_get_name(source));
  5241. OpenProjector(obs_sceneitem_get_source(item), -1, title,
  5242. ProjectorType::Source);
  5243. }
  5244. void OBSBasic::OpenMultiviewWindow()
  5245. {
  5246. OpenProjector(nullptr, -1, QTStr("MultiviewWindowed"),
  5247. ProjectorType::Multiview);
  5248. }
  5249. void OBSBasic::OpenSceneWindow()
  5250. {
  5251. OBSScene scene = GetCurrentScene();
  5252. if (!scene)
  5253. return;
  5254. OBSSource source = obs_scene_get_source(scene);
  5255. QString title = QString::fromUtf8(obs_source_get_name(source));
  5256. OpenProjector(obs_scene_get_source(scene), -1, title,
  5257. ProjectorType::Scene);
  5258. }
  5259. void OBSBasic::OpenSavedProjectors()
  5260. {
  5261. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5262. OBSProjector *projector = nullptr;
  5263. switch (info->type) {
  5264. case ProjectorType::Source:
  5265. case ProjectorType::Scene: {
  5266. OBSSource source =
  5267. obs_get_source_by_name(info->name.c_str());
  5268. if (!source)
  5269. continue;
  5270. QString title = nullptr;
  5271. if (info->monitor < 0)
  5272. title = QString::fromUtf8(
  5273. obs_source_get_name(source));
  5274. projector = OpenProjector(source, info->monitor, title,
  5275. info->type);
  5276. obs_source_release(source);
  5277. break;
  5278. }
  5279. case ProjectorType::Preview: {
  5280. projector = OpenProjector(nullptr, info->monitor,
  5281. QTStr("PreviewWindow"),
  5282. ProjectorType::Preview);
  5283. break;
  5284. }
  5285. case ProjectorType::StudioProgram: {
  5286. projector = OpenProjector(nullptr, info->monitor,
  5287. QTStr("StudioProgramWindow"),
  5288. ProjectorType::StudioProgram);
  5289. break;
  5290. }
  5291. case ProjectorType::Multiview: {
  5292. projector = OpenProjector(nullptr, info->monitor,
  5293. QTStr("MultiviewWindowed"),
  5294. ProjectorType::Multiview);
  5295. break;
  5296. }
  5297. }
  5298. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5299. QByteArray byteArray = QByteArray::fromBase64(
  5300. QByteArray(info->geometry.c_str()));
  5301. projector->restoreGeometry(byteArray);
  5302. if (!WindowPositionValid(projector->normalGeometry())) {
  5303. QRect rect = App()->desktop()->geometry();
  5304. projector->setGeometry(QStyle::alignedRect(
  5305. Qt::LeftToRight, Qt::AlignCenter,
  5306. size(), rect));
  5307. }
  5308. }
  5309. }
  5310. }
  5311. void OBSBasic::on_actionFullscreenInterface_triggered()
  5312. {
  5313. if (!fullscreenInterface)
  5314. showFullScreen();
  5315. else
  5316. showNormal();
  5317. fullscreenInterface = !fullscreenInterface;
  5318. }
  5319. void OBSBasic::UpdateTitleBar()
  5320. {
  5321. stringstream name;
  5322. const char *profile =
  5323. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  5324. const char *sceneCollection = config_get_string(
  5325. App()->GlobalConfig(), "Basic", "SceneCollection");
  5326. name << "OBS ";
  5327. if (previewProgramMode)
  5328. name << "Studio ";
  5329. name << App()->GetVersionString();
  5330. if (App()->IsPortableMode())
  5331. name << " - Portable Mode";
  5332. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5333. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5334. setWindowTitle(QT_UTF8(name.str().c_str()));
  5335. }
  5336. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5337. {
  5338. char profiles_path[512];
  5339. const char *profile =
  5340. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  5341. int ret;
  5342. if (!profile)
  5343. return -1;
  5344. if (!path)
  5345. return -1;
  5346. if (!file)
  5347. file = "";
  5348. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5349. if (ret <= 0)
  5350. return ret;
  5351. if (!*file)
  5352. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5353. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5354. }
  5355. void OBSBasic::on_resetUI_triggered()
  5356. {
  5357. /* prune deleted extra docks */
  5358. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5359. if (!extraDocks[i]) {
  5360. extraDocks.removeAt(i);
  5361. }
  5362. }
  5363. if (extraDocks.size()) {
  5364. QMessageBox::StandardButton button = QMessageBox::question(
  5365. this, QTStr("ResetUIWarning.Title"),
  5366. QTStr("ResetUIWarning.Text"));
  5367. if (button == QMessageBox::No)
  5368. return;
  5369. }
  5370. /* undock/hide/center extra docks */
  5371. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5372. if (extraDocks[i]) {
  5373. extraDocks[i]->setVisible(true);
  5374. extraDocks[i]->setFloating(true);
  5375. extraDocks[i]->move(frameGeometry().topLeft() +
  5376. rect().center() -
  5377. extraDocks[i]->rect().center());
  5378. extraDocks[i]->setVisible(false);
  5379. }
  5380. }
  5381. restoreState(startingDockLayout);
  5382. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5383. int cx = width();
  5384. int cy = height();
  5385. int cx22_5 = cx * 225 / 1000;
  5386. int cx5 = cx * 5 / 100;
  5387. cy = cy * 225 / 1000;
  5388. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5389. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  5390. ui->mixerDock, ui->transitionsDock,
  5391. ui->controlsDock};
  5392. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  5393. ui->scenesDock->setVisible(true);
  5394. ui->sourcesDock->setVisible(true);
  5395. ui->mixerDock->setVisible(true);
  5396. ui->transitionsDock->setVisible(true);
  5397. ui->controlsDock->setVisible(true);
  5398. statsDock->setVisible(false);
  5399. statsDock->setFloating(true);
  5400. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5401. resizeDocks(docks, sizes, Qt::Horizontal);
  5402. #endif
  5403. }
  5404. void OBSBasic::on_lockUI_toggled(bool lock)
  5405. {
  5406. QDockWidget::DockWidgetFeatures features =
  5407. lock ? QDockWidget::NoDockWidgetFeatures
  5408. : QDockWidget::AllDockWidgetFeatures;
  5409. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5410. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5411. ui->scenesDock->setFeatures(mainFeatures);
  5412. ui->sourcesDock->setFeatures(mainFeatures);
  5413. ui->mixerDock->setFeatures(mainFeatures);
  5414. ui->transitionsDock->setFeatures(mainFeatures);
  5415. ui->controlsDock->setFeatures(mainFeatures);
  5416. statsDock->setFeatures(features);
  5417. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5418. if (!extraDocks[i]) {
  5419. extraDocks.removeAt(i);
  5420. } else {
  5421. extraDocks[i]->setFeatures(features);
  5422. }
  5423. }
  5424. }
  5425. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5426. {
  5427. ui->sourcesToolbar->setVisible(visible);
  5428. ui->scenesToolbar->setVisible(visible);
  5429. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5430. "ShowListboxToolbars", visible);
  5431. }
  5432. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5433. {
  5434. ui->statusbar->setVisible(visible);
  5435. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  5436. visible);
  5437. }
  5438. void OBSBasic::on_actionLockPreview_triggered()
  5439. {
  5440. ui->preview->ToggleLocked();
  5441. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5442. }
  5443. void OBSBasic::on_scalingMenu_aboutToShow()
  5444. {
  5445. obs_video_info ovi;
  5446. obs_get_video_info(&ovi);
  5447. QAction *action = ui->actionScaleCanvas;
  5448. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5449. text = text.arg(QString::number(ovi.base_width),
  5450. QString::number(ovi.base_height));
  5451. action->setText(text);
  5452. action = ui->actionScaleOutput;
  5453. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5454. text = text.arg(QString::number(ovi.output_width),
  5455. QString::number(ovi.output_height));
  5456. action->setText(text);
  5457. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5458. ovi.output_height == ovi.base_height));
  5459. UpdatePreviewScalingMenu();
  5460. }
  5461. void OBSBasic::on_actionScaleWindow_triggered()
  5462. {
  5463. ui->preview->SetFixedScaling(false);
  5464. ui->preview->ResetScrollingOffset();
  5465. emit ui->preview->DisplayResized();
  5466. }
  5467. void OBSBasic::on_actionScaleCanvas_triggered()
  5468. {
  5469. ui->preview->SetFixedScaling(true);
  5470. ui->preview->SetScalingLevel(0);
  5471. emit ui->preview->DisplayResized();
  5472. }
  5473. void OBSBasic::on_actionScaleOutput_triggered()
  5474. {
  5475. obs_video_info ovi;
  5476. obs_get_video_info(&ovi);
  5477. ui->preview->SetFixedScaling(true);
  5478. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5479. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5480. int32_t approxScalingLevel =
  5481. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5482. ui->preview->SetScalingLevel(approxScalingLevel);
  5483. ui->preview->SetScalingAmount(scalingAmount);
  5484. emit ui->preview->DisplayResized();
  5485. }
  5486. void OBSBasic::SetShowing(bool showing)
  5487. {
  5488. if (!showing && isVisible()) {
  5489. config_set_string(App()->GlobalConfig(), "BasicWindow",
  5490. "geometry",
  5491. saveGeometry().toBase64().constData());
  5492. /* hide all visible child dialogs */
  5493. visDlgPositions.clear();
  5494. if (!visDialogs.isEmpty()) {
  5495. for (QDialog *dlg : visDialogs) {
  5496. visDlgPositions.append(dlg->pos());
  5497. dlg->hide();
  5498. }
  5499. }
  5500. if (showHide)
  5501. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5502. QTimer::singleShot(250, this, SLOT(hide()));
  5503. if (previewEnabled)
  5504. EnablePreviewDisplay(false);
  5505. setVisible(false);
  5506. #ifdef __APPLE__
  5507. EnableOSXDockIcon(false);
  5508. #endif
  5509. } else if (showing && !isVisible()) {
  5510. if (showHide)
  5511. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5512. QTimer::singleShot(250, this, SLOT(show()));
  5513. if (previewEnabled)
  5514. EnablePreviewDisplay(true);
  5515. setVisible(true);
  5516. #ifdef __APPLE__
  5517. EnableOSXDockIcon(true);
  5518. #endif
  5519. /* raise and activate window to ensure it is on top */
  5520. raise();
  5521. activateWindow();
  5522. /* show all child dialogs that was visible earlier */
  5523. if (!visDialogs.isEmpty()) {
  5524. for (int i = 0; i < visDialogs.size(); ++i) {
  5525. QDialog *dlg = visDialogs[i];
  5526. dlg->move(visDlgPositions[i]);
  5527. dlg->show();
  5528. }
  5529. }
  5530. /* Unminimize window if it was hidden to tray instead of task
  5531. * bar. */
  5532. if (sysTrayMinimizeToTray()) {
  5533. Qt::WindowStates state;
  5534. state = windowState() & ~Qt::WindowMinimized;
  5535. state |= Qt::WindowActive;
  5536. setWindowState(state);
  5537. }
  5538. }
  5539. }
  5540. void OBSBasic::ToggleShowHide()
  5541. {
  5542. bool showing = isVisible();
  5543. if (showing) {
  5544. /* check for modal dialogs */
  5545. EnumDialogs();
  5546. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5547. return;
  5548. }
  5549. SetShowing(!showing);
  5550. }
  5551. void OBSBasic::SystemTrayInit()
  5552. {
  5553. trayIcon.reset(new QSystemTrayIcon(
  5554. QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
  5555. this));
  5556. trayIcon->setToolTip("OBS Studio");
  5557. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  5558. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5559. trayIcon.data());
  5560. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5561. trayIcon.data());
  5562. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5563. trayIcon.data());
  5564. exit = new QAction(QTStr("Exit"), trayIcon.data());
  5565. trayMenu = new QMenu;
  5566. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5567. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5568. AddProjectorMenuMonitors(previewProjector, this,
  5569. SLOT(OpenPreviewProjector()));
  5570. AddProjectorMenuMonitors(studioProgramProjector, this,
  5571. SLOT(OpenStudioProgramProjector()));
  5572. trayMenu->addAction(showHide);
  5573. trayMenu->addMenu(previewProjector);
  5574. trayMenu->addMenu(studioProgramProjector);
  5575. trayMenu->addAction(sysTrayStream);
  5576. trayMenu->addAction(sysTrayRecord);
  5577. trayMenu->addAction(sysTrayReplayBuffer);
  5578. trayMenu->addAction(exit);
  5579. trayIcon->setContextMenu(trayMenu);
  5580. trayIcon->show();
  5581. if (outputHandler && !outputHandler->replayBuffer)
  5582. sysTrayReplayBuffer->setEnabled(false);
  5583. connect(trayIcon.data(),
  5584. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  5585. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5586. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  5587. connect(sysTrayStream, SIGNAL(triggered()), this,
  5588. SLOT(on_streamButton_clicked()));
  5589. connect(sysTrayRecord, SIGNAL(triggered()), this,
  5590. SLOT(on_recordButton_clicked()));
  5591. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  5592. &OBSBasic::ReplayBufferClicked);
  5593. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  5594. }
  5595. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5596. {
  5597. // Refresh projector list
  5598. previewProjector->clear();
  5599. studioProgramProjector->clear();
  5600. AddProjectorMenuMonitors(previewProjector, this,
  5601. SLOT(OpenPreviewProjector()));
  5602. AddProjectorMenuMonitors(studioProgramProjector, this,
  5603. SLOT(OpenStudioProgramProjector()));
  5604. if (reason == QSystemTrayIcon::Trigger)
  5605. ToggleShowHide();
  5606. }
  5607. void OBSBasic::SysTrayNotify(const QString &text,
  5608. QSystemTrayIcon::MessageIcon n)
  5609. {
  5610. if (trayIcon && QSystemTrayIcon::supportsMessages()) {
  5611. QSystemTrayIcon::MessageIcon icon =
  5612. QSystemTrayIcon::MessageIcon(n);
  5613. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5614. }
  5615. }
  5616. void OBSBasic::SystemTray(bool firstStarted)
  5617. {
  5618. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5619. return;
  5620. if (!trayIcon && !firstStarted)
  5621. return;
  5622. bool sysTrayWhenStarted = config_get_bool(
  5623. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  5624. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5625. "SysTrayEnabled");
  5626. if (firstStarted)
  5627. SystemTrayInit();
  5628. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5629. trayIcon->hide();
  5630. } else if ((sysTrayWhenStarted && sysTrayEnabled) ||
  5631. opt_minimize_tray) {
  5632. trayIcon->show();
  5633. if (firstStarted) {
  5634. QTimer::singleShot(50, this, SLOT(hide()));
  5635. EnablePreviewDisplay(false);
  5636. setVisible(false);
  5637. #ifdef __APPLE__
  5638. EnableOSXDockIcon(false);
  5639. #endif
  5640. opt_minimize_tray = false;
  5641. }
  5642. } else if (sysTrayEnabled) {
  5643. trayIcon->show();
  5644. } else if (!sysTrayEnabled) {
  5645. trayIcon->hide();
  5646. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5647. trayIcon->hide();
  5648. }
  5649. if (isVisible())
  5650. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5651. else
  5652. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5653. }
  5654. bool OBSBasic::sysTrayMinimizeToTray()
  5655. {
  5656. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  5657. "SysTrayMinimizeToTray");
  5658. }
  5659. void OBSBasic::on_actionCopySource_triggered()
  5660. {
  5661. OBSSceneItem item = GetCurrentSceneItem();
  5662. if (!item)
  5663. return;
  5664. on_actionCopyTransform_triggered();
  5665. OBSSource source = obs_sceneitem_get_source(item);
  5666. copyString = obs_source_get_name(source);
  5667. copyVisible = obs_sceneitem_visible(item);
  5668. ui->actionPasteRef->setEnabled(true);
  5669. uint32_t output_flags = obs_source_get_output_flags(source);
  5670. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5671. ui->actionPasteDup->setEnabled(true);
  5672. else
  5673. ui->actionPasteDup->setEnabled(false);
  5674. }
  5675. void OBSBasic::on_actionPasteRef_triggered()
  5676. {
  5677. /* do not allow duplicate refs of the same group in the same scene */
  5678. OBSScene scene = GetCurrentScene();
  5679. if (!!obs_scene_get_group(scene, copyString))
  5680. return;
  5681. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  5682. on_actionPasteTransform_triggered();
  5683. }
  5684. void OBSBasic::on_actionPasteDup_triggered()
  5685. {
  5686. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  5687. on_actionPasteTransform_triggered();
  5688. }
  5689. void OBSBasic::AudioMixerCopyFilters()
  5690. {
  5691. QAction *action = reinterpret_cast<QAction *>(sender());
  5692. VolControl *vol = action->property("volControl").value<VolControl *>();
  5693. obs_source_t *source = vol->GetSource();
  5694. copyFiltersString = obs_source_get_name(source);
  5695. }
  5696. void OBSBasic::AudioMixerPasteFilters()
  5697. {
  5698. QAction *action = reinterpret_cast<QAction *>(sender());
  5699. VolControl *vol = action->property("volControl").value<VolControl *>();
  5700. obs_source_t *dstSource = vol->GetSource();
  5701. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5702. obs_source_release(source);
  5703. if (source == dstSource)
  5704. return;
  5705. obs_source_copy_filters(dstSource, source);
  5706. }
  5707. void OBSBasic::SceneCopyFilters()
  5708. {
  5709. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  5710. }
  5711. void OBSBasic::ScenePasteFilters()
  5712. {
  5713. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5714. obs_source_release(source);
  5715. OBSSource dstSource = GetCurrentSceneSource();
  5716. if (source == dstSource)
  5717. return;
  5718. obs_source_copy_filters(dstSource, source);
  5719. }
  5720. void OBSBasic::on_actionCopyFilters_triggered()
  5721. {
  5722. OBSSceneItem item = GetCurrentSceneItem();
  5723. if (!item)
  5724. return;
  5725. OBSSource source = obs_sceneitem_get_source(item);
  5726. copyFiltersString = obs_source_get_name(source);
  5727. ui->actionPasteFilters->setEnabled(true);
  5728. }
  5729. void OBSBasic::on_actionPasteFilters_triggered()
  5730. {
  5731. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5732. obs_source_release(source);
  5733. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5734. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5735. if (source == dstSource)
  5736. return;
  5737. obs_source_copy_filters(dstSource, source);
  5738. }
  5739. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5740. QModelIndexList selectedItems)
  5741. {
  5742. for (int x = 0; x < selectedItems.count(); x++) {
  5743. SourceTreeItem *treeItem =
  5744. sources->GetItemWidget(selectedItems[x].row());
  5745. treeItem->setStyleSheet("background: " +
  5746. color.name(QColor::HexArgb));
  5747. treeItem->style()->unpolish(treeItem);
  5748. treeItem->style()->polish(treeItem);
  5749. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  5750. obs_data_t *privData =
  5751. obs_sceneitem_get_private_settings(sceneItem);
  5752. obs_data_set_int(privData, "color-preset", 1);
  5753. obs_data_set_string(privData, "color",
  5754. QT_TO_UTF8(color.name(QColor::HexArgb)));
  5755. obs_data_release(privData);
  5756. }
  5757. }
  5758. void OBSBasic::ColorChange()
  5759. {
  5760. QModelIndexList selectedItems =
  5761. ui->sources->selectionModel()->selectedIndexes();
  5762. QAction *action = qobject_cast<QAction *>(sender());
  5763. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  5764. if (selectedItems.count() == 0)
  5765. return;
  5766. if (colorButton) {
  5767. int preset = colorButton->property("bgColor").value<int>();
  5768. for (int x = 0; x < selectedItems.count(); x++) {
  5769. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  5770. selectedItems[x].row());
  5771. treeItem->setStyleSheet("");
  5772. treeItem->setProperty("bgColor", preset);
  5773. treeItem->style()->unpolish(treeItem);
  5774. treeItem->style()->polish(treeItem);
  5775. OBSSceneItem sceneItem =
  5776. ui->sources->Get(selectedItems[x].row());
  5777. obs_data_t *privData =
  5778. obs_sceneitem_get_private_settings(sceneItem);
  5779. obs_data_set_int(privData, "color-preset", preset + 1);
  5780. obs_data_set_string(privData, "color", "");
  5781. obs_data_release(privData);
  5782. }
  5783. for (int i = 1; i < 9; i++) {
  5784. stringstream button;
  5785. button << "preset" << i;
  5786. QPushButton *cButton =
  5787. colorButton->parentWidget()
  5788. ->findChild<QPushButton *>(
  5789. button.str().c_str());
  5790. cButton->setStyleSheet("border: 1px solid black");
  5791. }
  5792. colorButton->setStyleSheet("border: 2px solid black");
  5793. } else if (action) {
  5794. int preset = action->property("bgColor").value<int>();
  5795. if (preset == 1) {
  5796. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5797. SourceTreeItem *curTreeItem =
  5798. GetItemWidgetFromSceneItem(curSceneItem);
  5799. obs_data_t *curPrivData =
  5800. obs_sceneitem_get_private_settings(
  5801. curSceneItem);
  5802. int oldPreset =
  5803. obs_data_get_int(curPrivData, "color-preset");
  5804. const QString oldSheet = curTreeItem->styleSheet();
  5805. auto liveChangeColor = [=](const QColor &color) {
  5806. if (color.isValid()) {
  5807. curTreeItem->setStyleSheet(
  5808. "background: " +
  5809. color.name(QColor::HexArgb));
  5810. }
  5811. };
  5812. auto changedColor = [=](const QColor &color) {
  5813. if (color.isValid()) {
  5814. ConfirmColor(ui->sources, color,
  5815. selectedItems);
  5816. }
  5817. };
  5818. auto rejected = [=]() {
  5819. if (oldPreset == 1) {
  5820. curTreeItem->setStyleSheet(oldSheet);
  5821. curTreeItem->setProperty("bgColor", 0);
  5822. } else if (oldPreset == 0) {
  5823. curTreeItem->setStyleSheet(
  5824. "background: none");
  5825. curTreeItem->setProperty("bgColor", 0);
  5826. } else {
  5827. curTreeItem->setStyleSheet("");
  5828. curTreeItem->setProperty("bgColor",
  5829. oldPreset - 1);
  5830. }
  5831. curTreeItem->style()->unpolish(curTreeItem);
  5832. curTreeItem->style()->polish(curTreeItem);
  5833. };
  5834. QColorDialog::ColorDialogOptions options =
  5835. QColorDialog::ShowAlphaChannel;
  5836. const char *oldColor =
  5837. obs_data_get_string(curPrivData, "color");
  5838. const char *customColor = *oldColor != 0 ? oldColor
  5839. : "#55FF0000";
  5840. #ifdef __APPLE__
  5841. options |= QColorDialog::DontUseNativeDialog;
  5842. #endif
  5843. QColorDialog *colorDialog = new QColorDialog(this);
  5844. colorDialog->setOptions(options);
  5845. colorDialog->setCurrentColor(QColor(customColor));
  5846. connect(colorDialog, &QColorDialog::currentColorChanged,
  5847. liveChangeColor);
  5848. connect(colorDialog, &QColorDialog::colorSelected,
  5849. changedColor);
  5850. connect(colorDialog, &QColorDialog::rejected, rejected);
  5851. colorDialog->open();
  5852. obs_data_release(curPrivData);
  5853. } else {
  5854. for (int x = 0; x < selectedItems.count(); x++) {
  5855. SourceTreeItem *treeItem =
  5856. ui->sources->GetItemWidget(
  5857. selectedItems[x].row());
  5858. treeItem->setStyleSheet("background: none");
  5859. treeItem->setProperty("bgColor", preset);
  5860. treeItem->style()->unpolish(treeItem);
  5861. treeItem->style()->polish(treeItem);
  5862. OBSSceneItem sceneItem = ui->sources->Get(
  5863. selectedItems[x].row());
  5864. obs_data_t *privData =
  5865. obs_sceneitem_get_private_settings(
  5866. sceneItem);
  5867. obs_data_set_int(privData, "color-preset",
  5868. preset);
  5869. obs_data_set_string(privData, "color", "");
  5870. obs_data_release(privData);
  5871. }
  5872. }
  5873. }
  5874. }
  5875. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  5876. {
  5877. int i = 0;
  5878. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  5879. OBSSceneItem item = ui->sources->Get(i);
  5880. int64_t id = obs_sceneitem_get_id(sceneItem);
  5881. while (treeItem && obs_sceneitem_get_id(item) != id) {
  5882. i++;
  5883. treeItem = ui->sources->GetItemWidget(i);
  5884. item = ui->sources->Get(i);
  5885. }
  5886. if (treeItem)
  5887. return treeItem;
  5888. return nullptr;
  5889. }
  5890. void OBSBasic::on_autoConfigure_triggered()
  5891. {
  5892. AutoConfig test(this);
  5893. test.setModal(true);
  5894. test.show();
  5895. test.exec();
  5896. }
  5897. void OBSBasic::on_stats_triggered()
  5898. {
  5899. if (!stats.isNull()) {
  5900. stats->show();
  5901. stats->raise();
  5902. return;
  5903. }
  5904. OBSBasicStats *statsDlg;
  5905. statsDlg = new OBSBasicStats(nullptr);
  5906. statsDlg->show();
  5907. stats = statsDlg;
  5908. }
  5909. void OBSBasic::on_actionShowAbout_triggered()
  5910. {
  5911. if (about)
  5912. about->close();
  5913. about = new OBSAbout(this);
  5914. about->show();
  5915. about->setAttribute(Qt::WA_DeleteOnClose, true);
  5916. }
  5917. void OBSBasic::ResizeOutputSizeOfSource()
  5918. {
  5919. if (obs_video_active())
  5920. return;
  5921. QMessageBox resize_output(this);
  5922. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  5923. QTStr("ResizeOutputSizeOfSource.Continue"));
  5924. QAbstractButton *Yes =
  5925. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  5926. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  5927. resize_output.setIcon(QMessageBox::Warning);
  5928. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  5929. resize_output.exec();
  5930. if (resize_output.clickedButton() != Yes)
  5931. return;
  5932. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  5933. int width = obs_source_get_width(source);
  5934. int height = obs_source_get_height(source);
  5935. config_set_uint(basicConfig, "Video", "BaseCX", width);
  5936. config_set_uint(basicConfig, "Video", "BaseCY", height);
  5937. config_set_uint(basicConfig, "Video", "OutputCX", width);
  5938. config_set_uint(basicConfig, "Video", "OutputCY", height);
  5939. ResetVideo();
  5940. on_actionFitToScreen_triggered();
  5941. }
  5942. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  5943. {
  5944. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  5945. action->setCheckable(true);
  5946. assignDockToggle(dock, action);
  5947. extraDocks.push_back(dock);
  5948. bool lock = ui->lockUI->isChecked();
  5949. QDockWidget::DockWidgetFeatures features =
  5950. lock ? QDockWidget::NoDockWidgetFeatures
  5951. : QDockWidget::AllDockWidgetFeatures;
  5952. dock->setFeatures(features);
  5953. /* prune deleted docks */
  5954. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5955. if (!extraDocks[i]) {
  5956. extraDocks.removeAt(i);
  5957. }
  5958. }
  5959. return action;
  5960. }
  5961. OBSBasic *OBSBasic::Get()
  5962. {
  5963. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  5964. }
  5965. bool OBSBasic::StreamingActive()
  5966. {
  5967. if (!outputHandler)
  5968. return false;
  5969. return outputHandler->StreamingActive();
  5970. }
  5971. bool OBSBasic::RecordingActive()
  5972. {
  5973. if (!outputHandler)
  5974. return false;
  5975. return outputHandler->RecordingActive();
  5976. }
  5977. bool OBSBasic::ReplayBufferActive()
  5978. {
  5979. if (!outputHandler)
  5980. return false;
  5981. return outputHandler->ReplayBufferActive();
  5982. }
  5983. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  5984. : QStyledItemDelegate(parent)
  5985. {
  5986. }
  5987. void SceneRenameDelegate::setEditorData(QWidget *editor,
  5988. const QModelIndex &index) const
  5989. {
  5990. QStyledItemDelegate::setEditorData(editor, index);
  5991. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  5992. if (lineEdit)
  5993. lineEdit->selectAll();
  5994. }
  5995. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  5996. {
  5997. if (event->type() == QEvent::KeyPress) {
  5998. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  5999. if (keyEvent->key() == Qt::Key_Escape) {
  6000. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6001. if (lineEdit)
  6002. lineEdit->undo();
  6003. }
  6004. }
  6005. return QStyledItemDelegate::eventFilter(editor, event);
  6006. }
  6007. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  6008. {
  6009. if (!error.isEmpty())
  6010. return;
  6011. patronJson = QT_TO_UTF8(text);
  6012. }
  6013. void OBSBasic::PauseRecording()
  6014. {
  6015. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6016. return;
  6017. obs_output_t *output = outputHandler->fileOutput;
  6018. if (obs_output_pause(output, true)) {
  6019. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  6020. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  6021. pause->blockSignals(true);
  6022. pause->setChecked(true);
  6023. pause->blockSignals(false);
  6024. os_atomic_set_bool(&recording_paused, true);
  6025. if (api)
  6026. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  6027. if (os_atomic_load_bool(&replaybuf_active))
  6028. ShowReplayBufferPauseWarning();
  6029. }
  6030. }
  6031. void OBSBasic::UnpauseRecording()
  6032. {
  6033. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6034. return;
  6035. obs_output_t *output = outputHandler->fileOutput;
  6036. if (obs_output_pause(output, false)) {
  6037. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6038. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6039. pause->blockSignals(true);
  6040. pause->setChecked(false);
  6041. pause->blockSignals(false);
  6042. os_atomic_set_bool(&recording_paused, false);
  6043. if (api)
  6044. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  6045. }
  6046. }
  6047. void OBSBasic::PauseToggled()
  6048. {
  6049. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6050. return;
  6051. obs_output_t *output = outputHandler->fileOutput;
  6052. bool enable = !obs_output_paused(output);
  6053. if (enable)
  6054. PauseRecording();
  6055. else
  6056. UnpauseRecording();
  6057. }
  6058. void OBSBasic::UpdatePause(bool activate)
  6059. {
  6060. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  6061. pause.reset();
  6062. return;
  6063. }
  6064. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  6065. bool adv = astrcmpi(mode, "Advanced") == 0;
  6066. bool shared;
  6067. if (adv) {
  6068. const char *recType =
  6069. config_get_string(basicConfig, "AdvOut", "RecType");
  6070. if (astrcmpi(recType, "FFmpeg") == 0) {
  6071. shared = config_get_bool(basicConfig, "AdvOut",
  6072. "FFOutputToFile");
  6073. } else {
  6074. const char *recordEncoder = config_get_string(
  6075. basicConfig, "AdvOut", "RecEncoder");
  6076. shared = astrcmpi(recordEncoder, "none") == 0;
  6077. }
  6078. } else {
  6079. const char *quality = config_get_string(
  6080. basicConfig, "SimpleOutput", "RecQuality");
  6081. shared = strcmp(quality, "Stream") == 0;
  6082. }
  6083. if (!shared) {
  6084. pause.reset(new QPushButton());
  6085. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6086. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6087. pause->setCheckable(true);
  6088. pause->setChecked(false);
  6089. pause->setProperty("themeID",
  6090. QVariant(QStringLiteral("pauseIconSmall")));
  6091. connect(pause.data(), &QAbstractButton::clicked, this,
  6092. &OBSBasic::PauseToggled);
  6093. ui->recordingLayout->addWidget(pause.data());
  6094. } else {
  6095. pause.reset();
  6096. }
  6097. }
  6098. #define MBYTE (1024ULL * 1024ULL)
  6099. #define MBYTES_LEFT_STOP_REC 50ULL
  6100. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  6101. const char *OBSBasic::GetCurrentOutputPath()
  6102. {
  6103. const char *path = nullptr;
  6104. const char *mode = config_get_string(Config(), "Output", "Mode");
  6105. if (strcmp(mode, "Advanced") == 0) {
  6106. const char *advanced_mode =
  6107. config_get_string(Config(), "AdvOut", "RecType");
  6108. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6109. path = config_get_string(Config(), "AdvOut",
  6110. "FFFilePath");
  6111. } else {
  6112. path = config_get_string(Config(), "AdvOut",
  6113. "RecFilePath");
  6114. }
  6115. } else {
  6116. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  6117. }
  6118. return path;
  6119. }
  6120. void OBSBasic::DiskSpaceMessage()
  6121. {
  6122. blog(LOG_ERROR, "Recording stopped because of low disk space");
  6123. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  6124. QTStr("Output.RecordNoSpace.Msg"));
  6125. }
  6126. bool OBSBasic::LowDiskSpace()
  6127. {
  6128. const char *path;
  6129. path = GetCurrentOutputPath();
  6130. if (!path)
  6131. return false;
  6132. uint64_t num_bytes = os_get_free_disk_space(path);
  6133. if (num_bytes < (MAX_BYTES_LEFT))
  6134. return true;
  6135. else
  6136. return false;
  6137. }
  6138. void OBSBasic::CheckDiskSpaceRemaining()
  6139. {
  6140. if (LowDiskSpace()) {
  6141. StopRecording();
  6142. StopReplayBuffer();
  6143. DiskSpaceMessage();
  6144. }
  6145. }
  6146. void OBSBasic::ScenesReordered(const QModelIndex &parent, int start, int end,
  6147. const QModelIndex &destination, int row)
  6148. {
  6149. UNUSED_PARAMETER(parent);
  6150. UNUSED_PARAMETER(start);
  6151. UNUSED_PARAMETER(end);
  6152. UNUSED_PARAMETER(destination);
  6153. UNUSED_PARAMETER(row);
  6154. OBSProjector::UpdateMultiviewProjectors();
  6155. }