window-basic-main.cpp 203 KB

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