window-basic-main.cpp 199 KB

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