window-basic-main.cpp 301 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <unordered_set>
  21. #include <obs-data.h>
  22. #include <obs.h>
  23. #include <obs.hpp>
  24. #include <QGuiApplication>
  25. #include <QMessageBox>
  26. #include <QShowEvent>
  27. #include <QDesktopServices>
  28. #include <QFileDialog>
  29. #include <QScreen>
  30. #include <QColorDialog>
  31. #include <QSizePolicy>
  32. #include <QScrollBar>
  33. #include <QTextStream>
  34. #include <QActionGroup>
  35. #include <qt-wrappers.hpp>
  36. #include <util/dstr.h>
  37. #include <util/util.hpp>
  38. #include <util/platform.h>
  39. #include <util/profiler.hpp>
  40. #include <util/dstr.hpp>
  41. #include "obs-app.hpp"
  42. #include "platform.hpp"
  43. #include "visibility-item-widget.hpp"
  44. #include "item-widget-helpers.hpp"
  45. #include "basic-controls.hpp"
  46. #include "window-basic-settings.hpp"
  47. #include "window-namedialog.hpp"
  48. #include "window-basic-auto-config.hpp"
  49. #include "window-basic-source-select.hpp"
  50. #include "window-basic-main.hpp"
  51. #include "window-basic-stats.hpp"
  52. #include "window-basic-main-outputs.hpp"
  53. #include "window-basic-vcam-config.hpp"
  54. #include "window-log-reply.hpp"
  55. #ifdef __APPLE__
  56. #include "window-permissions.hpp"
  57. #endif
  58. #include "window-projector.hpp"
  59. #include "window-remux.hpp"
  60. #ifdef YOUTUBE_ENABLED
  61. #include "auth-youtube.hpp"
  62. #include "window-youtube-actions.hpp"
  63. #include "youtube-api-wrappers.hpp"
  64. #endif
  65. #include "context-bar-controls.hpp"
  66. #include "obs-proxy-style.hpp"
  67. #include "display-helpers.hpp"
  68. #include "volume-control.hpp"
  69. #include "remote-text.hpp"
  70. #include "ui-validation.hpp"
  71. #include "media-controls.hpp"
  72. #include "undo-stack-obs.hpp"
  73. #include <fstream>
  74. #include <sstream>
  75. #ifdef _WIN32
  76. #include "update/win-update.hpp"
  77. #include "update/shared-update.hpp"
  78. #include "windows.h"
  79. #endif
  80. #ifdef WHATSNEW_ENABLED
  81. #include "update/models/whatsnew.hpp"
  82. #endif
  83. #if !defined(_WIN32) && defined(WHATSNEW_ENABLED)
  84. #include "update/shared-update.hpp"
  85. #endif
  86. #ifdef ENABLE_SPARKLE_UPDATER
  87. #include "update/mac-update.hpp"
  88. #endif
  89. #include "ui_OBSBasic.h"
  90. #include "ui_ColorSelect.h"
  91. #include <QWindow>
  92. #ifdef ENABLE_WAYLAND
  93. #include <obs-nix-platform.h>
  94. #endif
  95. using namespace std;
  96. #ifdef BROWSER_AVAILABLE
  97. #include <browser-panel.hpp>
  98. #endif
  99. #include "ui-config.h"
  100. struct QCef;
  101. struct QCefCookieManager;
  102. QCef *cef = nullptr;
  103. QCefCookieManager *panel_cookies = nullptr;
  104. bool cef_js_avail = false;
  105. void DestroyPanelCookieManager();
  106. namespace {
  107. template<typename OBSRef> struct SignalContainer {
  108. OBSRef ref;
  109. vector<shared_ptr<OBSSignal>> handlers;
  110. };
  111. } // namespace
  112. extern volatile long insideEventLoop;
  113. Q_DECLARE_METATYPE(OBSScene);
  114. Q_DECLARE_METATYPE(OBSSceneItem);
  115. Q_DECLARE_METATYPE(OBSSource);
  116. Q_DECLARE_METATYPE(obs_order_movement);
  117. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  118. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  119. {
  120. out << v.ref;
  121. return out;
  122. }
  123. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  124. {
  125. in >> v.ref;
  126. return in;
  127. }
  128. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  129. {
  130. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  131. }
  132. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  133. {
  134. item->setData(static_cast<int>(QtDataRole::OBSRef),
  135. QVariant::fromValue(val));
  136. }
  137. static void AddExtraModulePaths()
  138. {
  139. string plugins_path, plugins_data_path;
  140. char *s;
  141. s = getenv("OBS_PLUGINS_PATH");
  142. if (s)
  143. plugins_path = s;
  144. s = getenv("OBS_PLUGINS_DATA_PATH");
  145. if (s)
  146. plugins_data_path = s;
  147. if (!plugins_path.empty() && !plugins_data_path.empty()) {
  148. string data_path_with_module_suffix;
  149. data_path_with_module_suffix += plugins_data_path;
  150. data_path_with_module_suffix += "/%module%";
  151. obs_add_module_path(plugins_path.c_str(),
  152. data_path_with_module_suffix.c_str());
  153. }
  154. if (portable_mode)
  155. return;
  156. char base_module_dir[512];
  157. #if defined(_WIN32)
  158. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  159. "obs-studio/plugins/%module%");
  160. #elif defined(__APPLE__)
  161. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  162. "obs-studio/plugins/%module%.plugin");
  163. #else
  164. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  165. "obs-studio/plugins/%module%");
  166. #endif
  167. if (ret <= 0)
  168. return;
  169. string path = base_module_dir;
  170. #if defined(__APPLE__)
  171. /* User Application Support Search Path */
  172. obs_add_module_path((path + "/Contents/MacOS").c_str(),
  173. (path + "/Contents/Resources").c_str());
  174. #ifndef __aarch64__
  175. /* Legacy System Library Search Path */
  176. char system_legacy_module_dir[PATH_MAX];
  177. GetProgramDataPath(system_legacy_module_dir,
  178. sizeof(system_legacy_module_dir),
  179. "obs-studio/plugins/%module%");
  180. std::string path_system_legacy = system_legacy_module_dir;
  181. obs_add_module_path((path_system_legacy + "/bin").c_str(),
  182. (path_system_legacy + "/data").c_str());
  183. /* Legacy User Application Support Search Path */
  184. char user_legacy_module_dir[PATH_MAX];
  185. GetConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir),
  186. "obs-studio/plugins/%module%");
  187. std::string path_user_legacy = user_legacy_module_dir;
  188. obs_add_module_path((path_user_legacy + "/bin").c_str(),
  189. (path_user_legacy + "/data").c_str());
  190. #endif
  191. #else
  192. #if ARCH_BITS == 64
  193. obs_add_module_path((path + "/bin/64bit").c_str(),
  194. (path + "/data").c_str());
  195. #else
  196. obs_add_module_path((path + "/bin/32bit").c_str(),
  197. (path + "/data").c_str());
  198. #endif
  199. #endif
  200. }
  201. /* First-party modules considered to be potentially unsafe to load in Safe Mode
  202. * due to them allowing external code (e.g. scripts) to modify OBS's state. */
  203. static const unordered_set<string> unsafe_modules = {
  204. "frontend-tools", // Scripting
  205. "obs-websocket", // Allows outside modifications
  206. };
  207. static void SetSafeModuleNames()
  208. {
  209. #ifndef SAFE_MODULES
  210. return;
  211. #else
  212. string module;
  213. stringstream modules(SAFE_MODULES);
  214. while (getline(modules, module, '|')) {
  215. /* When only disallowing third-party plugins, still add
  216. * "unsafe" bundled modules to the safe list. */
  217. if (disable_3p_plugins || !unsafe_modules.count(module))
  218. obs_add_safe_module(module.c_str());
  219. }
  220. #endif
  221. }
  222. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  223. void assignDockToggle(QDockWidget *dock, QAction *action)
  224. {
  225. auto handleWindowToggle = [action](bool vis) {
  226. action->blockSignals(true);
  227. action->setChecked(vis);
  228. action->blockSignals(false);
  229. };
  230. auto handleMenuToggle = [dock](bool check) {
  231. dock->blockSignals(true);
  232. dock->setVisible(check);
  233. dock->blockSignals(false);
  234. };
  235. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  236. handleWindowToggle);
  237. dock->connect(action, &QAction::toggled, handleMenuToggle);
  238. }
  239. void setupDockAction(QDockWidget *dock)
  240. {
  241. QAction *action = dock->toggleViewAction();
  242. auto neverDisable = [action]() {
  243. QSignalBlocker block(action);
  244. action->setEnabled(true);
  245. };
  246. auto newToggleView = [dock](bool check) {
  247. QSignalBlocker block(dock);
  248. dock->setVisible(check);
  249. };
  250. // Replace the slot connected by default
  251. QObject::disconnect(action, &QAction::triggered, nullptr, 0);
  252. dock->connect(action, &QAction::triggered, newToggleView);
  253. // Make the action unable to be disabled
  254. action->connect(action, &QAction::enabledChanged, neverDisable);
  255. }
  256. extern void RegisterTwitchAuth();
  257. extern void RegisterRestreamAuth();
  258. #ifdef YOUTUBE_ENABLED
  259. extern void RegisterYoutubeAuth();
  260. #endif
  261. OBSBasic::OBSBasic(QWidget *parent)
  262. : OBSMainWindow(parent),
  263. undo_s(ui),
  264. ui(new Ui::OBSBasic)
  265. {
  266. setAttribute(Qt::WA_NativeWindow);
  267. #ifdef TWITCH_ENABLED
  268. RegisterTwitchAuth();
  269. #endif
  270. #ifdef RESTREAM_ENABLED
  271. RegisterRestreamAuth();
  272. #endif
  273. #ifdef YOUTUBE_ENABLED
  274. RegisterYoutubeAuth();
  275. #endif
  276. setAcceptDrops(true);
  277. setContextMenuPolicy(Qt::CustomContextMenu);
  278. QEvent::registerEventType(QEvent::User + QEvent::Close);
  279. api = InitializeAPIInterface(this);
  280. ui->setupUi(this);
  281. ui->previewDisabledWidget->setVisible(false);
  282. /* Set up streaming connections */
  283. connect(
  284. this, &OBSBasic::StreamingStarting, this,
  285. [this] { this->streamingStarting = true; },
  286. Qt::DirectConnection);
  287. connect(
  288. this, &OBSBasic::StreamingStarted, this,
  289. [this] { this->streamingStarting = false; },
  290. Qt::DirectConnection);
  291. connect(
  292. this, &OBSBasic::StreamingStopped, this,
  293. [this] { this->streamingStarting = false; },
  294. Qt::DirectConnection);
  295. /* Set up recording connections */
  296. connect(
  297. this, &OBSBasic::RecordingStarted, this,
  298. [this]() {
  299. this->recordingStarted = true;
  300. this->recordingPaused = false;
  301. },
  302. Qt::DirectConnection);
  303. connect(
  304. this, &OBSBasic::RecordingPaused, this,
  305. [this]() { this->recordingPaused = true; },
  306. Qt::DirectConnection);
  307. connect(
  308. this, &OBSBasic::RecordingUnpaused, this,
  309. [this]() { this->recordingPaused = false; },
  310. Qt::DirectConnection);
  311. connect(
  312. this, &OBSBasic::RecordingStopped, this,
  313. [this]() {
  314. this->recordingStarted = false;
  315. this->recordingPaused = false;
  316. },
  317. Qt::DirectConnection);
  318. /* Add controls dock */
  319. OBSBasicControls *controls = new OBSBasicControls(this);
  320. controlsDock = new OBSDock(this);
  321. controlsDock->setObjectName(QString::fromUtf8("controlsDock"));
  322. controlsDock->setWindowTitle(QTStr("Basic.Main.Controls"));
  323. /* Parenting is done there so controls will be deleted alongside controlsDock */
  324. controlsDock->setWidget(controls);
  325. addDockWidget(Qt::BottomDockWidgetArea, controlsDock);
  326. connect(controls, &OBSBasicControls::StreamButtonClicked, this,
  327. &OBSBasic::StreamActionTriggered);
  328. connect(controls, &OBSBasicControls::StartStreamMenuActionClicked, this,
  329. &OBSBasic::StartStreaming);
  330. connect(controls, &OBSBasicControls::StopStreamMenuActionClicked, this,
  331. &OBSBasic::StopStreaming);
  332. connect(controls, &OBSBasicControls::ForceStopStreamMenuActionClicked,
  333. this, &OBSBasic::ForceStopStreaming);
  334. connect(controls, &OBSBasicControls::BroadcastButtonClicked, this,
  335. &OBSBasic::BroadcastButtonClicked);
  336. connect(controls, &OBSBasicControls::RecordButtonClicked, this,
  337. &OBSBasic::RecordActionTriggered);
  338. connect(controls, &OBSBasicControls::PauseRecordButtonClicked, this,
  339. &OBSBasic::RecordPauseToggled);
  340. connect(controls, &OBSBasicControls::ReplayBufferButtonClicked, this,
  341. &OBSBasic::ReplayBufferActionTriggered);
  342. connect(controls, &OBSBasicControls::SaveReplayBufferButtonClicked,
  343. this, &OBSBasic::ReplayBufferSave);
  344. connect(controls, &OBSBasicControls::VirtualCamButtonClicked, this,
  345. &OBSBasic::VirtualCamActionTriggered);
  346. connect(controls, &OBSBasicControls::VirtualCamConfigButtonClicked,
  347. this, &OBSBasic::OpenVirtualCamConfig);
  348. connect(controls, &OBSBasicControls::StudioModeButtonClicked, this,
  349. &OBSBasic::TogglePreviewProgramMode);
  350. connect(controls, &OBSBasicControls::SettingsButtonClicked, this,
  351. &OBSBasic::on_action_Settings_triggered);
  352. connect(controls, &OBSBasicControls::ExitButtonClicked, this,
  353. &QMainWindow::close);
  354. startingDockLayout = saveState();
  355. statsDock = new OBSDock();
  356. statsDock->setObjectName(QStringLiteral("statsDock"));
  357. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  358. QDockWidget::DockWidgetMovable |
  359. QDockWidget::DockWidgetFloatable);
  360. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  361. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  362. statsDock->setVisible(false);
  363. statsDock->setFloating(true);
  364. statsDock->resize(700, 200);
  365. copyActionsDynamicProperties();
  366. qRegisterMetaType<int64_t>("int64_t");
  367. qRegisterMetaType<uint32_t>("uint32_t");
  368. qRegisterMetaType<OBSScene>("OBSScene");
  369. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  370. qRegisterMetaType<OBSSource>("OBSSource");
  371. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  372. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  373. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  374. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  375. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  376. "gridMode");
  377. ui->scenes->SetGridMode(sceneGrid);
  378. if (sceneGrid)
  379. ui->actionSceneGridMode->setChecked(true);
  380. else
  381. ui->actionSceneListMode->setChecked(true);
  382. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  383. auto displayResize = [this]() {
  384. struct obs_video_info ovi;
  385. if (obs_get_video_info(&ovi))
  386. ResizePreview(ovi.base_width, ovi.base_height);
  387. UpdateContextBarVisibility();
  388. dpi = devicePixelRatioF();
  389. };
  390. dpi = devicePixelRatioF();
  391. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  392. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  393. delete shortcutFilter;
  394. shortcutFilter = CreateShortcutFilter();
  395. installEventFilter(shortcutFilter);
  396. stringstream name;
  397. name << "OBS " << App()->GetVersionString();
  398. blog(LOG_INFO, "%s", name.str().c_str());
  399. blog(LOG_INFO, "---------------------------------");
  400. UpdateTitleBar();
  401. connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor,
  402. this, &OBSBasic::SceneNameEdited);
  403. cpuUsageInfo = os_cpu_usage_info_start();
  404. cpuUsageTimer = new QTimer(this);
  405. connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar,
  406. &OBSBasicStatusBar::UpdateCPUUsage);
  407. cpuUsageTimer->start(3000);
  408. diskFullTimer = new QTimer(this);
  409. connect(diskFullTimer, &QTimer::timeout, this,
  410. &OBSBasic::CheckDiskSpaceRemaining);
  411. renameScene = new QAction(QTStr("Rename"), ui->scenesDock);
  412. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  413. connect(renameScene, &QAction::triggered, this,
  414. &OBSBasic::EditSceneName);
  415. ui->scenesDock->addAction(renameScene);
  416. renameSource = new QAction(QTStr("Rename"), ui->sourcesDock);
  417. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  418. connect(renameSource, &QAction::triggered, this,
  419. &OBSBasic::EditSceneItemName);
  420. ui->sourcesDock->addAction(renameSource);
  421. #ifdef __APPLE__
  422. renameScene->setShortcut({Qt::Key_Return});
  423. renameSource->setShortcut({Qt::Key_Return});
  424. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  425. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  426. ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole);
  427. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  428. ui->actionShowMacPermissions->setMenuRole(
  429. QAction::ApplicationSpecificRole);
  430. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  431. #else
  432. renameScene->setShortcut({Qt::Key_F2});
  433. renameSource->setShortcut({Qt::Key_F2});
  434. #endif
  435. #ifdef __linux__
  436. ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q);
  437. #endif
  438. auto addNudge = [this](const QKeySequence &seq, MoveDir direction,
  439. int distance) {
  440. QAction *nudge = new QAction(ui->preview);
  441. nudge->setShortcut(seq);
  442. nudge->setShortcutContext(Qt::WidgetShortcut);
  443. ui->preview->addAction(nudge);
  444. connect(nudge, &QAction::triggered,
  445. [this, distance, direction]() {
  446. Nudge(distance, direction);
  447. });
  448. };
  449. addNudge(Qt::Key_Up, MoveDir::Up, 1);
  450. addNudge(Qt::Key_Down, MoveDir::Down, 1);
  451. addNudge(Qt::Key_Left, MoveDir::Left, 1);
  452. addNudge(Qt::Key_Right, MoveDir::Right, 1);
  453. addNudge(Qt::SHIFT | Qt::Key_Up, MoveDir::Up, 10);
  454. addNudge(Qt::SHIFT | Qt::Key_Down, MoveDir::Down, 10);
  455. addNudge(Qt::SHIFT | Qt::Key_Left, MoveDir::Left, 10);
  456. addNudge(Qt::SHIFT | Qt::Key_Right, MoveDir::Right, 10);
  457. /* Setup dock toggle action
  458. * And hide all docks before restoring parent geometry */
  459. #define SETUP_DOCK(dock) \
  460. setupDockAction(dock); \
  461. ui->menuDocks->addAction(dock->toggleViewAction()); \
  462. dock->setVisible(false);
  463. SETUP_DOCK(ui->scenesDock);
  464. SETUP_DOCK(ui->sourcesDock);
  465. SETUP_DOCK(ui->mixerDock);
  466. SETUP_DOCK(ui->transitionsDock);
  467. SETUP_DOCK(controlsDock);
  468. SETUP_DOCK(statsDock);
  469. #undef SETUP_DOCK
  470. // Register shortcuts for Undo/Redo
  471. ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z);
  472. QList<QKeySequence> shrt;
  473. shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z)
  474. << QKeySequence(Qt::CTRL | Qt::Key_Y);
  475. ui->actionMainRedo->setShortcuts(shrt);
  476. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  477. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  478. QPoint curPos;
  479. //restore parent window geometry
  480. const char *geometry = config_get_string(App()->GlobalConfig(),
  481. "BasicWindow", "geometry");
  482. if (geometry != NULL) {
  483. QByteArray byteArray =
  484. QByteArray::fromBase64(QByteArray(geometry));
  485. restoreGeometry(byteArray);
  486. QRect windowGeometry = normalGeometry();
  487. if (!WindowPositionValid(windowGeometry)) {
  488. QRect rect =
  489. QGuiApplication::primaryScreen()->geometry();
  490. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  491. Qt::AlignCenter, size(),
  492. rect));
  493. }
  494. curPos = pos();
  495. } else {
  496. QRect desktopRect =
  497. QGuiApplication::primaryScreen()->geometry();
  498. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  499. curPos = QPoint(adjSize.width(), adjSize.height());
  500. }
  501. QPoint curSize(width(), height());
  502. QPoint statsDockSize(statsDock->width(), statsDock->height());
  503. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  504. QPoint newPos = curPos + statsDockPos;
  505. statsDock->move(newPos);
  506. #ifdef HAVE_OBSCONFIG_H
  507. ui->actionReleaseNotes->setVisible(true);
  508. #endif
  509. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  510. connect(ui->enablePreviewButton, &QPushButton::clicked, this,
  511. &OBSBasic::TogglePreview);
  512. connect(ui->scenes, &SceneTree::scenesReordered,
  513. []() { OBSProjector::UpdateMultiviewProjectors(); });
  514. connect(App(), &OBSApp::StyleChanged, this,
  515. [this]() { OnEvent(OBS_FRONTEND_EVENT_THEME_CHANGED); });
  516. QActionGroup *actionGroup = new QActionGroup(this);
  517. actionGroup->addAction(ui->actionSceneListMode);
  518. actionGroup->addAction(ui->actionSceneGridMode);
  519. UpdatePreviewSafeAreas();
  520. UpdatePreviewSpacingHelpers();
  521. UpdatePreviewOverflowSettings();
  522. }
  523. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  524. vector<OBSSource> &audioSources)
  525. {
  526. OBSSourceAutoRelease source = obs_get_output_source(channel);
  527. if (!source)
  528. return;
  529. audioSources.push_back(source.Get());
  530. OBSDataAutoRelease data = obs_save_source(source);
  531. obs_data_set_obj(parent, name, data);
  532. }
  533. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  534. obs_data_array_t *quickTransitionData,
  535. int transitionDuration,
  536. obs_data_array_t *transitions,
  537. OBSScene &scene, OBSSource &curProgramScene,
  538. obs_data_array_t *savedProjectorList)
  539. {
  540. obs_data_t *saveData = obs_data_create();
  541. vector<OBSSource> audioSources;
  542. audioSources.reserve(6);
  543. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  544. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  545. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  546. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  547. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  548. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  549. /* -------------------------------- */
  550. /* save non-group sources */
  551. auto FilterAudioSources = [&](obs_source_t *source) {
  552. if (obs_source_is_group(source))
  553. return false;
  554. return find(begin(audioSources), end(audioSources), source) ==
  555. end(audioSources);
  556. };
  557. using FilterAudioSources_t = decltype(FilterAudioSources);
  558. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  559. [](void *data, obs_source_t *source) {
  560. auto &func = *static_cast<FilterAudioSources_t *>(data);
  561. return func(source);
  562. },
  563. static_cast<void *>(&FilterAudioSources));
  564. /* -------------------------------- */
  565. /* save group sources separately */
  566. /* saving separately ensures they won't be loaded in older versions */
  567. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  568. [](void *, obs_source_t *source) {
  569. return obs_source_is_group(source);
  570. },
  571. nullptr);
  572. /* -------------------------------- */
  573. OBSSourceAutoRelease transition = obs_get_output_source(0);
  574. obs_source_t *currentScene = obs_scene_get_source(scene);
  575. const char *sceneName = obs_source_get_name(currentScene);
  576. const char *programName = obs_source_get_name(curProgramScene);
  577. const char *sceneCollection = config_get_string(
  578. App()->GlobalConfig(), "Basic", "SceneCollection");
  579. obs_data_set_string(saveData, "current_scene", sceneName);
  580. obs_data_set_string(saveData, "current_program_scene", programName);
  581. obs_data_set_array(saveData, "scene_order", sceneOrder);
  582. obs_data_set_string(saveData, "name", sceneCollection);
  583. obs_data_set_array(saveData, "sources", sourcesArray);
  584. obs_data_set_array(saveData, "groups", groupsArray);
  585. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  586. obs_data_set_array(saveData, "transitions", transitions);
  587. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  588. obs_data_array_release(sourcesArray);
  589. obs_data_array_release(groupsArray);
  590. obs_data_set_string(saveData, "current_transition",
  591. obs_source_get_name(transition));
  592. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  593. return saveData;
  594. }
  595. void OBSBasic::copyActionsDynamicProperties()
  596. {
  597. // Themes need the QAction dynamic properties
  598. for (QAction *x : ui->scenesToolbar->actions()) {
  599. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  600. if (!temp)
  601. continue;
  602. for (QByteArray &y : x->dynamicPropertyNames()) {
  603. temp->setProperty(y, x->property(y));
  604. }
  605. }
  606. for (QAction *x : ui->sourcesToolbar->actions()) {
  607. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  608. if (!temp)
  609. continue;
  610. for (QByteArray &y : x->dynamicPropertyNames()) {
  611. temp->setProperty(y, x->property(y));
  612. }
  613. }
  614. for (QAction *x : ui->mixerToolbar->actions()) {
  615. QWidget *temp = ui->mixerToolbar->widgetForAction(x);
  616. if (!temp)
  617. continue;
  618. for (QByteArray &y : x->dynamicPropertyNames()) {
  619. temp->setProperty(y, x->property(y));
  620. }
  621. }
  622. }
  623. void OBSBasic::UpdateVolumeControlsDecayRate()
  624. {
  625. double meterDecayRate =
  626. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  627. for (size_t i = 0; i < volumes.size(); i++) {
  628. volumes[i]->SetMeterDecayRate(meterDecayRate);
  629. }
  630. }
  631. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  632. {
  633. uint32_t peakMeterTypeIdx =
  634. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  635. enum obs_peak_meter_type peakMeterType;
  636. switch (peakMeterTypeIdx) {
  637. case 0:
  638. peakMeterType = SAMPLE_PEAK_METER;
  639. break;
  640. case 1:
  641. peakMeterType = TRUE_PEAK_METER;
  642. break;
  643. default:
  644. peakMeterType = SAMPLE_PEAK_METER;
  645. break;
  646. }
  647. for (size_t i = 0; i < volumes.size(); i++) {
  648. volumes[i]->setPeakMeterType(peakMeterType);
  649. }
  650. }
  651. void OBSBasic::ClearVolumeControls()
  652. {
  653. for (VolControl *vol : volumes)
  654. delete vol;
  655. volumes.clear();
  656. }
  657. void OBSBasic::RefreshVolumeColors()
  658. {
  659. for (VolControl *vol : volumes) {
  660. vol->refreshColors();
  661. }
  662. }
  663. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  664. {
  665. obs_data_array_t *sceneOrder = obs_data_array_create();
  666. for (int i = 0; i < ui->scenes->count(); i++) {
  667. OBSDataAutoRelease data = obs_data_create();
  668. obs_data_set_string(data, "name",
  669. QT_TO_UTF8(ui->scenes->item(i)->text()));
  670. obs_data_array_push_back(sceneOrder, data);
  671. }
  672. return sceneOrder;
  673. }
  674. obs_data_array_t *OBSBasic::SaveProjectors()
  675. {
  676. obs_data_array_t *savedProjectors = obs_data_array_create();
  677. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  678. if (!projector)
  679. return;
  680. OBSDataAutoRelease data = obs_data_create();
  681. ProjectorType type = projector->GetProjectorType();
  682. switch (type) {
  683. case ProjectorType::Scene:
  684. case ProjectorType::Source: {
  685. OBSSource source = projector->GetSource();
  686. const char *name = obs_source_get_name(source);
  687. obs_data_set_string(data, "name", name);
  688. break;
  689. }
  690. default:
  691. break;
  692. }
  693. obs_data_set_int(data, "monitor", projector->GetMonitor());
  694. obs_data_set_int(data, "type", static_cast<int>(type));
  695. obs_data_set_string(
  696. data, "geometry",
  697. projector->saveGeometry().toBase64().constData());
  698. if (projector->IsAlwaysOnTopOverridden())
  699. obs_data_set_bool(data, "alwaysOnTop",
  700. projector->IsAlwaysOnTop());
  701. obs_data_set_bool(data, "alwaysOnTopOverridden",
  702. projector->IsAlwaysOnTopOverridden());
  703. obs_data_array_push_back(savedProjectors, data);
  704. };
  705. for (size_t i = 0; i < projectors.size(); i++)
  706. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  707. return savedProjectors;
  708. }
  709. void OBSBasic::Save(const char *file)
  710. {
  711. OBSScene scene = GetCurrentScene();
  712. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  713. if (!curProgramScene)
  714. curProgramScene = obs_scene_get_source(scene);
  715. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  716. OBSDataArrayAutoRelease transitions = SaveTransitions();
  717. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  718. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  719. OBSDataAutoRelease saveData = GenerateSaveData(
  720. sceneOrder, quickTrData, ui->transitionDuration->value(),
  721. transitions, scene, curProgramScene, savedProjectorList);
  722. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  723. obs_data_set_bool(saveData, "scaling_enabled",
  724. ui->preview->IsFixedScaling());
  725. obs_data_set_int(saveData, "scaling_level",
  726. ui->preview->GetScalingLevel());
  727. obs_data_set_double(saveData, "scaling_off_x",
  728. ui->preview->GetScrollX());
  729. obs_data_set_double(saveData, "scaling_off_y",
  730. ui->preview->GetScrollY());
  731. if (vcamEnabled) {
  732. OBSDataAutoRelease obj = obs_data_create();
  733. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  734. switch (vcamConfig.type) {
  735. case VCamOutputType::Invalid:
  736. case VCamOutputType::ProgramView:
  737. case VCamOutputType::PreviewOutput:
  738. break;
  739. case VCamOutputType::SceneOutput:
  740. obs_data_set_string(obj, "scene",
  741. vcamConfig.scene.c_str());
  742. break;
  743. case VCamOutputType::SourceOutput:
  744. obs_data_set_string(obj, "source",
  745. vcamConfig.source.c_str());
  746. break;
  747. }
  748. obs_data_set_obj(saveData, "virtual-camera", obj);
  749. }
  750. if (api) {
  751. if (!collectionModuleData)
  752. collectionModuleData = obs_data_create();
  753. api->on_save(collectionModuleData);
  754. obs_data_set_obj(saveData, "modules", collectionModuleData);
  755. }
  756. if (lastOutputResolution) {
  757. OBSDataAutoRelease res = obs_data_create();
  758. obs_data_set_int(res, "x", lastOutputResolution->first);
  759. obs_data_set_int(res, "y", lastOutputResolution->second);
  760. obs_data_set_obj(saveData, "resolution", res);
  761. }
  762. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  763. blog(LOG_ERROR, "Could not save scene data to %s", file);
  764. }
  765. void OBSBasic::DeferSaveBegin()
  766. {
  767. os_atomic_inc_long(&disableSaving);
  768. }
  769. void OBSBasic::DeferSaveEnd()
  770. {
  771. long result = os_atomic_dec_long(&disableSaving);
  772. if (result == 0) {
  773. SaveProject();
  774. }
  775. }
  776. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  777. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  778. {
  779. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  780. if (!data)
  781. return;
  782. OBSSourceAutoRelease source = obs_load_source(data);
  783. if (!source)
  784. return;
  785. obs_set_output_source(channel, source);
  786. const char *source_name = obs_source_get_name(source);
  787. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  788. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  789. obs_monitoring_type monitoring_type =
  790. obs_source_get_monitoring_type(source);
  791. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  792. const char *type =
  793. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  794. ? "monitor only"
  795. : "monitor and output";
  796. blog(LOG_INFO, " - monitoring: %s", type);
  797. }
  798. }
  799. static inline bool HasAudioDevices(const char *source_id)
  800. {
  801. const char *output_id = source_id;
  802. obs_properties_t *props = obs_get_source_properties(output_id);
  803. size_t count = 0;
  804. if (!props)
  805. return false;
  806. obs_property_t *devices = obs_properties_get(props, "device_id");
  807. if (devices)
  808. count = obs_property_list_item_count(devices);
  809. obs_properties_destroy(props);
  810. return count != 0;
  811. }
  812. void OBSBasic::CreateFirstRunSources()
  813. {
  814. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  815. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  816. #ifdef __APPLE__
  817. hasDesktopAudio = hasDesktopAudio && shouldCreateDefaultAudioSource();
  818. #endif
  819. if (hasDesktopAudio)
  820. ResetAudioDevice(App()->OutputAudioSource(), "default",
  821. Str("Basic.DesktopDevice1"), 1);
  822. if (hasInputAudio)
  823. ResetAudioDevice(App()->InputAudioSource(), "default",
  824. Str("Basic.AuxDevice1"), 3);
  825. }
  826. void OBSBasic::CreateDefaultScene(bool firstStart)
  827. {
  828. disableSaving++;
  829. ClearSceneData();
  830. InitDefaultTransitions();
  831. CreateDefaultQuickTransitions();
  832. ui->transitionDuration->setValue(300);
  833. SetTransition(fadeTransition);
  834. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  835. if (firstStart)
  836. CreateFirstRunSources();
  837. SetCurrentScene(scene, true);
  838. disableSaving--;
  839. }
  840. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  841. {
  842. for (int i = 0; i < lw->count(); i++) {
  843. QListWidgetItem *item = lw->item(i);
  844. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  845. if (newIndex != i) {
  846. item = lw->takeItem(i);
  847. lw->insertItem(newIndex, item);
  848. }
  849. break;
  850. }
  851. }
  852. }
  853. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  854. {
  855. size_t num = obs_data_array_count(array);
  856. for (size_t i = 0; i < num; i++) {
  857. OBSDataAutoRelease data = obs_data_array_item(array, i);
  858. const char *name = obs_data_get_string(data, "name");
  859. ReorderItemByName(ui->scenes, name, (int)i);
  860. }
  861. }
  862. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  863. {
  864. for (SavedProjectorInfo *info : savedProjectorsArray) {
  865. delete info;
  866. }
  867. savedProjectorsArray.clear();
  868. size_t num = obs_data_array_count(array);
  869. for (size_t i = 0; i < num; i++) {
  870. OBSDataAutoRelease data = obs_data_array_item(array, i);
  871. SavedProjectorInfo *info = new SavedProjectorInfo();
  872. info->monitor = obs_data_get_int(data, "monitor");
  873. info->type = static_cast<ProjectorType>(
  874. obs_data_get_int(data, "type"));
  875. info->geometry =
  876. std::string(obs_data_get_string(data, "geometry"));
  877. info->name = std::string(obs_data_get_string(data, "name"));
  878. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  879. info->alwaysOnTopOverridden =
  880. obs_data_get_bool(data, "alwaysOnTopOverridden");
  881. savedProjectorsArray.emplace_back(info);
  882. }
  883. }
  884. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  885. {
  886. const char *name = obs_source_get_name(filter);
  887. const char *id = obs_source_get_id(filter);
  888. int val = (int)(intptr_t)v_val;
  889. string indent;
  890. for (int i = 0; i < val; i++)
  891. indent += " ";
  892. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  893. }
  894. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  895. {
  896. obs_source_t *source = obs_sceneitem_get_source(item);
  897. const char *name = obs_source_get_name(source);
  898. const char *id = obs_source_get_id(source);
  899. int indent_count = (int)(intptr_t)v_val;
  900. string indent;
  901. for (int i = 0; i < indent_count; i++)
  902. indent += " ";
  903. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  904. obs_monitoring_type monitoring_type =
  905. obs_source_get_monitoring_type(source);
  906. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  907. const char *type =
  908. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  909. ? "monitor only"
  910. : "monitor and output";
  911. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  912. }
  913. int child_indent = 1 + indent_count;
  914. obs_source_enum_filters(source, LogFilter,
  915. (void *)(intptr_t)child_indent);
  916. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  917. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  918. if (show_tn)
  919. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  920. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  921. if (hide_tn)
  922. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  923. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  924. if (obs_sceneitem_is_group(item))
  925. obs_sceneitem_group_enum_items(item, LogSceneItem,
  926. (void *)(intptr_t)child_indent);
  927. return true;
  928. }
  929. void OBSBasic::LogScenes()
  930. {
  931. blog(LOG_INFO, "------------------------------------------------");
  932. blog(LOG_INFO, "Loaded scenes:");
  933. for (int i = 0; i < ui->scenes->count(); i++) {
  934. QListWidgetItem *item = ui->scenes->item(i);
  935. OBSScene scene = GetOBSRef<OBSScene>(item);
  936. obs_source_t *source = obs_scene_get_source(scene);
  937. const char *name = obs_source_get_name(source);
  938. blog(LOG_INFO, "- scene '%s':", name);
  939. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  940. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  941. }
  942. blog(LOG_INFO, "------------------------------------------------");
  943. }
  944. void OBSBasic::Load(const char *file)
  945. {
  946. disableSaving++;
  947. lastOutputResolution.reset();
  948. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  949. if (!data) {
  950. disableSaving--;
  951. const auto path = filesystem::u8path(file);
  952. const string name = path.stem().u8string();
  953. /* Check if file exists but failed to load. */
  954. if (filesystem::exists(path)) {
  955. /* Assume the file is corrupt and rename it to allow
  956. * for manual recovery if possible. */
  957. auto newPath = path;
  958. newPath.concat(".invalid");
  959. blog(LOG_WARNING,
  960. "File exists but appears to be corrupt, renaming "
  961. "to \"%s\" before continuing.",
  962. newPath.filename().u8string().c_str());
  963. error_code ec;
  964. filesystem::rename(path, newPath, ec);
  965. if (ec) {
  966. blog(LOG_ERROR,
  967. "Failed renaming corrupt file with %d",
  968. ec.value());
  969. }
  970. }
  971. config_set_string(App()->GlobalConfig(), "Basic",
  972. "SceneCollection", name.c_str());
  973. config_set_string(App()->GlobalConfig(), "Basic",
  974. "SceneCollectionFile", name.c_str());
  975. blog(LOG_INFO, "No scene file found, creating default scene");
  976. CreateDefaultScene(true);
  977. SaveProject();
  978. return;
  979. }
  980. LoadData(data, file);
  981. }
  982. static inline void AddMissingFiles(void *data, obs_source_t *source)
  983. {
  984. obs_missing_files_t *f = (obs_missing_files_t *)data;
  985. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  986. obs_missing_files_append(f, sf);
  987. obs_missing_files_destroy(sf);
  988. }
  989. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  990. {
  991. ClearSceneData();
  992. ClearContextBar();
  993. /* Exit OBS if clearing scene data failed for some reason. */
  994. if (clearingFailed) {
  995. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"),
  996. QTStr("SourceLeak.Text"));
  997. close();
  998. return;
  999. }
  1000. InitDefaultTransitions();
  1001. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  1002. devicePropertiesThread->wait();
  1003. devicePropertiesThread.reset();
  1004. }
  1005. QApplication::sendPostedEvents(nullptr);
  1006. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  1007. if (api)
  1008. api->on_preload(modulesObj);
  1009. /* Keep a reference to "modules" data so plugins that are not loaded do
  1010. * not have their collection specific data lost. */
  1011. collectionModuleData = obs_data_get_obj(data, "modules");
  1012. OBSDataArrayAutoRelease sceneOrder =
  1013. obs_data_get_array(data, "scene_order");
  1014. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  1015. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  1016. OBSDataArrayAutoRelease transitions =
  1017. obs_data_get_array(data, "transitions");
  1018. const char *sceneName = obs_data_get_string(data, "current_scene");
  1019. const char *programSceneName =
  1020. obs_data_get_string(data, "current_program_scene");
  1021. const char *transitionName =
  1022. obs_data_get_string(data, "current_transition");
  1023. if (!opt_starting_scene.empty()) {
  1024. programSceneName = opt_starting_scene.c_str();
  1025. if (!IsPreviewProgramMode())
  1026. sceneName = opt_starting_scene.c_str();
  1027. }
  1028. int newDuration = obs_data_get_int(data, "transition_duration");
  1029. if (!newDuration)
  1030. newDuration = 300;
  1031. if (!transitionName)
  1032. transitionName = obs_source_get_name(fadeTransition);
  1033. const char *curSceneCollection = config_get_string(
  1034. App()->GlobalConfig(), "Basic", "SceneCollection");
  1035. obs_data_set_default_string(data, "name", curSceneCollection);
  1036. const char *name = obs_data_get_string(data, "name");
  1037. OBSSourceAutoRelease curScene;
  1038. OBSSourceAutoRelease curProgramScene;
  1039. obs_source_t *curTransition;
  1040. if (!name || !*name)
  1041. name = curSceneCollection;
  1042. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  1043. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  1044. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  1045. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  1046. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  1047. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  1048. if (!sources) {
  1049. sources = std::move(groups);
  1050. } else {
  1051. obs_data_array_push_back_array(sources, groups);
  1052. }
  1053. obs_missing_files_t *files = obs_missing_files_create();
  1054. obs_load_sources(sources, AddMissingFiles, files);
  1055. if (transitions)
  1056. LoadTransitions(transitions, AddMissingFiles, files);
  1057. if (sceneOrder)
  1058. LoadSceneListOrder(sceneOrder);
  1059. curTransition = FindTransition(transitionName);
  1060. if (!curTransition)
  1061. curTransition = fadeTransition;
  1062. ui->transitionDuration->setValue(newDuration);
  1063. SetTransition(curTransition);
  1064. retryScene:
  1065. curScene = obs_get_source_by_name(sceneName);
  1066. curProgramScene = obs_get_source_by_name(programSceneName);
  1067. /* if the starting scene command line parameter is bad at all,
  1068. * fall back to original settings */
  1069. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  1070. sceneName = obs_data_get_string(data, "current_scene");
  1071. programSceneName =
  1072. obs_data_get_string(data, "current_program_scene");
  1073. opt_starting_scene.clear();
  1074. goto retryScene;
  1075. }
  1076. if (!curScene) {
  1077. auto find_scene_cb = [](void *source_ptr, obs_source_t *scene) {
  1078. *static_cast<OBSSourceAutoRelease *>(source_ptr) =
  1079. obs_source_get_ref(scene);
  1080. return false;
  1081. };
  1082. obs_enum_scenes(find_scene_cb, &curScene);
  1083. }
  1084. SetCurrentScene(curScene.Get(), true);
  1085. if (!curProgramScene)
  1086. curProgramScene = std::move(curScene);
  1087. if (IsPreviewProgramMode())
  1088. TransitionToScene(curProgramScene.Get(), true);
  1089. /* ------------------- */
  1090. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  1091. "SaveProjectors");
  1092. if (projectorSave) {
  1093. OBSDataArrayAutoRelease savedProjectors =
  1094. obs_data_get_array(data, "saved_projectors");
  1095. if (savedProjectors) {
  1096. LoadSavedProjectors(savedProjectors);
  1097. OpenSavedProjectors();
  1098. activateWindow();
  1099. }
  1100. }
  1101. /* ------------------- */
  1102. std::string file_base = strrchr(file, '/') + 1;
  1103. file_base.erase(file_base.size() - 5, 5);
  1104. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  1105. name);
  1106. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  1107. file_base.c_str());
  1108. OBSDataArrayAutoRelease quickTransitionData =
  1109. obs_data_get_array(data, "quick_transitions");
  1110. LoadQuickTransitions(quickTransitionData);
  1111. RefreshQuickTransitions();
  1112. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1113. ui->preview->SetLocked(previewLocked);
  1114. ui->actionLockPreview->setChecked(previewLocked);
  1115. /* ---------------------- */
  1116. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1117. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1118. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1119. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1120. if (fixedScaling) {
  1121. ui->preview->SetScalingLevel(scalingLevel);
  1122. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1123. }
  1124. ui->preview->SetFixedScaling(fixedScaling);
  1125. emit ui->preview->DisplayResized();
  1126. if (vcamEnabled) {
  1127. OBSDataAutoRelease obj =
  1128. obs_data_get_obj(data, "virtual-camera");
  1129. vcamConfig.type =
  1130. (VCamOutputType)obs_data_get_int(obj, "type2");
  1131. if (vcamConfig.type == VCamOutputType::Invalid)
  1132. vcamConfig.type =
  1133. (VCamOutputType)obs_data_get_int(obj, "type");
  1134. if (vcamConfig.type == VCamOutputType::Invalid) {
  1135. VCamInternalType internal =
  1136. (VCamInternalType)obs_data_get_int(obj,
  1137. "internal");
  1138. switch (internal) {
  1139. case VCamInternalType::Default:
  1140. vcamConfig.type = VCamOutputType::ProgramView;
  1141. break;
  1142. case VCamInternalType::Preview:
  1143. vcamConfig.type = VCamOutputType::PreviewOutput;
  1144. break;
  1145. }
  1146. }
  1147. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1148. vcamConfig.source = obs_data_get_string(obj, "source");
  1149. }
  1150. if (obs_data_has_user_value(data, "resolution")) {
  1151. OBSDataAutoRelease res = obs_data_get_obj(data, "resolution");
  1152. if (obs_data_has_user_value(res, "x") &&
  1153. obs_data_has_user_value(res, "y")) {
  1154. lastOutputResolution = {obs_data_get_int(res, "x"),
  1155. obs_data_get_int(res, "y")};
  1156. }
  1157. }
  1158. /* ---------------------- */
  1159. if (api)
  1160. api->on_load(modulesObj);
  1161. obs_data_release(data);
  1162. if (!opt_starting_scene.empty())
  1163. opt_starting_scene.clear();
  1164. if (opt_start_streaming && !safe_mode) {
  1165. blog(LOG_INFO, "Starting stream due to command line parameter");
  1166. QMetaObject::invokeMethod(this, "StartStreaming",
  1167. Qt::QueuedConnection);
  1168. opt_start_streaming = false;
  1169. }
  1170. if (opt_start_recording && !safe_mode) {
  1171. blog(LOG_INFO,
  1172. "Starting recording due to command line parameter");
  1173. QMetaObject::invokeMethod(this, "StartRecording",
  1174. Qt::QueuedConnection);
  1175. opt_start_recording = false;
  1176. }
  1177. if (opt_start_replaybuffer && !safe_mode) {
  1178. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  1179. Qt::QueuedConnection);
  1180. opt_start_replaybuffer = false;
  1181. }
  1182. if (opt_start_virtualcam && !safe_mode) {
  1183. QMetaObject::invokeMethod(this, "StartVirtualCam",
  1184. Qt::QueuedConnection);
  1185. opt_start_virtualcam = false;
  1186. }
  1187. LogScenes();
  1188. if (!App()->IsMissingFilesCheckDisabled())
  1189. ShowMissingFilesDialog(files);
  1190. disableSaving--;
  1191. if (vcamEnabled)
  1192. outputHandler->UpdateVirtualCamOutputSource();
  1193. OnEvent(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1194. OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1195. }
  1196. #define SERVICE_PATH "service.json"
  1197. void OBSBasic::SaveService()
  1198. {
  1199. if (!service)
  1200. return;
  1201. char serviceJsonPath[512];
  1202. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1203. SERVICE_PATH);
  1204. if (ret <= 0)
  1205. return;
  1206. OBSDataAutoRelease data = obs_data_create();
  1207. OBSDataAutoRelease settings = obs_service_get_settings(service);
  1208. obs_data_set_string(data, "type", obs_service_get_type(service));
  1209. obs_data_set_obj(data, "settings", settings);
  1210. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  1211. blog(LOG_WARNING, "Failed to save service");
  1212. }
  1213. bool OBSBasic::LoadService()
  1214. {
  1215. const char *type;
  1216. char serviceJsonPath[512];
  1217. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1218. SERVICE_PATH);
  1219. if (ret <= 0)
  1220. return false;
  1221. OBSDataAutoRelease data =
  1222. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  1223. if (!data)
  1224. return false;
  1225. obs_data_set_default_string(data, "type", "rtmp_common");
  1226. type = obs_data_get_string(data, "type");
  1227. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  1228. OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys");
  1229. service = obs_service_create(type, "default_service", settings,
  1230. hotkey_data);
  1231. obs_service_release(service);
  1232. if (!service)
  1233. return false;
  1234. /* Enforce Opus on WHIP if needed */
  1235. if (strcmp(obs_service_get_protocol(service), "WHIP") == 0) {
  1236. const char *option = config_get_string(
  1237. basicConfig, "SimpleOutput", "StreamAudioEncoder");
  1238. if (strcmp(option, "opus") != 0)
  1239. config_set_string(basicConfig, "SimpleOutput",
  1240. "StreamAudioEncoder", "opus");
  1241. option = config_get_string(basicConfig, "AdvOut",
  1242. "AudioEncoder");
  1243. const char *encoder_codec = obs_get_encoder_codec(option);
  1244. if (!encoder_codec || strcmp(encoder_codec, "opus") != 0)
  1245. config_set_string(basicConfig, "AdvOut", "AudioEncoder",
  1246. "ffmpeg_opus");
  1247. }
  1248. return true;
  1249. }
  1250. bool OBSBasic::InitService()
  1251. {
  1252. ProfileScope("OBSBasic::InitService");
  1253. if (LoadService())
  1254. return true;
  1255. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1256. nullptr);
  1257. if (!service)
  1258. return false;
  1259. obs_service_release(service);
  1260. return true;
  1261. }
  1262. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1263. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1264. 2.5, 2.75, 3.0, 0.0};
  1265. extern void CheckExistingCookieId();
  1266. #ifdef __APPLE__
  1267. #define DEFAULT_CONTAINER "fragmented_mov"
  1268. #elif OBS_RELEASE_CANDIDATE == 0 && OBS_BETA == 0
  1269. #define DEFAULT_CONTAINER "mkv"
  1270. #else
  1271. #define DEFAULT_CONTAINER "hybrid_mp4"
  1272. #endif
  1273. bool OBSBasic::InitBasicConfigDefaults()
  1274. {
  1275. QList<QScreen *> screens = QGuiApplication::screens();
  1276. if (!screens.size()) {
  1277. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1278. "technically shouldn't be possible.");
  1279. return false;
  1280. }
  1281. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1282. uint32_t cx = primaryScreen->size().width();
  1283. uint32_t cy = primaryScreen->size().height();
  1284. cx *= devicePixelRatioF();
  1285. cy *= devicePixelRatioF();
  1286. bool oldResolutionDefaults = config_get_bool(
  1287. App()->GlobalConfig(), "General", "Pre19Defaults");
  1288. /* use 1920x1080 for new default base res if main monitor is above
  1289. * 1920x1080, but don't apply for people from older builds -- only to
  1290. * new users */
  1291. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1292. cx = 1920;
  1293. cy = 1080;
  1294. }
  1295. bool changed = false;
  1296. /* ----------------------------------------------------- */
  1297. /* move over old FFmpeg track settings */
  1298. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1299. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1300. int track = (int)config_get_int(basicConfig, "AdvOut",
  1301. "FFAudioTrack");
  1302. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1303. 1LL << (track - 1));
  1304. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1305. changed = true;
  1306. }
  1307. /* ----------------------------------------------------- */
  1308. /* move over mixer values in advanced if older config */
  1309. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1310. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1311. uint64_t track =
  1312. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1313. track = 1ULL << (track - 1);
  1314. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1315. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1316. changed = true;
  1317. }
  1318. /* ----------------------------------------------------- */
  1319. /* set twitch chat extensions to "both" if prev version */
  1320. /* is under 24.1 */
  1321. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1322. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1323. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1324. changed = true;
  1325. }
  1326. /* ----------------------------------------------------- */
  1327. /* move bitrate enforcement setting to new value */
  1328. if (config_has_user_value(basicConfig, "SimpleOutput",
  1329. "EnforceBitrate") &&
  1330. !config_has_user_value(basicConfig, "Stream1",
  1331. "IgnoreRecommended") &&
  1332. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1333. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1334. "EnforceBitrate");
  1335. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1336. !enforce);
  1337. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1338. true);
  1339. changed = true;
  1340. }
  1341. /* ----------------------------------------------------- */
  1342. /* enforce minimum retry delay of 1 second prior to 27.1 */
  1343. if (config_has_user_value(basicConfig, "Output", "RetryDelay")) {
  1344. int retryDelay =
  1345. config_get_uint(basicConfig, "Output", "RetryDelay");
  1346. if (retryDelay < 1) {
  1347. config_set_uint(basicConfig, "Output", "RetryDelay", 1);
  1348. changed = true;
  1349. }
  1350. }
  1351. /* ----------------------------------------------------- */
  1352. /* Migrate old container selection (if any) to new key. */
  1353. auto MigrateFormat = [&](const char *section) {
  1354. bool has_old_key = config_has_user_value(basicConfig, section,
  1355. "RecFormat");
  1356. bool has_new_key = config_has_user_value(basicConfig, section,
  1357. "RecFormat2");
  1358. if (!has_new_key && !has_old_key)
  1359. return;
  1360. string old_format = config_get_string(
  1361. basicConfig, section,
  1362. has_new_key ? "RecFormat2" : "RecFormat");
  1363. string new_format = old_format;
  1364. if (old_format == "ts")
  1365. new_format = "mpegts";
  1366. else if (old_format == "m3u8")
  1367. new_format = "hls";
  1368. else if (old_format == "fmp4")
  1369. new_format = "fragmented_mp4";
  1370. else if (old_format == "fmov")
  1371. new_format = "fragmented_mov";
  1372. if (new_format != old_format || !has_new_key) {
  1373. config_set_string(basicConfig, section, "RecFormat2",
  1374. new_format.c_str());
  1375. changed = true;
  1376. }
  1377. };
  1378. MigrateFormat("AdvOut");
  1379. MigrateFormat("SimpleOutput");
  1380. /* ----------------------------------------------------- */
  1381. /* Migrate output scale setting to GPU scaling options. */
  1382. if (config_get_bool(basicConfig, "AdvOut", "Rescale") &&
  1383. !config_has_user_value(basicConfig, "AdvOut", "RescaleFilter")) {
  1384. config_set_int(basicConfig, "AdvOut", "RescaleFilter",
  1385. OBS_SCALE_BILINEAR);
  1386. }
  1387. if (config_get_bool(basicConfig, "AdvOut", "RecRescale") &&
  1388. !config_has_user_value(basicConfig, "AdvOut", "RecRescaleFilter")) {
  1389. config_set_int(basicConfig, "AdvOut", "RecRescaleFilter",
  1390. OBS_SCALE_BILINEAR);
  1391. }
  1392. /* ----------------------------------------------------- */
  1393. if (changed)
  1394. config_save_safe(basicConfig, "tmp", nullptr);
  1395. /* ----------------------------------------------------- */
  1396. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1397. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1398. false);
  1399. config_set_default_bool(basicConfig, "Stream1", "EnableMultitrackVideo",
  1400. false);
  1401. config_set_default_bool(basicConfig, "Stream1",
  1402. "MultitrackVideoMaximumAggregateBitrateAuto",
  1403. true);
  1404. config_set_default_bool(basicConfig, "Stream1",
  1405. "MultitrackVideoMaximumVideoTracksAuto", true);
  1406. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1407. GetDefaultVideoSavePath().c_str());
  1408. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat2",
  1409. DEFAULT_CONTAINER);
  1410. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1411. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1412. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1413. false);
  1414. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1415. "veryfast");
  1416. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset2",
  1417. "p5");
  1418. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1419. "Stream");
  1420. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1421. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1422. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1423. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1424. "Replay");
  1425. config_set_default_string(basicConfig, "SimpleOutput",
  1426. "StreamAudioEncoder", "aac");
  1427. config_set_default_string(basicConfig, "SimpleOutput",
  1428. "RecAudioEncoder", "aac");
  1429. config_set_default_uint(basicConfig, "SimpleOutput", "RecTracks",
  1430. (1 << 0));
  1431. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1432. true);
  1433. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1434. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1435. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1436. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1437. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1438. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1439. GetDefaultVideoSavePath().c_str());
  1440. config_set_default_string(basicConfig, "AdvOut", "RecFormat2",
  1441. DEFAULT_CONTAINER);
  1442. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1443. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1444. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1445. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1446. config_set_default_uint(basicConfig, "AdvOut",
  1447. "StreamMultiTrackAudioMixes", 1);
  1448. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1449. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1450. GetDefaultVideoSavePath().c_str());
  1451. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1452. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1453. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1454. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1455. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1456. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1457. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1458. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1459. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1460. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1461. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1462. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1463. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1464. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileTime", 15);
  1465. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileSize",
  1466. 2048);
  1467. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1468. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1469. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1470. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1471. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1472. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1473. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1474. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1475. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1476. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1477. config_save_safe(basicConfig, "tmp", nullptr);
  1478. }
  1479. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1480. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1481. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1482. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1483. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1484. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1485. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1486. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1487. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1488. config_set_default_string(basicConfig, "Output", "IPFamily",
  1489. "IPv4+IPv6");
  1490. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1491. false);
  1492. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1493. false);
  1494. int i = 0;
  1495. uint32_t scale_cx = cx;
  1496. uint32_t scale_cy = cy;
  1497. /* use a default scaled resolution that has a pixel count no higher
  1498. * than 1280x720 */
  1499. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1500. double scale = scaled_vals[i++];
  1501. scale_cx = uint32_t(double(cx) / scale);
  1502. scale_cy = uint32_t(double(cy) / scale);
  1503. }
  1504. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1505. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1506. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1507. * changing */
  1508. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1509. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1510. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1511. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1512. config_save_safe(basicConfig, "tmp", nullptr);
  1513. }
  1514. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1515. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1516. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1517. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1518. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1519. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1520. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1521. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1522. config_set_default_string(basicConfig, "Video", "ColorRange",
  1523. "Partial");
  1524. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1525. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1526. 1000);
  1527. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1528. "default");
  1529. config_set_default_string(
  1530. basicConfig, "Audio", "MonitoringDeviceName",
  1531. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1532. ".Default"));
  1533. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1534. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1535. "Stereo");
  1536. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1537. VOLUME_METER_DECAY_FAST);
  1538. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1539. CheckExistingCookieId();
  1540. return true;
  1541. }
  1542. extern bool EncoderAvailable(const char *encoder);
  1543. void OBSBasic::InitBasicConfigDefaults2()
  1544. {
  1545. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1546. "Pre23Defaults");
  1547. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1548. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1549. useNV ? SIMPLE_ENCODER_NVENC
  1550. : SIMPLE_ENCODER_X264);
  1551. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1552. useNV ? SIMPLE_ENCODER_NVENC
  1553. : SIMPLE_ENCODER_X264);
  1554. const char *aac_default = "ffmpeg_aac";
  1555. if (EncoderAvailable("CoreAudio_AAC"))
  1556. aac_default = "CoreAudio_AAC";
  1557. else if (EncoderAvailable("libfdk_aac"))
  1558. aac_default = "libfdk_aac";
  1559. config_set_default_string(basicConfig, "AdvOut", "AudioEncoder",
  1560. aac_default);
  1561. config_set_default_string(basicConfig, "AdvOut", "RecAudioEncoder",
  1562. aac_default);
  1563. }
  1564. bool OBSBasic::InitBasicConfig()
  1565. {
  1566. ProfileScope("OBSBasic::InitBasicConfig");
  1567. char configPath[512];
  1568. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1569. if (ret <= 0) {
  1570. OBSErrorBox(nullptr, "Failed to get profile path");
  1571. return false;
  1572. }
  1573. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1574. OBSErrorBox(nullptr, "Failed to create profile path");
  1575. return false;
  1576. }
  1577. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1578. if (ret <= 0) {
  1579. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1580. return false;
  1581. }
  1582. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1583. if (code != CONFIG_SUCCESS) {
  1584. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1585. return false;
  1586. }
  1587. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1588. const char *curName = config_get_string(App()->GlobalConfig(),
  1589. "Basic", "Profile");
  1590. config_set_string(basicConfig, "General", "Name", curName);
  1591. basicConfig.SaveSafe("tmp");
  1592. }
  1593. return InitBasicConfigDefaults();
  1594. }
  1595. void OBSBasic::InitOBSCallbacks()
  1596. {
  1597. ProfileScope("OBSBasic::InitOBSCallbacks");
  1598. signalHandlers.reserve(signalHandlers.size() + 7);
  1599. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1600. OBSBasic::SourceCreated, this);
  1601. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1602. OBSBasic::SourceRemoved, this);
  1603. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1604. OBSBasic::SourceActivated, this);
  1605. signalHandlers.emplace_back(obs_get_signal_handler(),
  1606. "source_deactivate",
  1607. OBSBasic::SourceDeactivated, this);
  1608. signalHandlers.emplace_back(obs_get_signal_handler(),
  1609. "source_audio_activate",
  1610. OBSBasic::SourceAudioActivated, this);
  1611. signalHandlers.emplace_back(obs_get_signal_handler(),
  1612. "source_audio_deactivate",
  1613. OBSBasic::SourceAudioDeactivated, this);
  1614. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1615. OBSBasic::SourceRenamed, this);
  1616. signalHandlers.emplace_back(
  1617. obs_get_signal_handler(), "source_filter_add",
  1618. [](void *data, calldata_t *) {
  1619. static_cast<OBSBasic *>(data)->UpdateEditMenu();
  1620. },
  1621. this);
  1622. signalHandlers.emplace_back(
  1623. obs_get_signal_handler(), "source_filter_remove",
  1624. [](void *data, calldata_t *) {
  1625. static_cast<OBSBasic *>(data)->UpdateEditMenu();
  1626. },
  1627. this);
  1628. }
  1629. void OBSBasic::InitPrimitives()
  1630. {
  1631. ProfileScope("OBSBasic::InitPrimitives");
  1632. obs_enter_graphics();
  1633. gs_render_start(true);
  1634. gs_vertex2f(0.0f, 0.0f);
  1635. gs_vertex2f(0.0f, 1.0f);
  1636. gs_vertex2f(1.0f, 0.0f);
  1637. gs_vertex2f(1.0f, 1.0f);
  1638. box = gs_render_save();
  1639. gs_render_start(true);
  1640. gs_vertex2f(0.0f, 0.0f);
  1641. gs_vertex2f(0.0f, 1.0f);
  1642. boxLeft = gs_render_save();
  1643. gs_render_start(true);
  1644. gs_vertex2f(0.0f, 0.0f);
  1645. gs_vertex2f(1.0f, 0.0f);
  1646. boxTop = gs_render_save();
  1647. gs_render_start(true);
  1648. gs_vertex2f(1.0f, 0.0f);
  1649. gs_vertex2f(1.0f, 1.0f);
  1650. boxRight = gs_render_save();
  1651. gs_render_start(true);
  1652. gs_vertex2f(0.0f, 1.0f);
  1653. gs_vertex2f(1.0f, 1.0f);
  1654. boxBottom = gs_render_save();
  1655. gs_render_start(true);
  1656. for (int i = 0; i <= 360; i += (360 / 20)) {
  1657. float pos = RAD(float(i));
  1658. gs_vertex2f(cosf(pos), sinf(pos));
  1659. }
  1660. circle = gs_render_save();
  1661. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1662. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1663. obs_leave_graphics();
  1664. }
  1665. void OBSBasic::ReplayBufferActionTriggered()
  1666. {
  1667. if (outputHandler->ReplayBufferActive())
  1668. StopReplayBuffer();
  1669. else
  1670. StartReplayBuffer();
  1671. };
  1672. void OBSBasic::ResetOutputs()
  1673. {
  1674. ProfileScope("OBSBasic::ResetOutputs");
  1675. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1676. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1677. if ((!outputHandler || !outputHandler->Active()) &&
  1678. (!setupStreamingGuard.valid() ||
  1679. setupStreamingGuard.wait_for(std::chrono::seconds{0}) ==
  1680. std::future_status::ready)) {
  1681. outputHandler.reset();
  1682. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1683. : CreateSimpleOutputHandler(this));
  1684. emit ReplayBufEnabled(outputHandler->replayBuffer);
  1685. if (sysTrayReplayBuffer)
  1686. sysTrayReplayBuffer->setEnabled(
  1687. !!outputHandler->replayBuffer);
  1688. UpdateIsRecordingPausable();
  1689. } else {
  1690. outputHandler->Update();
  1691. }
  1692. }
  1693. #define STARTUP_SEPARATOR \
  1694. "==== Startup complete ==============================================="
  1695. #define SHUTDOWN_SEPARATOR \
  1696. "==== Shutting down =================================================="
  1697. #define UNSUPPORTED_ERROR \
  1698. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1699. "not found. Your GPU may not be supported."
  1700. #define UNKNOWN_ERROR \
  1701. "Failed to initialize video. Your GPU may not be supported, " \
  1702. "or your graphics drivers may need to be updated."
  1703. static inline void LogEncoders()
  1704. {
  1705. constexpr uint32_t hide_flags = OBS_ENCODER_CAP_DEPRECATED |
  1706. OBS_ENCODER_CAP_INTERNAL;
  1707. auto list_encoders = [](obs_encoder_type type) {
  1708. size_t idx = 0;
  1709. const char *encoder_type;
  1710. while (obs_enum_encoder_types(idx++, &encoder_type)) {
  1711. if (obs_get_encoder_caps(encoder_type) & hide_flags ||
  1712. obs_get_encoder_type(encoder_type) != type) {
  1713. continue;
  1714. }
  1715. blog(LOG_INFO, "\t- %s (%s)", encoder_type,
  1716. obs_encoder_get_display_name(encoder_type));
  1717. }
  1718. };
  1719. blog(LOG_INFO, "---------------------------------");
  1720. blog(LOG_INFO, "Available Encoders:");
  1721. blog(LOG_INFO, " Video Encoders:");
  1722. list_encoders(OBS_ENCODER_VIDEO);
  1723. blog(LOG_INFO, " Audio Encoders:");
  1724. list_encoders(OBS_ENCODER_AUDIO);
  1725. }
  1726. void OBSBasic::OBSInit()
  1727. {
  1728. ProfileScope("OBSBasic::OBSInit");
  1729. const char *sceneCollection = config_get_string(
  1730. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1731. char savePath[1024];
  1732. char fileName[1024];
  1733. int ret;
  1734. if (!sceneCollection)
  1735. throw "Failed to get scene collection name";
  1736. ret = snprintf(fileName, sizeof(fileName),
  1737. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1738. if (ret <= 0)
  1739. throw "Failed to create scene collection file name";
  1740. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1741. if (ret <= 0)
  1742. throw "Failed to get scene collection json file path";
  1743. if (!InitBasicConfig())
  1744. throw "Failed to load basic.ini";
  1745. if (!ResetAudio())
  1746. throw "Failed to initialize audio";
  1747. ret = ResetVideo();
  1748. switch (ret) {
  1749. case OBS_VIDEO_MODULE_NOT_FOUND:
  1750. throw "Failed to initialize video: Graphics module not found";
  1751. case OBS_VIDEO_NOT_SUPPORTED:
  1752. throw UNSUPPORTED_ERROR;
  1753. case OBS_VIDEO_INVALID_PARAM:
  1754. throw "Failed to initialize video: Invalid parameters";
  1755. default:
  1756. if (ret != OBS_VIDEO_SUCCESS)
  1757. throw UNKNOWN_ERROR;
  1758. }
  1759. /* load audio monitoring */
  1760. if (obs_audio_monitoring_available()) {
  1761. const char *device_name = config_get_string(
  1762. basicConfig, "Audio", "MonitoringDeviceName");
  1763. const char *device_id = config_get_string(basicConfig, "Audio",
  1764. "MonitoringDeviceId");
  1765. obs_set_audio_monitoring_device(device_name, device_id);
  1766. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1767. device_name, device_id);
  1768. }
  1769. InitOBSCallbacks();
  1770. InitHotkeys();
  1771. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1772. * to ship with */
  1773. #if defined(_WIN32) && !defined(_DEBUG)
  1774. LoadLibraryW(L"Qt6Network");
  1775. #endif
  1776. struct obs_module_failure_info mfi;
  1777. /* Safe Mode disables third-party plugins so we don't need to add earch
  1778. * paths outside the OBS bundle/installation. */
  1779. if (safe_mode || disable_3p_plugins) {
  1780. SetSafeModuleNames();
  1781. } else {
  1782. AddExtraModulePaths();
  1783. }
  1784. blog(LOG_INFO, "---------------------------------");
  1785. obs_load_all_modules2(&mfi);
  1786. blog(LOG_INFO, "---------------------------------");
  1787. obs_log_loaded_modules();
  1788. blog(LOG_INFO, "---------------------------------");
  1789. obs_post_load_modules();
  1790. BPtr<char *> failed_modules = mfi.failed_modules;
  1791. #ifdef BROWSER_AVAILABLE
  1792. cef = obs_browser_init_panel();
  1793. cef_js_avail = cef && obs_browser_qcef_version() >= 3;
  1794. #endif
  1795. vcamEnabled =
  1796. (obs_get_output_flags(VIRTUAL_CAM_ID) & OBS_OUTPUT_VIDEO) != 0;
  1797. if (vcamEnabled) {
  1798. emit VirtualCamEnabled();
  1799. }
  1800. InitBasicConfigDefaults2();
  1801. CheckForSimpleModeX264Fallback();
  1802. LogEncoders();
  1803. blog(LOG_INFO, STARTUP_SEPARATOR);
  1804. if (!InitService())
  1805. throw "Failed to initialize service";
  1806. ResetOutputs();
  1807. CreateHotkeys();
  1808. InitPrimitives();
  1809. sceneDuplicationMode = config_get_bool(
  1810. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1811. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1812. "SwapScenesMode");
  1813. editPropertiesMode = config_get_bool(
  1814. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1815. if (!opt_studio_mode) {
  1816. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1817. "BasicWindow",
  1818. "PreviewProgramMode"));
  1819. } else {
  1820. SetPreviewProgramMode(true);
  1821. opt_studio_mode = false;
  1822. }
  1823. #define SET_VISIBILITY(name, control) \
  1824. do { \
  1825. if (config_has_user_value(App()->GlobalConfig(), \
  1826. "BasicWindow", name)) { \
  1827. bool visible = config_get_bool(App()->GlobalConfig(), \
  1828. "BasicWindow", name); \
  1829. ui->control->setChecked(visible); \
  1830. } \
  1831. } while (false)
  1832. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1833. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1834. #undef SET_VISIBILITY
  1835. bool sourceIconsVisible = config_get_bool(
  1836. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1837. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1838. bool contextVisible = config_get_bool(
  1839. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1840. ui->toggleContextBar->setChecked(contextVisible);
  1841. ui->contextContainer->setVisible(contextVisible);
  1842. if (contextVisible)
  1843. UpdateContextBar(true);
  1844. UpdateEditMenu();
  1845. {
  1846. ProfileScope("OBSBasic::Load");
  1847. disableSaving--;
  1848. Load(savePath);
  1849. disableSaving++;
  1850. }
  1851. loaded = true;
  1852. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1853. "PreviewEnabled");
  1854. if (!previewEnabled && !IsPreviewProgramMode())
  1855. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1856. Qt::QueuedConnection,
  1857. Q_ARG(bool, previewEnabled));
  1858. else if (!previewEnabled && IsPreviewProgramMode())
  1859. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1860. Qt::QueuedConnection,
  1861. Q_ARG(bool, true));
  1862. RefreshSceneCollections();
  1863. RefreshProfiles();
  1864. disableSaving--;
  1865. auto addDisplay = [this](OBSQTDisplay *window) {
  1866. obs_display_add_draw_callback(window->GetDisplay(),
  1867. OBSBasic::RenderMain, this);
  1868. struct obs_video_info ovi;
  1869. if (obs_get_video_info(&ovi))
  1870. ResizePreview(ovi.base_width, ovi.base_height);
  1871. };
  1872. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1873. /* Show the main window, unless the tray icon isn't available
  1874. * or neither the setting nor flag for starting minimized is set. */
  1875. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1876. "BasicWindow", "SysTrayEnabled");
  1877. bool sysTrayWhenStarted = config_get_bool(
  1878. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1879. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1880. sysTrayEnabled &&
  1881. (opt_minimize_tray || sysTrayWhenStarted);
  1882. #ifdef _WIN32
  1883. SetWin32DropStyle(this);
  1884. if (!hideWindowOnStart)
  1885. show();
  1886. #endif
  1887. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1888. "AlwaysOnTop");
  1889. #ifdef ENABLE_WAYLAND
  1890. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1891. #else
  1892. bool isWayland = false;
  1893. #endif
  1894. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1895. SetAlwaysOnTop(this, true);
  1896. ui->actionAlwaysOnTop->setChecked(true);
  1897. } else if (isWayland) {
  1898. if (opt_always_on_top)
  1899. blog(LOG_INFO,
  1900. "Always On Top not available on Wayland, ignoring.");
  1901. ui->actionAlwaysOnTop->setEnabled(false);
  1902. ui->actionAlwaysOnTop->setVisible(false);
  1903. }
  1904. #ifndef _WIN32
  1905. if (!hideWindowOnStart)
  1906. show();
  1907. #endif
  1908. /* setup stats dock */
  1909. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1910. statsDock->setWidget(statsDlg);
  1911. /* ----------------------------- */
  1912. /* add custom browser docks */
  1913. #if defined(BROWSER_AVAILABLE) && defined(YOUTUBE_ENABLED)
  1914. YouTubeAppDock::CleanupYouTubeUrls();
  1915. #endif
  1916. #ifdef BROWSER_AVAILABLE
  1917. if (cef) {
  1918. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1919. "CustomBrowserDocks"),
  1920. this);
  1921. ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(),
  1922. action);
  1923. connect(action, &QAction::triggered, this,
  1924. &OBSBasic::ManageExtraBrowserDocks);
  1925. ui->menuDocks->insertSeparator(
  1926. ui->scenesDock->toggleViewAction());
  1927. LoadExtraBrowserDocks();
  1928. }
  1929. #endif
  1930. #ifdef YOUTUBE_ENABLED
  1931. /* setup YouTube app dock */
  1932. if (YouTubeAppDock::IsYTServiceSelected())
  1933. NewYouTubeAppDock();
  1934. #endif
  1935. const char *dockStateStr = config_get_string(
  1936. App()->GlobalConfig(), "BasicWindow", "DockState");
  1937. if (!dockStateStr) {
  1938. on_resetDocks_triggered(true);
  1939. } else {
  1940. QByteArray dockState =
  1941. QByteArray::fromBase64(QByteArray(dockStateStr));
  1942. if (!restoreState(dockState))
  1943. on_resetDocks_triggered(true);
  1944. }
  1945. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1946. "Pre23Defaults");
  1947. if (pre23Defaults) {
  1948. bool resetDockLock23 = config_get_bool(
  1949. App()->GlobalConfig(), "General", "ResetDockLock23");
  1950. if (!resetDockLock23) {
  1951. config_set_bool(App()->GlobalConfig(), "General",
  1952. "ResetDockLock23", true);
  1953. config_remove_value(App()->GlobalConfig(),
  1954. "BasicWindow", "DocksLocked");
  1955. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1956. }
  1957. }
  1958. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1959. "DocksLocked");
  1960. on_lockDocks_toggled(docksLocked);
  1961. ui->lockDocks->blockSignals(true);
  1962. ui->lockDocks->setChecked(docksLocked);
  1963. ui->lockDocks->blockSignals(false);
  1964. bool sideDocks = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1965. "SideDocks");
  1966. on_sideDocks_toggled(sideDocks);
  1967. ui->sideDocks->blockSignals(true);
  1968. ui->sideDocks->setChecked(sideDocks);
  1969. ui->sideDocks->blockSignals(false);
  1970. SystemTray(true);
  1971. TaskbarOverlayInit();
  1972. #ifdef __APPLE__
  1973. disableColorSpaceConversion(this);
  1974. #endif
  1975. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1976. "General", "LastVersion");
  1977. bool first_run =
  1978. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1979. if (!first_run) {
  1980. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1981. true);
  1982. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1983. }
  1984. if (!first_run && !has_last_version && !Active())
  1985. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1986. Qt::QueuedConnection);
  1987. #if (defined(_WIN32) || defined(__APPLE__)) && \
  1988. (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0)
  1989. /* Automatically set branch to "beta" the first time a pre-release build is run. */
  1990. if (!config_get_bool(App()->GlobalConfig(), "General",
  1991. "AutoBetaOptIn")) {
  1992. config_set_string(App()->GlobalConfig(), "General",
  1993. "UpdateBranch", "beta");
  1994. config_set_bool(App()->GlobalConfig(), "General",
  1995. "AutoBetaOptIn", true);
  1996. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1997. }
  1998. #endif
  1999. TimedCheckForUpdates();
  2000. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  2001. "VerticalVolControl"));
  2002. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  2003. on_stats_triggered();
  2004. OBSBasicStats::InitializeValues();
  2005. /* ----------------------- */
  2006. /* Add multiview menu */
  2007. ui->viewMenu->addSeparator();
  2008. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  2009. &OBSBasic::OpenMultiviewProjector);
  2010. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  2011. &OBSBasic::UpdateMultiviewProjectorMenu);
  2012. ui->sources->UpdateIcons();
  2013. #if !defined(_WIN32)
  2014. delete ui->actionShowCrashLogs;
  2015. delete ui->actionUploadLastCrashLog;
  2016. delete ui->menuCrashLogs;
  2017. delete ui->actionRepair;
  2018. ui->actionShowCrashLogs = nullptr;
  2019. ui->actionUploadLastCrashLog = nullptr;
  2020. ui->menuCrashLogs = nullptr;
  2021. ui->actionRepair = nullptr;
  2022. #if !defined(__APPLE__)
  2023. delete ui->actionCheckForUpdates;
  2024. ui->actionCheckForUpdates = nullptr;
  2025. #endif
  2026. #endif
  2027. #ifdef __APPLE__
  2028. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  2029. delete ui->actionFullscreenInterface;
  2030. ui->actionFullscreenInterface = nullptr;
  2031. #else
  2032. /* Don't show menu to raise macOS-only permissions dialog */
  2033. delete ui->actionShowMacPermissions;
  2034. ui->actionShowMacPermissions = nullptr;
  2035. #endif
  2036. #if defined(_WIN32) || defined(__APPLE__)
  2037. if (App()->IsUpdaterDisabled()) {
  2038. ui->actionCheckForUpdates->setEnabled(false);
  2039. #if defined(_WIN32)
  2040. ui->actionRepair->setEnabled(false);
  2041. #endif
  2042. }
  2043. #endif
  2044. #ifndef WHATSNEW_ENABLED
  2045. delete ui->actionShowWhatsNew;
  2046. ui->actionShowWhatsNew = nullptr;
  2047. #endif
  2048. if (safe_mode) {
  2049. ui->actionRestartSafe->setText(
  2050. QTStr("Basic.MainMenu.Help.RestartNormal"));
  2051. }
  2052. UpdatePreviewProgramIndicators();
  2053. OnFirstLoad();
  2054. if (!hideWindowOnStart)
  2055. activateWindow();
  2056. /* ------------------------------------------- */
  2057. /* display warning message for failed modules */
  2058. if (mfi.count) {
  2059. QString failed_plugins;
  2060. char **plugin = mfi.failed_modules;
  2061. while (*plugin) {
  2062. failed_plugins += *plugin;
  2063. failed_plugins += "\n";
  2064. plugin++;
  2065. }
  2066. QString failed_msg =
  2067. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  2068. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  2069. failed_msg);
  2070. }
  2071. }
  2072. void OBSBasic::OnFirstLoad()
  2073. {
  2074. OnEvent(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  2075. #ifdef WHATSNEW_ENABLED
  2076. /* Attempt to load init screen if available */
  2077. if (cef) {
  2078. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  2079. connect(wnit, &WhatsNewInfoThread::Result, this,
  2080. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  2081. introCheckThread.reset(wnit);
  2082. introCheckThread->start();
  2083. }
  2084. #endif
  2085. Auth::Load();
  2086. bool showLogViewerOnStartup = config_get_bool(
  2087. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  2088. if (showLogViewerOnStartup)
  2089. on_actionViewCurrentLog_triggered();
  2090. }
  2091. /* shows a "what's new" page on startup of new versions using CEF */
  2092. void OBSBasic::ReceivedIntroJson(const QString &text)
  2093. {
  2094. #ifdef WHATSNEW_ENABLED
  2095. if (closing)
  2096. return;
  2097. WhatsNewList items;
  2098. try {
  2099. nlohmann::json json = nlohmann::json::parse(text.toStdString());
  2100. items = json.get<WhatsNewList>();
  2101. } catch (nlohmann::json::exception &e) {
  2102. blog(LOG_WARNING, "Parsing whatsnew data failed: %s", e.what());
  2103. return;
  2104. }
  2105. std::string info_url;
  2106. int info_increment = -1;
  2107. /* check to see if there's an info page for this version */
  2108. for (const WhatsNewItem &item : items) {
  2109. if (item.os) {
  2110. WhatsNewPlatforms platforms = *item.os;
  2111. #ifdef _WIN32
  2112. if (!platforms.windows)
  2113. continue;
  2114. #elif defined(__APPLE__)
  2115. if (!platforms.macos)
  2116. continue;
  2117. #else
  2118. if (!platforms.linux)
  2119. continue;
  2120. #endif
  2121. }
  2122. int major = 0;
  2123. int minor = 0;
  2124. sscanf(item.version.c_str(), "%d.%d", &major, &minor);
  2125. if (major == LIBOBS_API_MAJOR_VER &&
  2126. minor == LIBOBS_API_MINOR_VER &&
  2127. item.RC == OBS_RELEASE_CANDIDATE && item.Beta == OBS_BETA) {
  2128. info_url = item.url;
  2129. info_increment = item.increment;
  2130. }
  2131. }
  2132. /* this version was not found, or no info for this version */
  2133. if (info_increment == -1) {
  2134. return;
  2135. }
  2136. #if OBS_RELEASE_CANDIDATE > 0
  2137. constexpr const char *lastInfoVersion = "InfoLastRCVersion";
  2138. #elif OBS_BETA > 0
  2139. constexpr const char *lastInfoVersion = "InfoLastBetaVersion";
  2140. #else
  2141. constexpr const char *lastInfoVersion = "InfoLastVersion";
  2142. #endif
  2143. constexpr uint64_t currentVersion = (uint64_t)LIBOBS_API_VER << 16ULL |
  2144. OBS_RELEASE_CANDIDATE << 8ULL |
  2145. OBS_BETA;
  2146. uint64_t lastVersion = config_get_uint(App()->GlobalConfig(), "General",
  2147. lastInfoVersion);
  2148. int current_version_increment = -1;
  2149. if ((lastVersion & ~0xFFFF0000ULL) <
  2150. (currentVersion & ~0xFFFF0000ULL)) {
  2151. config_set_int(App()->GlobalConfig(), "General",
  2152. "InfoIncrement", -1);
  2153. config_set_uint(App()->GlobalConfig(), "General",
  2154. lastInfoVersion, currentVersion);
  2155. } else {
  2156. current_version_increment = config_get_int(
  2157. App()->GlobalConfig(), "General", "InfoIncrement");
  2158. }
  2159. if (info_increment <= current_version_increment) {
  2160. return;
  2161. }
  2162. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  2163. info_increment);
  2164. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2165. cef->init_browser();
  2166. WhatsNewBrowserInitThread *wnbit =
  2167. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  2168. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  2169. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  2170. whatsNewInitThread.reset(wnbit);
  2171. whatsNewInitThread->start();
  2172. #else
  2173. UNUSED_PARAMETER(text);
  2174. #endif
  2175. }
  2176. void OBSBasic::ShowWhatsNew(const QString &url)
  2177. {
  2178. #ifdef BROWSER_AVAILABLE
  2179. if (closing)
  2180. return;
  2181. std::string info_url = QT_TO_UTF8(url);
  2182. QDialog *dlg = new QDialog(this);
  2183. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  2184. dlg->setWindowTitle("What's New");
  2185. dlg->resize(700, 600);
  2186. Qt::WindowFlags flags = dlg->windowFlags();
  2187. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  2188. dlg->setWindowFlags(flags & (~helpFlag));
  2189. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  2190. if (!cefWidget) {
  2191. return;
  2192. }
  2193. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  2194. SLOT(setWindowTitle(const QString &)));
  2195. QPushButton *close = new QPushButton(QTStr("Close"));
  2196. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  2197. QHBoxLayout *bottomLayout = new QHBoxLayout();
  2198. bottomLayout->addStretch();
  2199. bottomLayout->addWidget(close);
  2200. bottomLayout->addStretch();
  2201. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  2202. topLayout->addWidget(cefWidget);
  2203. topLayout->addLayout(bottomLayout);
  2204. dlg->show();
  2205. #else
  2206. UNUSED_PARAMETER(url);
  2207. #endif
  2208. }
  2209. void OBSBasic::UpdateMultiviewProjectorMenu()
  2210. {
  2211. ui->multiviewProjectorMenu->clear();
  2212. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  2213. &OBSBasic::OpenMultiviewProjector);
  2214. }
  2215. void OBSBasic::InitHotkeys()
  2216. {
  2217. ProfileScope("OBSBasic::InitHotkeys");
  2218. struct obs_hotkeys_translations t = {};
  2219. t.insert = Str("Hotkeys.Insert");
  2220. t.del = Str("Hotkeys.Delete");
  2221. t.home = Str("Hotkeys.Home");
  2222. t.end = Str("Hotkeys.End");
  2223. t.page_up = Str("Hotkeys.PageUp");
  2224. t.page_down = Str("Hotkeys.PageDown");
  2225. t.num_lock = Str("Hotkeys.NumLock");
  2226. t.scroll_lock = Str("Hotkeys.ScrollLock");
  2227. t.caps_lock = Str("Hotkeys.CapsLock");
  2228. t.backspace = Str("Hotkeys.Backspace");
  2229. t.tab = Str("Hotkeys.Tab");
  2230. t.print = Str("Hotkeys.Print");
  2231. t.pause = Str("Hotkeys.Pause");
  2232. t.left = Str("Hotkeys.Left");
  2233. t.right = Str("Hotkeys.Right");
  2234. t.up = Str("Hotkeys.Up");
  2235. t.down = Str("Hotkeys.Down");
  2236. #ifdef _WIN32
  2237. t.meta = Str("Hotkeys.Windows");
  2238. #else
  2239. t.meta = Str("Hotkeys.Super");
  2240. #endif
  2241. t.menu = Str("Hotkeys.Menu");
  2242. t.space = Str("Hotkeys.Space");
  2243. t.numpad_num = Str("Hotkeys.NumpadNum");
  2244. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  2245. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  2246. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  2247. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  2248. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  2249. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  2250. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  2251. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  2252. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  2253. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  2254. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  2255. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  2256. t.mouse_num = Str("Hotkeys.MouseButton");
  2257. t.escape = Str("Hotkeys.Escape");
  2258. obs_hotkeys_set_translations(&t);
  2259. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  2260. Str("Push-to-mute"),
  2261. Str("Push-to-talk"));
  2262. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  2263. Str("SceneItemHide"));
  2264. obs_hotkey_enable_callback_rerouting(true);
  2265. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  2266. }
  2267. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  2268. {
  2269. obs_hotkey_trigger_routed_callback(id, pressed);
  2270. }
  2271. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  2272. {
  2273. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2274. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  2275. Q_ARG(obs_hotkey_id, id),
  2276. Q_ARG(bool, pressed));
  2277. }
  2278. void OBSBasic::CreateHotkeys()
  2279. {
  2280. ProfileScope("OBSBasic::CreateHotkeys");
  2281. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  2282. const char *info =
  2283. config_get_string(basicConfig, "Hotkeys", name);
  2284. if (!info)
  2285. return {};
  2286. OBSDataAutoRelease data = obs_data_create_from_json(info);
  2287. if (!data)
  2288. return {};
  2289. return data.Get();
  2290. };
  2291. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  2292. OBSDataArrayAutoRelease array =
  2293. obs_data_get_array(LoadHotkeyData(name), "bindings");
  2294. obs_hotkey_load(id, array);
  2295. };
  2296. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  2297. const char *name1,
  2298. const char *oldName = NULL) {
  2299. if (oldName) {
  2300. const auto info = config_get_string(basicConfig,
  2301. "Hotkeys", oldName);
  2302. if (info) {
  2303. config_set_string(basicConfig, "Hotkeys", name0,
  2304. info);
  2305. config_set_string(basicConfig, "Hotkeys", name1,
  2306. info);
  2307. config_remove_value(basicConfig, "Hotkeys",
  2308. oldName);
  2309. config_save(basicConfig);
  2310. }
  2311. }
  2312. OBSDataArrayAutoRelease array0 =
  2313. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  2314. OBSDataArrayAutoRelease array1 =
  2315. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  2316. obs_hotkey_pair_load(id, array0, array1);
  2317. };
  2318. #define MAKE_CALLBACK(pred, method, log_action) \
  2319. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  2320. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  2321. if ((pred) && pressed) { \
  2322. blog(LOG_INFO, log_action " due to hotkey"); \
  2323. method(); \
  2324. return true; \
  2325. } \
  2326. return false; \
  2327. }
  2328. streamingHotkeys = obs_hotkey_pair_register_frontend(
  2329. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  2330. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  2331. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  2332. !basic.streamingStarting,
  2333. basic.StartStreaming, "Starting stream"),
  2334. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  2335. !basic.streamingStarting,
  2336. basic.StopStreaming, "Stopping stream"),
  2337. this, this);
  2338. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  2339. "OBSBasic.StopStreaming");
  2340. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2341. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2342. if (basic.outputHandler->StreamingActive() && pressed) {
  2343. basic.ForceStopStreaming();
  2344. }
  2345. };
  2346. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  2347. "OBSBasic.ForceStopStreaming",
  2348. Str("Basic.Main.ForceStopStreaming"), cb, this);
  2349. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  2350. recordingHotkeys = obs_hotkey_pair_register_frontend(
  2351. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  2352. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  2353. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  2354. !basic.recordingStarted,
  2355. basic.StartRecording, "Starting recording"),
  2356. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  2357. basic.recordingStarted,
  2358. basic.StopRecording, "Stopping recording"),
  2359. this, this);
  2360. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  2361. "OBSBasic.StopRecording");
  2362. pauseHotkeys = obs_hotkey_pair_register_frontend(
  2363. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  2364. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  2365. MAKE_CALLBACK(basic.isRecordingPausable &&
  2366. !basic.recordingPaused,
  2367. basic.PauseRecording, "Pausing recording"),
  2368. MAKE_CALLBACK(basic.isRecordingPausable &&
  2369. basic.recordingPaused,
  2370. basic.UnpauseRecording, "Unpausing recording"),
  2371. this, this);
  2372. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  2373. "OBSBasic.UnpauseRecording");
  2374. splitFileHotkey = obs_hotkey_register_frontend(
  2375. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  2376. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2377. if (pressed)
  2378. obs_frontend_recording_split_file();
  2379. },
  2380. this);
  2381. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  2382. addChapterHotkey = obs_hotkey_register_frontend(
  2383. "OBSBasic.AddChapterMarker", Str("Basic.Main.AddChapterMarker"),
  2384. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2385. if (pressed)
  2386. obs_frontend_recording_add_chapter(nullptr);
  2387. },
  2388. this);
  2389. LoadHotkey(addChapterHotkey, "OBSBasic.AddChapterMarker");
  2390. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  2391. "OBSBasic.StartReplayBuffer",
  2392. Str("Basic.Main.StartReplayBuffer"),
  2393. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  2394. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  2395. basic.StartReplayBuffer,
  2396. "Starting replay buffer"),
  2397. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2398. basic.StopReplayBuffer, "Stopping replay buffer"),
  2399. this, this);
  2400. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2401. "OBSBasic.StopReplayBuffer");
  2402. if (vcamEnabled) {
  2403. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2404. "OBSBasic.StartVirtualCam",
  2405. Str("Basic.Main.StartVirtualCam"),
  2406. "OBSBasic.StopVirtualCam",
  2407. Str("Basic.Main.StopVirtualCam"),
  2408. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2409. basic.StartVirtualCam,
  2410. "Starting virtual camera"),
  2411. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2412. basic.StopVirtualCam,
  2413. "Stopping virtual camera"),
  2414. this, this);
  2415. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2416. "OBSBasic.StopVirtualCam");
  2417. }
  2418. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2419. "OBSBasic.EnablePreview",
  2420. Str("Basic.Main.PreviewConextMenu.Enable"),
  2421. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2422. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2423. "Enabling preview"),
  2424. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2425. "Disabling preview"),
  2426. this, this);
  2427. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2428. "OBSBasic.DisablePreview");
  2429. togglePreviewProgramHotkeys = obs_hotkey_pair_register_frontend(
  2430. "OBSBasic.EnablePreviewProgram",
  2431. Str("Basic.EnablePreviewProgramMode"),
  2432. "OBSBasic.DisablePreviewProgram",
  2433. Str("Basic.DisablePreviewProgramMode"),
  2434. MAKE_CALLBACK(!basic.IsPreviewProgramMode(),
  2435. basic.EnablePreviewProgram,
  2436. "Enabling preview program"),
  2437. MAKE_CALLBACK(basic.IsPreviewProgramMode(),
  2438. basic.DisablePreviewProgram,
  2439. "Disabling preview program"),
  2440. this, this);
  2441. LoadHotkeyPair(togglePreviewProgramHotkeys,
  2442. "OBSBasic.EnablePreviewProgram",
  2443. "OBSBasic.DisablePreviewProgram",
  2444. "OBSBasic.TogglePreviewProgram");
  2445. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2446. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2447. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2448. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2449. basic.ShowContextBar, "Showing Context Bar"),
  2450. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2451. basic.HideContextBar, "Hiding Context Bar"),
  2452. this, this);
  2453. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2454. "OBSBasic.HideContextBar");
  2455. #undef MAKE_CALLBACK
  2456. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2457. bool pressed) {
  2458. if (pressed)
  2459. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2460. "TransitionClicked",
  2461. Qt::QueuedConnection);
  2462. };
  2463. transitionHotkey = obs_hotkey_register_frontend(
  2464. "OBSBasic.Transition", Str("Transition"), transition, this);
  2465. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2466. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2467. bool pressed) {
  2468. if (pressed)
  2469. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2470. "ResetStatsHotkey",
  2471. Qt::QueuedConnection);
  2472. };
  2473. statsHotkey = obs_hotkey_register_frontend(
  2474. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2475. resetStats, this);
  2476. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2477. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2478. bool pressed) {
  2479. if (pressed)
  2480. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2481. "Screenshot",
  2482. Qt::QueuedConnection);
  2483. };
  2484. screenshotHotkey = obs_hotkey_register_frontend(
  2485. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2486. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2487. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2488. bool pressed) {
  2489. if (pressed)
  2490. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2491. "ScreenshotSelectedSource",
  2492. Qt::QueuedConnection);
  2493. };
  2494. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2495. "OBSBasic.SelectedSourceScreenshot",
  2496. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2497. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2498. }
  2499. void OBSBasic::ClearHotkeys()
  2500. {
  2501. obs_hotkey_pair_unregister(streamingHotkeys);
  2502. obs_hotkey_pair_unregister(recordingHotkeys);
  2503. obs_hotkey_pair_unregister(pauseHotkeys);
  2504. obs_hotkey_unregister(splitFileHotkey);
  2505. obs_hotkey_unregister(addChapterHotkey);
  2506. obs_hotkey_pair_unregister(replayBufHotkeys);
  2507. obs_hotkey_pair_unregister(vcamHotkeys);
  2508. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2509. obs_hotkey_pair_unregister(contextBarHotkeys);
  2510. obs_hotkey_pair_unregister(togglePreviewProgramHotkeys);
  2511. obs_hotkey_unregister(forceStreamingStopHotkey);
  2512. obs_hotkey_unregister(transitionHotkey);
  2513. obs_hotkey_unregister(statsHotkey);
  2514. obs_hotkey_unregister(screenshotHotkey);
  2515. obs_hotkey_unregister(sourceScreenshotHotkey);
  2516. }
  2517. OBSBasic::~OBSBasic()
  2518. {
  2519. /* clear out UI event queue */
  2520. QApplication::sendPostedEvents(nullptr);
  2521. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2522. if (updateCheckThread && updateCheckThread->isRunning())
  2523. updateCheckThread->wait();
  2524. if (patronJsonThread && patronJsonThread->isRunning())
  2525. patronJsonThread->wait();
  2526. delete screenshotData;
  2527. delete previewProjector;
  2528. delete studioProgramProjector;
  2529. delete previewProjectorSource;
  2530. delete previewProjectorMain;
  2531. delete sourceProjector;
  2532. delete sceneProjectorMenu;
  2533. delete scaleFilteringMenu;
  2534. delete blendingModeMenu;
  2535. delete colorMenu;
  2536. delete colorWidgetAction;
  2537. delete colorSelect;
  2538. delete deinterlaceMenu;
  2539. delete perSceneTransitionMenu;
  2540. delete shortcutFilter;
  2541. delete trayMenu;
  2542. delete programOptions;
  2543. delete program;
  2544. /* XXX: any obs data must be released before calling obs_shutdown.
  2545. * currently, we can't automate this with C++ RAII because of the
  2546. * delicate nature of obs_shutdown needing to be freed before the UI
  2547. * can be freed, and we have no control over the destruction order of
  2548. * the Qt UI stuff, so we have to manually clear any references to
  2549. * libobs. */
  2550. delete cpuUsageTimer;
  2551. os_cpu_usage_info_destroy(cpuUsageInfo);
  2552. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2553. ClearHotkeys();
  2554. service = nullptr;
  2555. outputHandler.reset();
  2556. delete interaction;
  2557. delete properties;
  2558. delete filters;
  2559. delete transformWindow;
  2560. delete advAudioWindow;
  2561. delete about;
  2562. delete remux;
  2563. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2564. OBSBasic::RenderMain, this);
  2565. obs_enter_graphics();
  2566. gs_vertexbuffer_destroy(box);
  2567. gs_vertexbuffer_destroy(boxLeft);
  2568. gs_vertexbuffer_destroy(boxTop);
  2569. gs_vertexbuffer_destroy(boxRight);
  2570. gs_vertexbuffer_destroy(boxBottom);
  2571. gs_vertexbuffer_destroy(circle);
  2572. gs_vertexbuffer_destroy(actionSafeMargin);
  2573. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2574. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2575. gs_vertexbuffer_destroy(leftLine);
  2576. gs_vertexbuffer_destroy(topLine);
  2577. gs_vertexbuffer_destroy(rightLine);
  2578. obs_leave_graphics();
  2579. /* When shutting down, sometimes source references can get in to the
  2580. * event queue, and if we don't forcibly process those events they
  2581. * won't get processed until after obs_shutdown has been called. I
  2582. * really wish there were a more elegant way to deal with this via C++,
  2583. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2584. * normal C++ behavior for your data to be freed in the order that you
  2585. * expect or want it to. */
  2586. QApplication::sendPostedEvents(nullptr);
  2587. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2588. LIBOBS_API_VER);
  2589. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2590. previewEnabled);
  2591. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2592. ui->actionAlwaysOnTop->isChecked());
  2593. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2594. "SceneDuplicationMode", sceneDuplicationMode);
  2595. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2596. swapScenesMode);
  2597. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2598. "EditPropertiesMode", editPropertiesMode);
  2599. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2600. "PreviewProgramMode", IsPreviewProgramMode());
  2601. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2602. ui->lockDocks->isChecked());
  2603. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SideDocks",
  2604. ui->sideDocks->isChecked());
  2605. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2606. #ifdef BROWSER_AVAILABLE
  2607. DestroyPanelCookieManager();
  2608. delete cef;
  2609. cef = nullptr;
  2610. #endif
  2611. }
  2612. void OBSBasic::SaveProjectNow()
  2613. {
  2614. if (disableSaving)
  2615. return;
  2616. projectChanged = true;
  2617. SaveProjectDeferred();
  2618. }
  2619. void OBSBasic::SaveProject()
  2620. {
  2621. if (disableSaving)
  2622. return;
  2623. projectChanged = true;
  2624. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2625. Qt::QueuedConnection);
  2626. }
  2627. void OBSBasic::SaveProjectDeferred()
  2628. {
  2629. if (disableSaving)
  2630. return;
  2631. if (!projectChanged)
  2632. return;
  2633. projectChanged = false;
  2634. const char *sceneCollection = config_get_string(
  2635. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2636. char savePath[1024];
  2637. char fileName[1024];
  2638. int ret;
  2639. if (!sceneCollection)
  2640. return;
  2641. ret = snprintf(fileName, sizeof(fileName),
  2642. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2643. if (ret <= 0)
  2644. return;
  2645. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2646. if (ret <= 0)
  2647. return;
  2648. Save(savePath);
  2649. }
  2650. OBSSource OBSBasic::GetProgramSource()
  2651. {
  2652. return OBSGetStrongRef(programScene);
  2653. }
  2654. OBSScene OBSBasic::GetCurrentScene()
  2655. {
  2656. return currentScene.load();
  2657. }
  2658. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2659. {
  2660. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2661. }
  2662. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2663. {
  2664. return ui->sources->Get(GetTopSelectedSourceItem());
  2665. }
  2666. void OBSBasic::UpdatePreviewScalingMenu()
  2667. {
  2668. bool fixedScaling = ui->preview->IsFixedScaling();
  2669. float scalingAmount = ui->preview->GetScalingAmount();
  2670. if (!fixedScaling) {
  2671. ui->actionScaleWindow->setChecked(true);
  2672. ui->actionScaleCanvas->setChecked(false);
  2673. ui->actionScaleOutput->setChecked(false);
  2674. return;
  2675. }
  2676. obs_video_info ovi;
  2677. obs_get_video_info(&ovi);
  2678. ui->actionScaleWindow->setChecked(false);
  2679. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2680. ui->actionScaleOutput->setChecked(scalingAmount ==
  2681. float(ovi.output_width) /
  2682. float(ovi.base_width));
  2683. }
  2684. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2685. {
  2686. bool closed = true;
  2687. if (interaction)
  2688. closed = interaction->close();
  2689. if (!closed)
  2690. return;
  2691. interaction = new OBSBasicInteraction(this, source);
  2692. interaction->Init();
  2693. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2694. }
  2695. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2696. {
  2697. bool closed = true;
  2698. if (properties)
  2699. closed = properties->close();
  2700. if (!closed)
  2701. return;
  2702. properties = new OBSBasicProperties(this, source);
  2703. properties->Init();
  2704. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2705. }
  2706. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2707. {
  2708. bool closed = true;
  2709. if (filters)
  2710. closed = filters->close();
  2711. if (!closed)
  2712. return;
  2713. filters = new OBSBasicFilters(this, source);
  2714. filters->Init();
  2715. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2716. }
  2717. /* Qt callbacks for invokeMethod */
  2718. void OBSBasic::AddScene(OBSSource source)
  2719. {
  2720. const char *name = obs_source_get_name(source);
  2721. obs_scene_t *scene = obs_scene_from_source(source);
  2722. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2723. SetOBSRef(item, OBSScene(scene));
  2724. ui->scenes->insertItem(ui->scenes->currentRow() + 1, item);
  2725. obs_hotkey_register_source(
  2726. source, "OBSBasic.SelectScene",
  2727. Str("Basic.Hotkeys.SelectScene"),
  2728. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2729. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2730. App()->GetMainWindow());
  2731. auto potential_source =
  2732. static_cast<obs_source_t *>(data);
  2733. OBSSourceAutoRelease source =
  2734. obs_source_get_ref(potential_source);
  2735. if (source && pressed)
  2736. main->SetCurrentScene(source.Get());
  2737. },
  2738. static_cast<obs_source_t *>(source));
  2739. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2740. SignalContainer<OBSScene> container;
  2741. container.ref = scene;
  2742. container.handlers.assign({
  2743. std::make_shared<OBSSignal>(handler, "item_add",
  2744. OBSBasic::SceneItemAdded, this),
  2745. std::make_shared<OBSSignal>(handler, "reorder",
  2746. OBSBasic::SceneReordered, this),
  2747. std::make_shared<OBSSignal>(handler, "refresh",
  2748. OBSBasic::SceneRefreshed, this),
  2749. });
  2750. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2751. QVariant::fromValue(container));
  2752. /* if the scene already has items (a duplicated scene) add them */
  2753. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2754. AddSceneItem(item);
  2755. };
  2756. using addSceneItem_t = decltype(addSceneItem);
  2757. obs_scene_enum_items(
  2758. scene,
  2759. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2760. addSceneItem_t *func;
  2761. func = reinterpret_cast<addSceneItem_t *>(param);
  2762. (*func)(item);
  2763. return true;
  2764. },
  2765. &addSceneItem);
  2766. SaveProject();
  2767. if (!disableSaving) {
  2768. obs_source_t *source = obs_scene_get_source(scene);
  2769. blog(LOG_INFO, "User added scene '%s'",
  2770. obs_source_get_name(source));
  2771. OBSProjector::UpdateMultiviewProjectors();
  2772. }
  2773. OnEvent(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2774. }
  2775. void OBSBasic::RemoveScene(OBSSource source)
  2776. {
  2777. obs_scene_t *scene = obs_scene_from_source(source);
  2778. QListWidgetItem *sel = nullptr;
  2779. int count = ui->scenes->count();
  2780. for (int i = 0; i < count; i++) {
  2781. auto item = ui->scenes->item(i);
  2782. auto cur_scene = GetOBSRef<OBSScene>(item);
  2783. if (cur_scene != scene)
  2784. continue;
  2785. sel = item;
  2786. break;
  2787. }
  2788. if (sel != nullptr) {
  2789. if (sel == ui->scenes->currentItem())
  2790. ui->sources->Clear();
  2791. delete sel;
  2792. }
  2793. SaveProject();
  2794. if (!disableSaving) {
  2795. blog(LOG_INFO, "User Removed scene '%s'",
  2796. obs_source_get_name(source));
  2797. OBSProjector::UpdateMultiviewProjectors();
  2798. }
  2799. OnEvent(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2800. }
  2801. static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item,
  2802. void *param)
  2803. {
  2804. obs_sceneitem_t *selectedItem =
  2805. reinterpret_cast<obs_sceneitem_t *>(param);
  2806. if (obs_sceneitem_is_group(item))
  2807. obs_sceneitem_group_enum_items(item, select_one, param);
  2808. obs_sceneitem_select(item, (selectedItem == item));
  2809. return true;
  2810. }
  2811. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2812. {
  2813. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2814. if (GetCurrentScene() == scene)
  2815. ui->sources->Add(item);
  2816. SaveProject();
  2817. if (!disableSaving) {
  2818. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2819. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2820. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2821. obs_source_get_name(itemSource),
  2822. obs_source_get_id(itemSource),
  2823. obs_source_get_name(sceneSource));
  2824. obs_scene_enum_items(scene, select_one,
  2825. (obs_sceneitem_t *)item);
  2826. }
  2827. }
  2828. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2829. const QString &prevName)
  2830. {
  2831. QList<QListWidgetItem *> items =
  2832. listWidget->findItems(prevName, Qt::MatchExactly);
  2833. for (int i = 0; i < items.count(); i++)
  2834. items[i]->setText(newName);
  2835. }
  2836. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2837. QString prevName)
  2838. {
  2839. RenameListValues(ui->scenes, newName, prevName);
  2840. if (vcamConfig.type == VCamOutputType::SourceOutput &&
  2841. prevName == QString::fromStdString(vcamConfig.source))
  2842. vcamConfig.source = newName.toStdString();
  2843. if (vcamConfig.type == VCamOutputType::SceneOutput &&
  2844. prevName == QString::fromStdString(vcamConfig.scene))
  2845. vcamConfig.scene = newName.toStdString();
  2846. SaveProject();
  2847. obs_scene_t *scene = obs_scene_from_source(source);
  2848. if (scene)
  2849. OBSProjector::UpdateMultiviewProjectors();
  2850. UpdateContextBar();
  2851. UpdatePreviewProgramIndicators();
  2852. }
  2853. void OBSBasic::ClearContextBar()
  2854. {
  2855. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2856. if (la) {
  2857. delete la->widget();
  2858. ui->emptySpace->layout()->removeItem(la);
  2859. }
  2860. }
  2861. void OBSBasic::UpdateContextBarVisibility()
  2862. {
  2863. int width = ui->centralwidget->size().width();
  2864. ContextBarSize contextBarSizeNew;
  2865. if (width >= 740) {
  2866. contextBarSizeNew = ContextBarSize_Normal;
  2867. } else if (width >= 600) {
  2868. contextBarSizeNew = ContextBarSize_Reduced;
  2869. } else {
  2870. contextBarSizeNew = ContextBarSize_Minimized;
  2871. }
  2872. if (contextBarSize == contextBarSizeNew)
  2873. return;
  2874. contextBarSize = contextBarSizeNew;
  2875. UpdateContextBarDeferred();
  2876. }
  2877. static bool is_network_media_source(obs_source_t *source, const char *id)
  2878. {
  2879. if (strcmp(id, "ffmpeg_source") != 0)
  2880. return false;
  2881. OBSDataAutoRelease s = obs_source_get_settings(source);
  2882. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2883. return !is_local_file;
  2884. }
  2885. void OBSBasic::UpdateContextBarDeferred(bool force)
  2886. {
  2887. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2888. Qt::QueuedConnection, Q_ARG(bool, force));
  2889. }
  2890. void OBSBasic::SourceToolBarActionsSetEnabled()
  2891. {
  2892. bool enable = false;
  2893. bool disableProps = false;
  2894. OBSSceneItem item = GetCurrentSceneItem();
  2895. if (item) {
  2896. OBSSource source = obs_sceneitem_get_source(item);
  2897. disableProps = !obs_source_configurable(source);
  2898. enable = true;
  2899. }
  2900. if (disableProps)
  2901. ui->actionSourceProperties->setEnabled(false);
  2902. else
  2903. ui->actionSourceProperties->setEnabled(enable);
  2904. ui->actionRemoveSource->setEnabled(enable);
  2905. ui->actionSourceUp->setEnabled(enable);
  2906. ui->actionSourceDown->setEnabled(enable);
  2907. RefreshToolBarStyling(ui->sourcesToolbar);
  2908. }
  2909. void OBSBasic::UpdateContextBar(bool force)
  2910. {
  2911. SourceToolBarActionsSetEnabled();
  2912. if (!ui->contextContainer->isVisible() && !force)
  2913. return;
  2914. OBSSceneItem item = GetCurrentSceneItem();
  2915. if (item) {
  2916. obs_source_t *source = obs_sceneitem_get_source(item);
  2917. bool updateNeeded = true;
  2918. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2919. if (la) {
  2920. if (SourceToolbar *toolbar =
  2921. dynamic_cast<SourceToolbar *>(
  2922. la->widget())) {
  2923. if (toolbar->GetSource() == source)
  2924. updateNeeded = false;
  2925. } else if (MediaControls *toolbar =
  2926. dynamic_cast<MediaControls *>(
  2927. la->widget())) {
  2928. if (toolbar->GetSource() == source)
  2929. updateNeeded = false;
  2930. }
  2931. }
  2932. const char *id = obs_source_get_unversioned_id(source);
  2933. uint32_t flags = obs_source_get_output_flags(source);
  2934. ui->sourceInteractButton->setVisible(flags &
  2935. OBS_SOURCE_INTERACTION);
  2936. if (contextBarSize >= ContextBarSize_Reduced &&
  2937. (updateNeeded || force)) {
  2938. ClearContextBar();
  2939. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2940. if (!is_network_media_source(source, id)) {
  2941. MediaControls *mediaControls =
  2942. new MediaControls(
  2943. ui->emptySpace);
  2944. mediaControls->SetSource(source);
  2945. ui->emptySpace->layout()->addWidget(
  2946. mediaControls);
  2947. }
  2948. } else if (strcmp(id, "browser_source") == 0) {
  2949. BrowserToolbar *c = new BrowserToolbar(
  2950. ui->emptySpace, source);
  2951. ui->emptySpace->layout()->addWidget(c);
  2952. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2953. strcmp(id, "wasapi_output_capture") == 0 ||
  2954. strcmp(id, "coreaudio_input_capture") == 0 ||
  2955. strcmp(id, "coreaudio_output_capture") ==
  2956. 0 ||
  2957. strcmp(id, "pulse_input_capture") == 0 ||
  2958. strcmp(id, "pulse_output_capture") == 0 ||
  2959. strcmp(id, "alsa_input_capture") == 0) {
  2960. AudioCaptureToolbar *c =
  2961. new AudioCaptureToolbar(ui->emptySpace,
  2962. source);
  2963. c->Init();
  2964. ui->emptySpace->layout()->addWidget(c);
  2965. } else if (strcmp(id,
  2966. "wasapi_process_output_capture") ==
  2967. 0) {
  2968. ApplicationAudioCaptureToolbar *c =
  2969. new ApplicationAudioCaptureToolbar(
  2970. ui->emptySpace, source);
  2971. c->Init();
  2972. ui->emptySpace->layout()->addWidget(c);
  2973. } else if (strcmp(id, "window_capture") == 0 ||
  2974. strcmp(id, "xcomposite_input") == 0) {
  2975. WindowCaptureToolbar *c =
  2976. new WindowCaptureToolbar(ui->emptySpace,
  2977. source);
  2978. c->Init();
  2979. ui->emptySpace->layout()->addWidget(c);
  2980. } else if (strcmp(id, "monitor_capture") == 0 ||
  2981. strcmp(id, "display_capture") == 0 ||
  2982. strcmp(id, "xshm_input") == 0) {
  2983. DisplayCaptureToolbar *c =
  2984. new DisplayCaptureToolbar(
  2985. ui->emptySpace, source);
  2986. c->Init();
  2987. ui->emptySpace->layout()->addWidget(c);
  2988. } else if (strcmp(id, "dshow_input") == 0) {
  2989. DeviceCaptureToolbar *c =
  2990. new DeviceCaptureToolbar(ui->emptySpace,
  2991. source);
  2992. ui->emptySpace->layout()->addWidget(c);
  2993. } else if (strcmp(id, "game_capture") == 0) {
  2994. GameCaptureToolbar *c = new GameCaptureToolbar(
  2995. ui->emptySpace, source);
  2996. ui->emptySpace->layout()->addWidget(c);
  2997. } else if (strcmp(id, "image_source") == 0) {
  2998. ImageSourceToolbar *c = new ImageSourceToolbar(
  2999. ui->emptySpace, source);
  3000. ui->emptySpace->layout()->addWidget(c);
  3001. } else if (strcmp(id, "color_source") == 0) {
  3002. ColorSourceToolbar *c = new ColorSourceToolbar(
  3003. ui->emptySpace, source);
  3004. ui->emptySpace->layout()->addWidget(c);
  3005. } else if (strcmp(id, "text_ft2_source") == 0 ||
  3006. strcmp(id, "text_gdiplus") == 0) {
  3007. TextSourceToolbar *c = new TextSourceToolbar(
  3008. ui->emptySpace, source);
  3009. ui->emptySpace->layout()->addWidget(c);
  3010. }
  3011. } else if (contextBarSize == ContextBarSize_Minimized) {
  3012. ClearContextBar();
  3013. }
  3014. QIcon icon;
  3015. if (strcmp(id, "scene") == 0)
  3016. icon = GetSceneIcon();
  3017. else if (strcmp(id, "group") == 0)
  3018. icon = GetGroupIcon();
  3019. else
  3020. icon = GetSourceIcon(id);
  3021. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  3022. ui->contextSourceIcon->setPixmap(pixmap);
  3023. ui->contextSourceIconSpacer->hide();
  3024. ui->contextSourceIcon->show();
  3025. const char *name = obs_source_get_name(source);
  3026. ui->contextSourceLabel->setText(name);
  3027. ui->sourceFiltersButton->setEnabled(true);
  3028. ui->sourcePropertiesButton->setEnabled(
  3029. obs_source_configurable(source));
  3030. } else {
  3031. ClearContextBar();
  3032. ui->contextSourceIcon->hide();
  3033. ui->contextSourceIconSpacer->show();
  3034. ui->contextSourceLabel->setText(
  3035. QTStr("ContextBar.NoSelectedSource"));
  3036. ui->sourceFiltersButton->setEnabled(false);
  3037. ui->sourcePropertiesButton->setEnabled(false);
  3038. ui->sourceInteractButton->setVisible(false);
  3039. }
  3040. if (contextBarSize == ContextBarSize_Normal) {
  3041. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  3042. ui->sourceFiltersButton->setText(QTStr("Filters"));
  3043. ui->sourceInteractButton->setText(QTStr("Interact"));
  3044. } else {
  3045. ui->sourcePropertiesButton->setText("");
  3046. ui->sourceFiltersButton->setText("");
  3047. ui->sourceInteractButton->setText("");
  3048. }
  3049. }
  3050. static inline bool SourceMixerHidden(obs_source_t *source)
  3051. {
  3052. OBSDataAutoRelease priv_settings =
  3053. obs_source_get_private_settings(source);
  3054. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  3055. return hidden;
  3056. }
  3057. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  3058. {
  3059. OBSDataAutoRelease priv_settings =
  3060. obs_source_get_private_settings(source);
  3061. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  3062. }
  3063. void OBSBasic::GetAudioSourceFilters()
  3064. {
  3065. QAction *action = reinterpret_cast<QAction *>(sender());
  3066. VolControl *vol = action->property("volControl").value<VolControl *>();
  3067. obs_source_t *source = vol->GetSource();
  3068. CreateFiltersWindow(source);
  3069. }
  3070. void OBSBasic::GetAudioSourceProperties()
  3071. {
  3072. QAction *action = reinterpret_cast<QAction *>(sender());
  3073. VolControl *vol = action->property("volControl").value<VolControl *>();
  3074. obs_source_t *source = vol->GetSource();
  3075. CreatePropertiesWindow(source);
  3076. }
  3077. void OBSBasic::HideAudioControl()
  3078. {
  3079. QAction *action = reinterpret_cast<QAction *>(sender());
  3080. VolControl *vol = action->property("volControl").value<VolControl *>();
  3081. obs_source_t *source = vol->GetSource();
  3082. if (!SourceMixerHidden(source)) {
  3083. SetSourceMixerHidden(source, true);
  3084. /* Due to a bug with QT 6.2.4, the version that's in the Ubuntu
  3085. * 22.04 ppa, hiding the audio mixer causes a crash, so defer to
  3086. * the next event loop to hide it. Doesn't seem to be a problem
  3087. * with newer versions of QT. */
  3088. QMetaObject::invokeMethod(this, "DeactivateAudioSource",
  3089. Qt::QueuedConnection,
  3090. Q_ARG(OBSSource, OBSSource(source)));
  3091. }
  3092. }
  3093. void OBSBasic::UnhideAllAudioControls()
  3094. {
  3095. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  3096. {
  3097. if (!obs_source_active(source))
  3098. return true;
  3099. if (!SourceMixerHidden(source))
  3100. return true;
  3101. SetSourceMixerHidden(source, false);
  3102. ActivateAudioSource(source);
  3103. return true;
  3104. };
  3105. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  3106. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  3107. {
  3108. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  3109. };
  3110. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  3111. }
  3112. void OBSBasic::ToggleHideMixer()
  3113. {
  3114. OBSSceneItem item = GetCurrentSceneItem();
  3115. OBSSource source = obs_sceneitem_get_source(item);
  3116. if (!SourceMixerHidden(source)) {
  3117. SetSourceMixerHidden(source, true);
  3118. DeactivateAudioSource(source);
  3119. } else {
  3120. SetSourceMixerHidden(source, false);
  3121. ActivateAudioSource(source);
  3122. }
  3123. }
  3124. void OBSBasic::MixerRenameSource()
  3125. {
  3126. QAction *action = reinterpret_cast<QAction *>(sender());
  3127. VolControl *vol = action->property("volControl").value<VolControl *>();
  3128. OBSSource source = vol->GetSource();
  3129. const char *prevName = obs_source_get_name(source);
  3130. for (;;) {
  3131. string name;
  3132. bool accepted = NameDialog::AskForName(
  3133. this, QTStr("Basic.Main.MixerRename.Title"),
  3134. QTStr("Basic.Main.MixerRename.Text"), name,
  3135. QT_UTF8(prevName));
  3136. if (!accepted)
  3137. return;
  3138. if (name.empty()) {
  3139. OBSMessageBox::warning(this,
  3140. QTStr("NoNameEntered.Title"),
  3141. QTStr("NoNameEntered.Text"));
  3142. continue;
  3143. }
  3144. OBSSourceAutoRelease sourceTest =
  3145. obs_get_source_by_name(name.c_str());
  3146. if (sourceTest) {
  3147. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3148. QTStr("NameExists.Text"));
  3149. continue;
  3150. }
  3151. obs_source_set_name(source, name.c_str());
  3152. break;
  3153. }
  3154. }
  3155. static inline bool SourceVolumeLocked(obs_source_t *source)
  3156. {
  3157. OBSDataAutoRelease priv_settings =
  3158. obs_source_get_private_settings(source);
  3159. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  3160. return lock;
  3161. }
  3162. void OBSBasic::LockVolumeControl(bool lock)
  3163. {
  3164. QAction *action = reinterpret_cast<QAction *>(sender());
  3165. VolControl *vol = action->property("volControl").value<VolControl *>();
  3166. obs_source_t *source = vol->GetSource();
  3167. OBSDataAutoRelease priv_settings =
  3168. obs_source_get_private_settings(source);
  3169. obs_data_set_bool(priv_settings, "volume_locked", lock);
  3170. vol->EnableSlider(!lock);
  3171. }
  3172. void OBSBasic::VolControlContextMenu()
  3173. {
  3174. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  3175. /* ------------------- */
  3176. QAction lockAction(QTStr("LockVolume"), this);
  3177. lockAction.setCheckable(true);
  3178. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  3179. QAction hideAction(QTStr("Hide"), this);
  3180. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3181. QAction mixerRenameAction(QTStr("Rename"), this);
  3182. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  3183. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  3184. QAction filtersAction(QTStr("Filters"), this);
  3185. QAction propertiesAction(QTStr("Properties"), this);
  3186. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3187. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3188. toggleControlLayoutAction.setCheckable(true);
  3189. toggleControlLayoutAction.setChecked(config_get_bool(
  3190. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3191. /* ------------------- */
  3192. connect(&hideAction, &QAction::triggered, this,
  3193. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  3194. connect(&unhideAllAction, &QAction::triggered, this,
  3195. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3196. connect(&lockAction, &QAction::toggled, this,
  3197. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  3198. connect(&mixerRenameAction, &QAction::triggered, this,
  3199. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  3200. connect(&copyFiltersAction, &QAction::triggered, this,
  3201. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  3202. connect(&pasteFiltersAction, &QAction::triggered, this,
  3203. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  3204. connect(&filtersAction, &QAction::triggered, this,
  3205. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  3206. connect(&propertiesAction, &QAction::triggered, this,
  3207. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  3208. connect(&advPropAction, &QAction::triggered, this,
  3209. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3210. Qt::DirectConnection);
  3211. /* ------------------- */
  3212. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3213. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3214. /* ------------------- */
  3215. hideAction.setProperty("volControl",
  3216. QVariant::fromValue<VolControl *>(vol));
  3217. lockAction.setProperty("volControl",
  3218. QVariant::fromValue<VolControl *>(vol));
  3219. mixerRenameAction.setProperty("volControl",
  3220. QVariant::fromValue<VolControl *>(vol));
  3221. copyFiltersAction.setProperty("volControl",
  3222. QVariant::fromValue<VolControl *>(vol));
  3223. pasteFiltersAction.setProperty("volControl",
  3224. QVariant::fromValue<VolControl *>(vol));
  3225. filtersAction.setProperty("volControl",
  3226. QVariant::fromValue<VolControl *>(vol));
  3227. propertiesAction.setProperty("volControl",
  3228. QVariant::fromValue<VolControl *>(vol));
  3229. /* ------------------- */
  3230. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  3231. 0);
  3232. pasteFiltersAction.setEnabled(
  3233. !obs_weak_source_expired(copyFiltersSource));
  3234. QMenu popup;
  3235. vol->SetContextMenu(&popup);
  3236. popup.addAction(&lockAction);
  3237. popup.addSeparator();
  3238. popup.addAction(&unhideAllAction);
  3239. popup.addAction(&hideAction);
  3240. popup.addAction(&mixerRenameAction);
  3241. popup.addSeparator();
  3242. popup.addAction(&copyFiltersAction);
  3243. popup.addAction(&pasteFiltersAction);
  3244. popup.addSeparator();
  3245. popup.addAction(&toggleControlLayoutAction);
  3246. popup.addSeparator();
  3247. popup.addAction(&filtersAction);
  3248. popup.addAction(&propertiesAction);
  3249. popup.addAction(&advPropAction);
  3250. // toggleControlLayoutAction deletes and re-creates the volume controls
  3251. // meaning that "vol" would be pointing to freed memory.
  3252. if (popup.exec(QCursor::pos()) != &toggleControlLayoutAction)
  3253. vol->SetContextMenu(nullptr);
  3254. }
  3255. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  3256. {
  3257. StackedMixerAreaContextMenuRequested();
  3258. }
  3259. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  3260. {
  3261. StackedMixerAreaContextMenuRequested();
  3262. }
  3263. void OBSBasic::StackedMixerAreaContextMenuRequested()
  3264. {
  3265. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3266. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3267. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3268. toggleControlLayoutAction.setCheckable(true);
  3269. toggleControlLayoutAction.setChecked(config_get_bool(
  3270. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3271. /* ------------------- */
  3272. connect(&unhideAllAction, &QAction::triggered, this,
  3273. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3274. connect(&advPropAction, &QAction::triggered, this,
  3275. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3276. Qt::DirectConnection);
  3277. /* ------------------- */
  3278. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3279. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3280. /* ------------------- */
  3281. QMenu popup;
  3282. popup.addAction(&unhideAllAction);
  3283. popup.addSeparator();
  3284. popup.addAction(&toggleControlLayoutAction);
  3285. popup.addSeparator();
  3286. popup.addAction(&advPropAction);
  3287. popup.exec(QCursor::pos());
  3288. }
  3289. void OBSBasic::ToggleMixerLayout(bool vertical)
  3290. {
  3291. if (vertical) {
  3292. ui->stackedMixerArea->setMinimumSize(180, 220);
  3293. ui->stackedMixerArea->setCurrentIndex(1);
  3294. } else {
  3295. ui->stackedMixerArea->setMinimumSize(220, 0);
  3296. ui->stackedMixerArea->setCurrentIndex(0);
  3297. }
  3298. }
  3299. void OBSBasic::ToggleVolControlLayout()
  3300. {
  3301. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  3302. "VerticalVolControl");
  3303. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  3304. vertical);
  3305. ToggleMixerLayout(vertical);
  3306. // We need to store it so we can delete current and then add
  3307. // at the right order
  3308. vector<OBSSource> sources;
  3309. for (size_t i = 0; i != volumes.size(); i++)
  3310. sources.emplace_back(volumes[i]->GetSource());
  3311. ClearVolumeControls();
  3312. for (const auto &source : sources)
  3313. ActivateAudioSource(source);
  3314. }
  3315. void OBSBasic::ActivateAudioSource(OBSSource source)
  3316. {
  3317. if (SourceMixerHidden(source))
  3318. return;
  3319. if (!obs_source_active(source))
  3320. return;
  3321. if (!obs_source_audio_active(source))
  3322. return;
  3323. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3324. "VerticalVolControl");
  3325. VolControl *vol = new VolControl(source, true, vertical);
  3326. vol->EnableSlider(!SourceVolumeLocked(source));
  3327. double meterDecayRate =
  3328. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  3329. vol->SetMeterDecayRate(meterDecayRate);
  3330. uint32_t peakMeterTypeIdx =
  3331. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  3332. enum obs_peak_meter_type peakMeterType;
  3333. switch (peakMeterTypeIdx) {
  3334. case 0:
  3335. peakMeterType = SAMPLE_PEAK_METER;
  3336. break;
  3337. case 1:
  3338. peakMeterType = TRUE_PEAK_METER;
  3339. break;
  3340. default:
  3341. peakMeterType = SAMPLE_PEAK_METER;
  3342. break;
  3343. }
  3344. vol->setPeakMeterType(peakMeterType);
  3345. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  3346. connect(vol, &QWidget::customContextMenuRequested, this,
  3347. &OBSBasic::VolControlContextMenu);
  3348. connect(vol, &VolControl::ConfigClicked, this,
  3349. &OBSBasic::VolControlContextMenu);
  3350. InsertQObjectByName(volumes, vol);
  3351. for (auto volume : volumes) {
  3352. if (vertical)
  3353. ui->vVolControlLayout->addWidget(volume);
  3354. else
  3355. ui->hVolControlLayout->addWidget(volume);
  3356. }
  3357. }
  3358. void OBSBasic::DeactivateAudioSource(OBSSource source)
  3359. {
  3360. for (size_t i = 0; i < volumes.size(); i++) {
  3361. if (volumes[i]->GetSource() == source) {
  3362. delete volumes[i];
  3363. volumes.erase(volumes.begin() + i);
  3364. break;
  3365. }
  3366. }
  3367. }
  3368. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  3369. {
  3370. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  3371. !obs_source_is_group(source)) {
  3372. int count = ui->scenes->count();
  3373. if (count == 1) {
  3374. OBSMessageBox::information(this,
  3375. QTStr("FinalScene.Title"),
  3376. QTStr("FinalScene.Text"));
  3377. return false;
  3378. }
  3379. }
  3380. const char *name = obs_source_get_name(source);
  3381. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  3382. QMessageBox remove_source(this);
  3383. remove_source.setText(text);
  3384. QPushButton *Yes =
  3385. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  3386. remove_source.setDefaultButton(Yes);
  3387. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  3388. remove_source.setIcon(QMessageBox::Question);
  3389. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3390. remove_source.exec();
  3391. return Yes == remove_source.clickedButton();
  3392. }
  3393. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  3394. void OBSBasic::TimedCheckForUpdates()
  3395. {
  3396. if (App()->IsUpdaterDisabled())
  3397. return;
  3398. if (!config_get_bool(App()->GlobalConfig(), "General",
  3399. "EnableAutoUpdates"))
  3400. return;
  3401. #if defined(ENABLE_SPARKLE_UPDATER)
  3402. CheckForUpdates(false);
  3403. #elif _WIN32
  3404. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  3405. "LastUpdateCheck");
  3406. uint32_t lastVersion =
  3407. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  3408. if (lastVersion < LIBOBS_API_VER) {
  3409. lastUpdate = 0;
  3410. config_set_int(App()->GlobalConfig(), "General",
  3411. "LastUpdateCheck", 0);
  3412. }
  3413. long long t = (long long)time(nullptr);
  3414. long long secs = t - lastUpdate;
  3415. if (secs > UPDATE_CHECK_INTERVAL)
  3416. CheckForUpdates(false);
  3417. #endif
  3418. }
  3419. void OBSBasic::CheckForUpdates(bool manualUpdate)
  3420. {
  3421. #if _WIN32
  3422. ui->actionCheckForUpdates->setEnabled(false);
  3423. ui->actionRepair->setEnabled(false);
  3424. if (updateCheckThread && updateCheckThread->isRunning())
  3425. return;
  3426. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  3427. updateCheckThread->start();
  3428. #elif defined(ENABLE_SPARKLE_UPDATER)
  3429. ui->actionCheckForUpdates->setEnabled(false);
  3430. if (updateCheckThread && updateCheckThread->isRunning())
  3431. return;
  3432. MacUpdateThread *mut = new MacUpdateThread(manualUpdate);
  3433. connect(mut, &MacUpdateThread::Result, this,
  3434. &OBSBasic::MacBranchesFetched, Qt::QueuedConnection);
  3435. updateCheckThread.reset(mut);
  3436. updateCheckThread->start();
  3437. #else
  3438. UNUSED_PARAMETER(manualUpdate);
  3439. #endif
  3440. }
  3441. void OBSBasic::MacBranchesFetched(const QString &branch, bool manualUpdate)
  3442. {
  3443. #ifdef ENABLE_SPARKLE_UPDATER
  3444. static OBSSparkle *updater;
  3445. if (!updater) {
  3446. updater = new OBSSparkle(QT_TO_UTF8(branch),
  3447. ui->actionCheckForUpdates);
  3448. return;
  3449. }
  3450. updater->setBranch(QT_TO_UTF8(branch));
  3451. updater->checkForUpdates(manualUpdate);
  3452. #else
  3453. UNUSED_PARAMETER(branch);
  3454. UNUSED_PARAMETER(manualUpdate);
  3455. #endif
  3456. }
  3457. void OBSBasic::updateCheckFinished()
  3458. {
  3459. ui->actionCheckForUpdates->setEnabled(true);
  3460. ui->actionRepair->setEnabled(true);
  3461. }
  3462. void OBSBasic::DuplicateSelectedScene()
  3463. {
  3464. OBSScene curScene = GetCurrentScene();
  3465. if (!curScene)
  3466. return;
  3467. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3468. QString format{obs_source_get_name(curSceneSource)};
  3469. format += " %1";
  3470. int i = 2;
  3471. QString placeHolderText = format.arg(i);
  3472. OBSSourceAutoRelease source = nullptr;
  3473. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3474. placeHolderText = format.arg(++i);
  3475. }
  3476. for (;;) {
  3477. string name;
  3478. bool accepted = NameDialog::AskForName(
  3479. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3480. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3481. placeHolderText);
  3482. if (!accepted)
  3483. return;
  3484. if (name.empty()) {
  3485. OBSMessageBox::warning(this,
  3486. QTStr("NoNameEntered.Title"),
  3487. QTStr("NoNameEntered.Text"));
  3488. continue;
  3489. }
  3490. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3491. if (source) {
  3492. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3493. QTStr("NameExists.Text"));
  3494. obs_source_release(source);
  3495. continue;
  3496. }
  3497. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3498. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3499. source = obs_scene_get_source(scene);
  3500. SetCurrentScene(source, true);
  3501. auto undo = [](const std::string &data) {
  3502. OBSSourceAutoRelease source =
  3503. obs_get_source_by_name(data.c_str());
  3504. obs_source_remove(source);
  3505. };
  3506. auto redo = [this, name](const std::string &data) {
  3507. OBSSourceAutoRelease source =
  3508. obs_get_source_by_name(data.c_str());
  3509. obs_scene_t *scene = obs_scene_from_source(source);
  3510. scene = obs_scene_duplicate(scene, name.c_str(),
  3511. OBS_SCENE_DUP_REFS);
  3512. source = obs_scene_get_source(scene);
  3513. SetCurrentScene(source.Get(), true);
  3514. };
  3515. undo_s.add_action(
  3516. QTStr("Undo.Scene.Duplicate")
  3517. .arg(obs_source_get_name(source)),
  3518. undo, redo, obs_source_get_name(source),
  3519. obs_source_get_name(obs_scene_get_source(curScene)));
  3520. break;
  3521. }
  3522. }
  3523. static bool save_undo_source_enum(obs_scene_t * /* scene */,
  3524. obs_sceneitem_t *item, void *p)
  3525. {
  3526. obs_source_t *source = obs_sceneitem_get_source(item);
  3527. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3528. return true;
  3529. obs_data_array_t *array = (obs_data_array_t *)p;
  3530. /* check if the source is already stored in the array */
  3531. const char *name = obs_source_get_name(source);
  3532. const size_t count = obs_data_array_count(array);
  3533. for (size_t i = 0; i < count; i++) {
  3534. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3535. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3536. return true;
  3537. }
  3538. if (obs_source_is_group(source))
  3539. obs_scene_enum_items(obs_group_from_source(source),
  3540. save_undo_source_enum, p);
  3541. OBSDataAutoRelease source_data = obs_save_source(source);
  3542. obs_data_array_push_back(array, source_data);
  3543. return true;
  3544. }
  3545. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3546. {
  3547. obs_source_remove(source);
  3548. auto cb = [](void *, obs_source_t *source) {
  3549. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3550. obs_scene_prune_sources(obs_scene_from_source(source));
  3551. return true;
  3552. };
  3553. obs_enum_scenes(cb, NULL);
  3554. }
  3555. void OBSBasic::RemoveSelectedScene()
  3556. {
  3557. OBSScene scene = GetCurrentScene();
  3558. obs_source_t *source = obs_scene_get_source(scene);
  3559. if (!source || !QueryRemoveSource(source)) {
  3560. return;
  3561. }
  3562. /* ------------------------------ */
  3563. /* save all sources in scene */
  3564. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3565. obs_data_array_create();
  3566. obs_scene_enum_items(scene, save_undo_source_enum,
  3567. sources_in_deleted_scene);
  3568. OBSDataAutoRelease scene_data = obs_save_source(source);
  3569. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3570. /* ----------------------------------------------- */
  3571. /* save all scenes and groups the scene is used in */
  3572. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3573. obs_data_array_create();
  3574. struct other_scenes_cb_data {
  3575. obs_source_t *oldScene;
  3576. obs_data_array_t *scene_used_in_other_scenes;
  3577. } other_scenes_cb_data;
  3578. other_scenes_cb_data.oldScene = source;
  3579. other_scenes_cb_data.scene_used_in_other_scenes =
  3580. scene_used_in_other_scenes;
  3581. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3582. struct other_scenes_cb_data *data =
  3583. (struct other_scenes_cb_data *)data_ptr;
  3584. if (strcmp(obs_source_get_name(scene),
  3585. obs_source_get_name(data->oldScene)) == 0)
  3586. return true;
  3587. obs_sceneitem_t *item = obs_scene_find_source(
  3588. obs_group_or_scene_from_source(scene),
  3589. obs_source_get_name(data->oldScene));
  3590. if (item) {
  3591. OBSDataAutoRelease scene_data =
  3592. obs_save_source(obs_scene_get_source(
  3593. obs_sceneitem_get_scene(item)));
  3594. obs_data_array_push_back(
  3595. data->scene_used_in_other_scenes, scene_data);
  3596. }
  3597. return true;
  3598. };
  3599. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3600. /* --------------------------- */
  3601. /* undo/redo */
  3602. auto undo = [this](const std::string &json) {
  3603. OBSDataAutoRelease base =
  3604. obs_data_create_from_json(json.c_str());
  3605. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3606. obs_data_get_array(base, "sources_in_deleted_scene");
  3607. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3608. obs_data_get_array(base, "scene_used_in_other_scenes");
  3609. int savedIndex = (int)obs_data_get_int(base, "index");
  3610. std::vector<OBSSource> sources;
  3611. /* create missing sources */
  3612. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3613. sources.reserve(count);
  3614. for (size_t i = 0; i < count; i++) {
  3615. OBSDataAutoRelease data = obs_data_array_item(
  3616. sources_in_deleted_scene, i);
  3617. const char *name = obs_data_get_string(data, "name");
  3618. OBSSourceAutoRelease source =
  3619. obs_get_source_by_name(name);
  3620. if (!source) {
  3621. source = obs_load_source(data);
  3622. sources.push_back(source.Get());
  3623. }
  3624. }
  3625. /* actually load sources now */
  3626. for (obs_source_t *source : sources)
  3627. obs_source_load2(source);
  3628. /* Add scene to scenes and groups it was nested in */
  3629. for (size_t i = 0;
  3630. i < obs_data_array_count(scene_used_in_other_scenes);
  3631. i++) {
  3632. OBSDataAutoRelease data = obs_data_array_item(
  3633. scene_used_in_other_scenes, i);
  3634. const char *name = obs_data_get_string(data, "name");
  3635. OBSSourceAutoRelease source =
  3636. obs_get_source_by_name(name);
  3637. OBSDataAutoRelease settings =
  3638. obs_data_get_obj(data, "settings");
  3639. OBSDataArrayAutoRelease items =
  3640. obs_data_get_array(settings, "items");
  3641. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3642. std::vector<OBSSource> existing_sources;
  3643. auto cb = [](obs_scene_t *, obs_sceneitem_t *item,
  3644. void *data) {
  3645. std::vector<OBSSource> *existing =
  3646. (std::vector<OBSSource> *)data;
  3647. OBSSource source =
  3648. obs_sceneitem_get_source(item);
  3649. obs_sceneitem_remove(item);
  3650. existing->push_back(source);
  3651. return true;
  3652. };
  3653. obs_scene_enum_items(
  3654. obs_group_or_scene_from_source(source), cb,
  3655. (void *)&existing_sources);
  3656. /* Re-add sources to the scene */
  3657. obs_sceneitems_add(
  3658. obs_group_or_scene_from_source(source), items);
  3659. }
  3660. obs_source_t *scene_source = sources.back();
  3661. OBSScene scene = obs_scene_from_source(scene_source);
  3662. SetCurrentScene(scene, true);
  3663. /* set original index in list box */
  3664. ui->scenes->blockSignals(true);
  3665. int curIndex = ui->scenes->currentRow();
  3666. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3667. ui->scenes->insertItem(savedIndex, item);
  3668. ui->scenes->setCurrentRow(savedIndex);
  3669. currentScene = scene.Get();
  3670. ui->scenes->blockSignals(false);
  3671. };
  3672. auto redo = [](const std::string &name) {
  3673. OBSSourceAutoRelease source =
  3674. obs_get_source_by_name(name.c_str());
  3675. RemoveSceneAndReleaseNested(source);
  3676. };
  3677. OBSDataAutoRelease data = obs_data_create();
  3678. obs_data_set_array(data, "sources_in_deleted_scene",
  3679. sources_in_deleted_scene);
  3680. obs_data_set_array(data, "scene_used_in_other_scenes",
  3681. scene_used_in_other_scenes);
  3682. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3683. const char *scene_name = obs_source_get_name(source);
  3684. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3685. obs_data_get_json(data), scene_name);
  3686. /* --------------------------- */
  3687. /* remove */
  3688. RemoveSceneAndReleaseNested(source);
  3689. OnEvent(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3690. }
  3691. void OBSBasic::ReorderSources(OBSScene scene)
  3692. {
  3693. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3694. return;
  3695. ui->sources->ReorderItems();
  3696. SaveProject();
  3697. }
  3698. void OBSBasic::RefreshSources(OBSScene scene)
  3699. {
  3700. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3701. return;
  3702. ui->sources->RefreshItems();
  3703. SaveProject();
  3704. }
  3705. /* OBS Callbacks */
  3706. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3707. {
  3708. OBSBasic *window = static_cast<OBSBasic *>(data);
  3709. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3710. QMetaObject::invokeMethod(window, "ReorderSources",
  3711. Q_ARG(OBSScene, OBSScene(scene)));
  3712. }
  3713. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3714. {
  3715. OBSBasic *window = static_cast<OBSBasic *>(data);
  3716. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3717. QMetaObject::invokeMethod(window, "RefreshSources",
  3718. Q_ARG(OBSScene, OBSScene(scene)));
  3719. }
  3720. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3721. {
  3722. OBSBasic *window = static_cast<OBSBasic *>(data);
  3723. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3724. QMetaObject::invokeMethod(window, "AddSceneItem",
  3725. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3726. }
  3727. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3728. {
  3729. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3730. if (obs_scene_from_source(source) != NULL)
  3731. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3732. "AddScene", WaitConnection(),
  3733. Q_ARG(OBSSource, OBSSource(source)));
  3734. }
  3735. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3736. {
  3737. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3738. if (obs_scene_from_source(source) != NULL)
  3739. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3740. "RemoveScene",
  3741. Q_ARG(OBSSource, OBSSource(source)));
  3742. }
  3743. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3744. {
  3745. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3746. uint32_t flags = obs_source_get_output_flags(source);
  3747. if (flags & OBS_SOURCE_AUDIO)
  3748. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3749. "ActivateAudioSource",
  3750. Q_ARG(OBSSource, OBSSource(source)));
  3751. }
  3752. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3753. {
  3754. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3755. uint32_t flags = obs_source_get_output_flags(source);
  3756. if (flags & OBS_SOURCE_AUDIO)
  3757. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3758. "DeactivateAudioSource",
  3759. Q_ARG(OBSSource, OBSSource(source)));
  3760. }
  3761. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3762. {
  3763. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3764. if (obs_source_active(source))
  3765. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3766. "ActivateAudioSource",
  3767. Q_ARG(OBSSource, OBSSource(source)));
  3768. }
  3769. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3770. {
  3771. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3772. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3773. "DeactivateAudioSource",
  3774. Q_ARG(OBSSource, OBSSource(source)));
  3775. }
  3776. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3777. {
  3778. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3779. const char *newName = calldata_string(params, "new_name");
  3780. const char *prevName = calldata_string(params, "prev_name");
  3781. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3782. "RenameSources", Q_ARG(OBSSource, source),
  3783. Q_ARG(QString, QT_UTF8(newName)),
  3784. Q_ARG(QString, QT_UTF8(prevName)));
  3785. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3786. }
  3787. void OBSBasic::DrawBackdrop(float cx, float cy)
  3788. {
  3789. if (!box)
  3790. return;
  3791. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3792. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3793. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3794. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3795. vec4 colorVal;
  3796. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3797. gs_effect_set_vec4(color, &colorVal);
  3798. gs_technique_begin(tech);
  3799. gs_technique_begin_pass(tech, 0);
  3800. gs_matrix_push();
  3801. gs_matrix_identity();
  3802. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3803. gs_load_vertexbuffer(box);
  3804. gs_draw(GS_TRISTRIP, 0, 0);
  3805. gs_matrix_pop();
  3806. gs_technique_end_pass(tech);
  3807. gs_technique_end(tech);
  3808. gs_load_vertexbuffer(nullptr);
  3809. GS_DEBUG_MARKER_END();
  3810. }
  3811. void OBSBasic::RenderMain(void *data, uint32_t, uint32_t)
  3812. {
  3813. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3814. OBSBasic *window = static_cast<OBSBasic *>(data);
  3815. obs_video_info ovi;
  3816. obs_get_video_info(&ovi);
  3817. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3818. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3819. gs_viewport_push();
  3820. gs_projection_push();
  3821. obs_display_t *display = window->ui->preview->GetDisplay();
  3822. uint32_t width, height;
  3823. obs_display_size(display, &width, &height);
  3824. float right = float(width) - window->previewX;
  3825. float bottom = float(height) - window->previewY;
  3826. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3827. 100.0f);
  3828. window->ui->preview->DrawOverflow();
  3829. /* --------------------------------------- */
  3830. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3831. -100.0f, 100.0f);
  3832. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3833. window->previewCY);
  3834. if (window->IsPreviewProgramMode()) {
  3835. window->DrawBackdrop(float(ovi.base_width),
  3836. float(ovi.base_height));
  3837. OBSScene scene = window->GetCurrentScene();
  3838. obs_source_t *source = obs_scene_get_source(scene);
  3839. if (source)
  3840. obs_source_video_render(source);
  3841. } else {
  3842. obs_render_main_texture_src_color_only();
  3843. }
  3844. gs_load_vertexbuffer(nullptr);
  3845. /* --------------------------------------- */
  3846. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3847. 100.0f);
  3848. gs_reset_viewport();
  3849. uint32_t targetCX = window->previewCX;
  3850. uint32_t targetCY = window->previewCY;
  3851. if (window->drawSafeAreas) {
  3852. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3853. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3854. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3855. targetCY);
  3856. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3857. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3858. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3859. }
  3860. window->ui->preview->DrawSceneEditing();
  3861. if (window->drawSpacingHelpers)
  3862. window->ui->preview->DrawSpacingHelpers();
  3863. /* --------------------------------------- */
  3864. gs_projection_pop();
  3865. gs_viewport_pop();
  3866. GS_DEBUG_MARKER_END();
  3867. }
  3868. /* Main class functions */
  3869. obs_service_t *OBSBasic::GetService()
  3870. {
  3871. if (!service) {
  3872. service =
  3873. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3874. obs_service_release(service);
  3875. }
  3876. return service;
  3877. }
  3878. void OBSBasic::SetService(obs_service_t *newService)
  3879. {
  3880. if (newService) {
  3881. service = newService;
  3882. }
  3883. }
  3884. int OBSBasic::GetTransitionDuration()
  3885. {
  3886. return ui->transitionDuration->value();
  3887. }
  3888. bool OBSBasic::Active() const
  3889. {
  3890. if (!outputHandler)
  3891. return false;
  3892. return outputHandler->Active();
  3893. }
  3894. #ifdef _WIN32
  3895. #define IS_WIN32 1
  3896. #else
  3897. #define IS_WIN32 0
  3898. #endif
  3899. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3900. {
  3901. return obs_reset_video(ovi);
  3902. }
  3903. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3904. {
  3905. const char *scaleTypeStr =
  3906. config_get_string(basicConfig, "Video", "ScaleType");
  3907. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3908. return OBS_SCALE_BILINEAR;
  3909. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3910. return OBS_SCALE_LANCZOS;
  3911. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3912. return OBS_SCALE_AREA;
  3913. else
  3914. return OBS_SCALE_BICUBIC;
  3915. }
  3916. static inline enum video_format GetVideoFormatFromName(const char *name)
  3917. {
  3918. if (astrcmpi(name, "I420") == 0)
  3919. return VIDEO_FORMAT_I420;
  3920. else if (astrcmpi(name, "NV12") == 0)
  3921. return VIDEO_FORMAT_NV12;
  3922. else if (astrcmpi(name, "I444") == 0)
  3923. return VIDEO_FORMAT_I444;
  3924. else if (astrcmpi(name, "I010") == 0)
  3925. return VIDEO_FORMAT_I010;
  3926. else if (astrcmpi(name, "P010") == 0)
  3927. return VIDEO_FORMAT_P010;
  3928. else if (astrcmpi(name, "P216") == 0)
  3929. return VIDEO_FORMAT_P216;
  3930. else if (astrcmpi(name, "P416") == 0)
  3931. return VIDEO_FORMAT_P416;
  3932. #if 0 //currently unsupported
  3933. else if (astrcmpi(name, "YVYU") == 0)
  3934. return VIDEO_FORMAT_YVYU;
  3935. else if (astrcmpi(name, "YUY2") == 0)
  3936. return VIDEO_FORMAT_YUY2;
  3937. else if (astrcmpi(name, "UYVY") == 0)
  3938. return VIDEO_FORMAT_UYVY;
  3939. #endif
  3940. else
  3941. return VIDEO_FORMAT_BGRA;
  3942. }
  3943. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3944. {
  3945. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3946. if (strcmp(name, "601") == 0)
  3947. colorspace = VIDEO_CS_601;
  3948. else if (strcmp(name, "709") == 0)
  3949. colorspace = VIDEO_CS_709;
  3950. else if (strcmp(name, "2100PQ") == 0)
  3951. colorspace = VIDEO_CS_2100_PQ;
  3952. else if (strcmp(name, "2100HLG") == 0)
  3953. colorspace = VIDEO_CS_2100_HLG;
  3954. return colorspace;
  3955. }
  3956. void OBSBasic::ResetUI()
  3957. {
  3958. bool studioPortraitLayout = config_get_bool(
  3959. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3960. if (studioPortraitLayout)
  3961. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3962. else
  3963. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3964. UpdatePreviewProgramIndicators();
  3965. }
  3966. int OBSBasic::ResetVideo()
  3967. {
  3968. if (outputHandler && outputHandler->Active())
  3969. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3970. ProfileScope("OBSBasic::ResetVideo");
  3971. struct obs_video_info ovi;
  3972. int ret;
  3973. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3974. const char *colorFormat =
  3975. config_get_string(basicConfig, "Video", "ColorFormat");
  3976. const char *colorSpace =
  3977. config_get_string(basicConfig, "Video", "ColorSpace");
  3978. const char *colorRange =
  3979. config_get_string(basicConfig, "Video", "ColorRange");
  3980. ovi.graphics_module = App()->GetRenderModule();
  3981. ovi.base_width =
  3982. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3983. ovi.base_height =
  3984. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3985. ovi.output_width =
  3986. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3987. ovi.output_height =
  3988. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3989. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3990. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3991. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3992. : VIDEO_RANGE_PARTIAL;
  3993. ovi.adapter =
  3994. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3995. ovi.gpu_conversion = true;
  3996. ovi.scale_type = GetScaleType(basicConfig);
  3997. if (ovi.base_width < 32 || ovi.base_height < 32) {
  3998. ovi.base_width = 1920;
  3999. ovi.base_height = 1080;
  4000. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  4001. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  4002. }
  4003. if (ovi.output_width < 32 || ovi.output_height < 32) {
  4004. ovi.output_width = ovi.base_width;
  4005. ovi.output_height = ovi.base_height;
  4006. config_set_uint(basicConfig, "Video", "OutputCX",
  4007. ovi.base_width);
  4008. config_set_uint(basicConfig, "Video", "OutputCY",
  4009. ovi.base_height);
  4010. }
  4011. ret = AttemptToResetVideo(&ovi);
  4012. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  4013. blog(LOG_WARNING, "Tried to reset when already active");
  4014. return ret;
  4015. }
  4016. if (ret == OBS_VIDEO_SUCCESS) {
  4017. ResizePreview(ovi.base_width, ovi.base_height);
  4018. if (program)
  4019. ResizeProgram(ovi.base_width, ovi.base_height);
  4020. const float sdr_white_level = (float)config_get_uint(
  4021. basicConfig, "Video", "SdrWhiteLevel");
  4022. const float hdr_nominal_peak_level = (float)config_get_uint(
  4023. basicConfig, "Video", "HdrNominalPeakLevel");
  4024. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  4025. OBSBasicStats::InitializeValues();
  4026. OBSProjector::UpdateMultiviewProjectors();
  4027. }
  4028. return ret;
  4029. }
  4030. bool OBSBasic::ResetAudio()
  4031. {
  4032. ProfileScope("OBSBasic::ResetAudio");
  4033. struct obs_audio_info2 ai = {};
  4034. ai.samples_per_sec =
  4035. config_get_uint(basicConfig, "Audio", "SampleRate");
  4036. const char *channelSetupStr =
  4037. config_get_string(basicConfig, "Audio", "ChannelSetup");
  4038. if (strcmp(channelSetupStr, "Mono") == 0)
  4039. ai.speakers = SPEAKERS_MONO;
  4040. else if (strcmp(channelSetupStr, "2.1") == 0)
  4041. ai.speakers = SPEAKERS_2POINT1;
  4042. else if (strcmp(channelSetupStr, "4.0") == 0)
  4043. ai.speakers = SPEAKERS_4POINT0;
  4044. else if (strcmp(channelSetupStr, "4.1") == 0)
  4045. ai.speakers = SPEAKERS_4POINT1;
  4046. else if (strcmp(channelSetupStr, "5.1") == 0)
  4047. ai.speakers = SPEAKERS_5POINT1;
  4048. else if (strcmp(channelSetupStr, "7.1") == 0)
  4049. ai.speakers = SPEAKERS_7POINT1;
  4050. else
  4051. ai.speakers = SPEAKERS_STEREO;
  4052. bool lowLatencyAudioBuffering = config_get_bool(
  4053. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  4054. if (lowLatencyAudioBuffering) {
  4055. ai.max_buffering_ms = 20;
  4056. ai.fixed_buffering = true;
  4057. }
  4058. return obs_reset_audio2(&ai);
  4059. }
  4060. extern char *get_new_source_name(const char *name, const char *format);
  4061. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  4062. const char *deviceDesc, int channel)
  4063. {
  4064. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  4065. OBSSourceAutoRelease source;
  4066. OBSDataAutoRelease settings;
  4067. source = obs_get_output_source(channel);
  4068. if (source) {
  4069. if (disable) {
  4070. obs_set_output_source(channel, nullptr);
  4071. } else {
  4072. settings = obs_source_get_settings(source);
  4073. const char *oldId =
  4074. obs_data_get_string(settings, "device_id");
  4075. if (strcmp(oldId, deviceId) != 0) {
  4076. obs_data_set_string(settings, "device_id",
  4077. deviceId);
  4078. obs_source_update(source, settings);
  4079. }
  4080. }
  4081. } else if (!disable) {
  4082. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  4083. settings = obs_data_create();
  4084. obs_data_set_string(settings, "device_id", deviceId);
  4085. source = obs_source_create(sourceId, name, settings, nullptr);
  4086. obs_set_output_source(channel, source);
  4087. }
  4088. }
  4089. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  4090. {
  4091. QSize targetSize;
  4092. bool isFixedScaling;
  4093. obs_video_info ovi;
  4094. /* resize preview panel to fix to the top section of the window */
  4095. targetSize = GetPixelSize(ui->preview);
  4096. isFixedScaling = ui->preview->IsFixedScaling();
  4097. obs_get_video_info(&ovi);
  4098. if (isFixedScaling) {
  4099. ui->preview->ClampScrollingOffsets();
  4100. previewScale = ui->preview->GetScalingAmount();
  4101. GetCenterPosFromFixedScale(
  4102. int(cx), int(cy),
  4103. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4104. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  4105. previewY, previewScale);
  4106. previewX += ui->preview->GetScrollX();
  4107. previewY += ui->preview->GetScrollY();
  4108. } else {
  4109. GetScaleAndCenterPos(int(cx), int(cy),
  4110. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4111. targetSize.height() -
  4112. PREVIEW_EDGE_SIZE * 2,
  4113. previewX, previewY, previewScale);
  4114. }
  4115. previewX += float(PREVIEW_EDGE_SIZE);
  4116. previewY += float(PREVIEW_EDGE_SIZE);
  4117. }
  4118. void OBSBasic::CloseDialogs()
  4119. {
  4120. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  4121. if (!childDialogs.isEmpty()) {
  4122. for (int i = 0; i < childDialogs.size(); ++i) {
  4123. childDialogs.at(i)->close();
  4124. }
  4125. }
  4126. if (!stats.isNull())
  4127. stats->close(); //call close to save Stats geometry
  4128. if (!remux.isNull())
  4129. remux->close();
  4130. }
  4131. void OBSBasic::EnumDialogs()
  4132. {
  4133. visDialogs.clear();
  4134. modalDialogs.clear();
  4135. visMsgBoxes.clear();
  4136. /* fill list of Visible dialogs and Modal dialogs */
  4137. QList<QDialog *> dialogs = findChildren<QDialog *>();
  4138. for (QDialog *dialog : dialogs) {
  4139. if (dialog->isVisible())
  4140. visDialogs.append(dialog);
  4141. if (dialog->isModal())
  4142. modalDialogs.append(dialog);
  4143. }
  4144. /* fill list of Visible message boxes */
  4145. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  4146. for (QMessageBox *msgbox : msgBoxes) {
  4147. if (msgbox->isVisible())
  4148. visMsgBoxes.append(msgbox);
  4149. }
  4150. }
  4151. void OBSBasic::ClearProjectors()
  4152. {
  4153. for (size_t i = 0; i < projectors.size(); i++) {
  4154. if (projectors[i])
  4155. delete projectors[i];
  4156. }
  4157. projectors.clear();
  4158. }
  4159. void OBSBasic::ClearSceneData()
  4160. {
  4161. disableSaving++;
  4162. setCursor(Qt::WaitCursor);
  4163. CloseDialogs();
  4164. ClearVolumeControls();
  4165. ClearListItems(ui->scenes);
  4166. ui->sources->Clear();
  4167. ClearQuickTransitions();
  4168. ui->transitions->clear();
  4169. ClearProjectors();
  4170. for (int i = 0; i < MAX_CHANNELS; i++)
  4171. obs_set_output_source(i, nullptr);
  4172. /* Reset VCam to default to clear its private scene and any references
  4173. * it holds. It will be reconfigured during loading. */
  4174. if (vcamEnabled) {
  4175. vcamConfig.type = VCamOutputType::ProgramView;
  4176. outputHandler->UpdateVirtualCamOutputSource();
  4177. }
  4178. collectionModuleData = nullptr;
  4179. lastScene = nullptr;
  4180. swapScene = nullptr;
  4181. programScene = nullptr;
  4182. prevFTBSource = nullptr;
  4183. clipboard.clear();
  4184. copyFiltersSource = nullptr;
  4185. copyFilter = nullptr;
  4186. auto cb = [](void *, obs_source_t *source) {
  4187. obs_source_remove(source);
  4188. return true;
  4189. };
  4190. obs_enum_scenes(cb, nullptr);
  4191. obs_enum_sources(cb, nullptr);
  4192. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  4193. undo_s.clear();
  4194. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  4195. * that deleteLater events are processed at this point */
  4196. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  4197. do {
  4198. QApplication::sendPostedEvents(nullptr);
  4199. } while (obs_wait_for_destroy_queue());
  4200. /* Pump Qt events one final time to give remaining signals time to be
  4201. * processed (since this happens after the destroy thread finishes and
  4202. * the audio/video threads have processed their tasks). */
  4203. QApplication::sendPostedEvents(nullptr);
  4204. unsetCursor();
  4205. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  4206. * reference, they will still be in the hash table, enumerate them and
  4207. * store the names for logging purposes. */
  4208. auto cb2 = [](void *param, obs_source_t *source) {
  4209. auto orphans = static_cast<vector<string> *>(param);
  4210. orphans->push_back(obs_source_get_name(source));
  4211. return true;
  4212. };
  4213. vector<string> orphan_sources;
  4214. obs_enum_sources(cb2, &orphan_sources);
  4215. if (!orphan_sources.empty()) {
  4216. /* Avoid logging list twice in case it gets called after
  4217. * setting the flag the first time. */
  4218. if (!clearingFailed) {
  4219. /* This ugly mess exists to join a vector of strings
  4220. * with a user-defined delimiter. */
  4221. string orphan_names = std::accumulate(
  4222. orphan_sources.begin(), orphan_sources.end(),
  4223. string(""), [](string a, string b) {
  4224. return std::move(a) + "\n- " + b;
  4225. });
  4226. blog(LOG_ERROR,
  4227. "Not all sources were cleared when clearing scene data:\n%s\n",
  4228. orphan_names.c_str());
  4229. }
  4230. /* We do not decrement disableSaving here to avoid OBS
  4231. * overwriting user data with garbage. */
  4232. clearingFailed = true;
  4233. } else {
  4234. disableSaving--;
  4235. blog(LOG_INFO, "All scene data cleared");
  4236. blog(LOG_INFO,
  4237. "------------------------------------------------");
  4238. }
  4239. }
  4240. void OBSBasic::closeEvent(QCloseEvent *event)
  4241. {
  4242. /* Wait for multitrack video stream to start/finish processing in the background */
  4243. if (setupStreamingGuard.valid() &&
  4244. setupStreamingGuard.wait_for(std::chrono::seconds{0}) !=
  4245. std::future_status::ready) {
  4246. QTimer::singleShot(1000, this, &OBSBasic::close);
  4247. event->ignore();
  4248. return;
  4249. }
  4250. /* Do not close window if inside of a temporary event loop because we
  4251. * could be inside of an Auth::LoadUI call. Keep trying once per
  4252. * second until we've exit any known sub-loops. */
  4253. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4254. QTimer::singleShot(1000, this, &OBSBasic::close);
  4255. event->ignore();
  4256. return;
  4257. }
  4258. #ifdef YOUTUBE_ENABLED
  4259. /* Also don't close the window if the youtube stream check is active */
  4260. if (youtubeStreamCheckThread) {
  4261. QTimer::singleShot(1000, this, &OBSBasic::close);
  4262. event->ignore();
  4263. return;
  4264. }
  4265. #endif
  4266. if (isVisible())
  4267. config_set_string(App()->GlobalConfig(), "BasicWindow",
  4268. "geometry",
  4269. saveGeometry().toBase64().constData());
  4270. bool confirmOnExit =
  4271. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  4272. if (confirmOnExit && outputHandler && outputHandler->Active() &&
  4273. !clearingFailed) {
  4274. SetShowing(true);
  4275. QMessageBox::StandardButton button = OBSMessageBox::question(
  4276. this, QTStr("ConfirmExit.Title"),
  4277. QTStr("ConfirmExit.Text"));
  4278. if (button == QMessageBox::No) {
  4279. event->ignore();
  4280. restart = false;
  4281. return;
  4282. }
  4283. }
  4284. if (remux && !remux->close()) {
  4285. event->ignore();
  4286. restart = false;
  4287. return;
  4288. }
  4289. QWidget::closeEvent(event);
  4290. if (!event->isAccepted())
  4291. return;
  4292. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  4293. closing = true;
  4294. /* While closing, a resize event to OBSQTDisplay could be triggered.
  4295. * The graphics thread on macOS dispatches a lambda function to be
  4296. * executed asynchronously in the main thread. However, the display is
  4297. * sometimes deleted before the lambda function is actually executed.
  4298. * To avoid such a case, destroy displays earlier than others such as
  4299. * deleting browser docks. */
  4300. ui->preview->DestroyDisplay();
  4301. if (program)
  4302. program->DestroyDisplay();
  4303. if (outputHandler->VirtualCamActive())
  4304. outputHandler->StopVirtualCam();
  4305. if (introCheckThread)
  4306. introCheckThread->wait();
  4307. if (whatsNewInitThread)
  4308. whatsNewInitThread->wait();
  4309. if (updateCheckThread)
  4310. updateCheckThread->wait();
  4311. if (logUploadThread)
  4312. logUploadThread->wait();
  4313. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  4314. devicePropertiesThread->wait();
  4315. devicePropertiesThread.reset();
  4316. }
  4317. QApplication::sendPostedEvents(nullptr);
  4318. signalHandlers.clear();
  4319. Auth::Save();
  4320. SaveProjectNow();
  4321. auth.reset();
  4322. delete extraBrowsers;
  4323. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  4324. saveState().toBase64().constData());
  4325. #ifdef BROWSER_AVAILABLE
  4326. if (cef)
  4327. SaveExtraBrowserDocks();
  4328. ClearExtraBrowserDocks();
  4329. #endif
  4330. OnEvent(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  4331. disableSaving++;
  4332. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  4333. * sources, etc) so that all references are released before shutdown */
  4334. ClearSceneData();
  4335. OnEvent(OBS_FRONTEND_EVENT_EXIT);
  4336. // Destroys the frontend API so plugins can't continue calling it
  4337. obs_frontend_set_callbacks_internal(nullptr);
  4338. api = nullptr;
  4339. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  4340. }
  4341. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  4342. {
  4343. #ifdef _WIN32
  4344. const MSG &msg = *static_cast<MSG *>(message);
  4345. switch (msg.message) {
  4346. case WM_MOVE:
  4347. for (OBSQTDisplay *const display :
  4348. findChildren<OBSQTDisplay *>()) {
  4349. display->OnMove();
  4350. }
  4351. break;
  4352. case WM_DISPLAYCHANGE:
  4353. for (OBSQTDisplay *const display :
  4354. findChildren<OBSQTDisplay *>()) {
  4355. display->OnDisplayChange();
  4356. }
  4357. }
  4358. #else
  4359. UNUSED_PARAMETER(message);
  4360. #endif
  4361. return false;
  4362. }
  4363. void OBSBasic::changeEvent(QEvent *event)
  4364. {
  4365. if (event->type() == QEvent::WindowStateChange) {
  4366. QWindowStateChangeEvent *stateEvent =
  4367. (QWindowStateChangeEvent *)event;
  4368. if (isMinimized()) {
  4369. if (trayIcon && trayIcon->isVisible() &&
  4370. sysTrayMinimizeToTray()) {
  4371. ToggleShowHide();
  4372. return;
  4373. }
  4374. if (previewEnabled)
  4375. EnablePreviewDisplay(false);
  4376. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  4377. isVisible()) {
  4378. if (previewEnabled)
  4379. EnablePreviewDisplay(true);
  4380. }
  4381. }
  4382. }
  4383. void OBSBasic::on_actionShow_Recordings_triggered()
  4384. {
  4385. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4386. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  4387. const char *adv_path =
  4388. strcmp(type, "Standard")
  4389. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  4390. : config_get_string(basicConfig, "AdvOut",
  4391. "RecFilePath");
  4392. const char *path = strcmp(mode, "Advanced")
  4393. ? config_get_string(basicConfig,
  4394. "SimpleOutput",
  4395. "FilePath")
  4396. : adv_path;
  4397. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4398. }
  4399. void OBSBasic::on_actionRemux_triggered()
  4400. {
  4401. if (!remux.isNull()) {
  4402. remux->show();
  4403. remux->raise();
  4404. return;
  4405. }
  4406. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4407. const char *path = strcmp(mode, "Advanced")
  4408. ? config_get_string(basicConfig,
  4409. "SimpleOutput",
  4410. "FilePath")
  4411. : config_get_string(basicConfig, "AdvOut",
  4412. "RecFilePath");
  4413. OBSRemux *remuxDlg;
  4414. remuxDlg = new OBSRemux(path, this);
  4415. remuxDlg->show();
  4416. remux = remuxDlg;
  4417. }
  4418. void OBSBasic::on_action_Settings_triggered()
  4419. {
  4420. static bool settings_already_executing = false;
  4421. /* Do not load settings window if inside of a temporary event loop
  4422. * because we could be inside of an Auth::LoadUI call. Keep trying
  4423. * once per second until we've exit any known sub-loops. */
  4424. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4425. QTimer::singleShot(1000, this,
  4426. &OBSBasic::on_action_Settings_triggered);
  4427. return;
  4428. }
  4429. if (settings_already_executing) {
  4430. return;
  4431. }
  4432. settings_already_executing = true;
  4433. {
  4434. OBSBasicSettings settings(this);
  4435. settings.exec();
  4436. }
  4437. settings_already_executing = false;
  4438. if (restart) {
  4439. QMessageBox::StandardButton button = OBSMessageBox::question(
  4440. this, QTStr("Restart"), QTStr("NeedsRestart"));
  4441. if (button == QMessageBox::Yes)
  4442. close();
  4443. else
  4444. restart = false;
  4445. }
  4446. }
  4447. void OBSBasic::on_actionShowMacPermissions_triggered()
  4448. {
  4449. #ifdef __APPLE__
  4450. OBSPermissions check(this, CheckPermission(kScreenCapture),
  4451. CheckPermission(kVideoDeviceAccess),
  4452. CheckPermission(kAudioDeviceAccess),
  4453. CheckPermission(kAccessibility));
  4454. check.exec();
  4455. #endif
  4456. }
  4457. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4458. {
  4459. if (obs_missing_files_count(files) > 0) {
  4460. /* When loading the missing files dialog on launch, the
  4461. * window hasn't fully initialized by this point on macOS,
  4462. * so put this at the end of the current task queue. Fixes
  4463. * a bug where the window is behind OBS on startup. */
  4464. QTimer::singleShot(0, [this, files] {
  4465. missDialog = new OBSMissingFiles(files, this);
  4466. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4467. missDialog->show();
  4468. missDialog->raise();
  4469. });
  4470. } else {
  4471. obs_missing_files_destroy(files);
  4472. /* Only raise dialog if triggered manually */
  4473. if (!disableSaving)
  4474. OBSMessageBox::information(
  4475. this, QTStr("MissingFiles.NoMissing.Title"),
  4476. QTStr("MissingFiles.NoMissing.Text"));
  4477. }
  4478. }
  4479. void OBSBasic::on_actionShowMissingFiles_triggered()
  4480. {
  4481. obs_missing_files_t *files = obs_missing_files_create();
  4482. auto cb_sources = [](void *data, obs_source_t *source) {
  4483. AddMissingFiles(data, source);
  4484. return true;
  4485. };
  4486. obs_enum_all_sources(cb_sources, files);
  4487. ShowMissingFilesDialog(files);
  4488. }
  4489. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4490. {
  4491. if (advAudioWindow != nullptr) {
  4492. advAudioWindow->raise();
  4493. return;
  4494. }
  4495. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4496. "BasicWindow", "ShowSourceIcons");
  4497. advAudioWindow = new OBSBasicAdvAudio(this);
  4498. advAudioWindow->show();
  4499. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4500. advAudioWindow->SetIconsVisible(iconsVisible);
  4501. }
  4502. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4503. {
  4504. on_actionAdvAudioProperties_triggered();
  4505. }
  4506. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4507. {
  4508. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4509. connect(&unhideAllAction, &QAction::triggered, this,
  4510. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4511. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4512. toggleControlLayoutAction.setCheckable(true);
  4513. toggleControlLayoutAction.setChecked(config_get_bool(
  4514. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4515. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4516. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4517. QMenu popup;
  4518. popup.addAction(&unhideAllAction);
  4519. popup.addSeparator();
  4520. popup.addAction(&toggleControlLayoutAction);
  4521. popup.exec(QCursor::pos());
  4522. }
  4523. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4524. QListWidgetItem *)
  4525. {
  4526. OBSSource source;
  4527. if (current) {
  4528. OBSScene scene = GetOBSRef<OBSScene>(current);
  4529. source = obs_scene_get_source(scene);
  4530. currentScene = scene;
  4531. } else {
  4532. currentScene = NULL;
  4533. }
  4534. SetCurrentScene(source);
  4535. if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput)
  4536. outputHandler->UpdateVirtualCamOutputSource();
  4537. OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4538. UpdateContextBar();
  4539. }
  4540. void OBSBasic::EditSceneName()
  4541. {
  4542. ui->scenesDock->removeAction(renameScene);
  4543. QListWidgetItem *item = ui->scenes->currentItem();
  4544. Qt::ItemFlags flags = item->flags();
  4545. item->setFlags(flags | Qt::ItemIsEditable);
  4546. ui->scenes->editItem(item);
  4547. item->setFlags(flags);
  4548. }
  4549. QList<QString> OBSBasic::GetProjectorMenuMonitorsFormatted()
  4550. {
  4551. QList<QString> projectorsFormatted;
  4552. QList<QScreen *> screens = QGuiApplication::screens();
  4553. for (int i = 0; i < screens.size(); i++) {
  4554. QScreen *screen = screens[i];
  4555. QRect screenGeometry = screen->geometry();
  4556. qreal ratio = screen->devicePixelRatio();
  4557. QString name = "";
  4558. #if defined(_WIN32) && QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
  4559. QTextStream fullname(&name);
  4560. fullname << GetMonitorName(screen->name());
  4561. fullname << " (";
  4562. fullname << (i + 1);
  4563. fullname << ")";
  4564. #elif defined(__APPLE__) || defined(_WIN32)
  4565. name = screen->name();
  4566. #else
  4567. name = screen->model().simplified();
  4568. if (name.length() > 1 && name.endsWith("-"))
  4569. name.chop(1);
  4570. #endif
  4571. name = name.simplified();
  4572. if (name.length() == 0) {
  4573. name = QString("%1 %2")
  4574. .arg(QTStr("Display"))
  4575. .arg(QString::number(i + 1));
  4576. }
  4577. QString str =
  4578. QString("%1: %2x%3 @ %4,%5")
  4579. .arg(name,
  4580. QString::number(screenGeometry.width() *
  4581. ratio),
  4582. QString::number(screenGeometry.height() *
  4583. ratio),
  4584. QString::number(screenGeometry.x()),
  4585. QString::number(screenGeometry.y()));
  4586. projectorsFormatted.push_back(str);
  4587. }
  4588. return projectorsFormatted;
  4589. }
  4590. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4591. {
  4592. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4593. QMenu popup(this);
  4594. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4595. popup.addAction(QTStr("Add"), this,
  4596. &OBSBasic::on_actionAddScene_triggered);
  4597. if (item) {
  4598. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4599. copyFilters->setEnabled(false);
  4600. connect(copyFilters, &QAction::triggered, this,
  4601. &OBSBasic::SceneCopyFilters);
  4602. QAction *pasteFilters =
  4603. new QAction(QTStr("Paste.Filters"), this);
  4604. pasteFilters->setEnabled(
  4605. !obs_weak_source_expired(copyFiltersSource));
  4606. connect(pasteFilters, &QAction::triggered, this,
  4607. &OBSBasic::ScenePasteFilters);
  4608. popup.addSeparator();
  4609. popup.addAction(QTStr("Duplicate"), this,
  4610. &OBSBasic::DuplicateSelectedScene);
  4611. popup.addAction(copyFilters);
  4612. popup.addAction(pasteFilters);
  4613. popup.addSeparator();
  4614. popup.addAction(renameScene);
  4615. popup.addAction(ui->actionRemoveScene);
  4616. popup.addSeparator();
  4617. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4618. &OBSBasic::on_actionSceneUp_triggered);
  4619. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4620. this, &OBSBasic::on_actionSceneDown_triggered);
  4621. order.addSeparator();
  4622. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4623. this, &OBSBasic::MoveSceneToTop);
  4624. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4625. this, &OBSBasic::MoveSceneToBottom);
  4626. popup.addMenu(&order);
  4627. popup.addSeparator();
  4628. delete sceneProjectorMenu;
  4629. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4630. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4631. &OBSBasic::OpenSceneProjector);
  4632. popup.addMenu(sceneProjectorMenu);
  4633. QAction *sceneWindow = popup.addAction(
  4634. QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow);
  4635. popup.addAction(sceneWindow);
  4636. popup.addAction(QTStr("Screenshot.Scene"), this,
  4637. &OBSBasic::ScreenshotScene);
  4638. popup.addSeparator();
  4639. popup.addAction(QTStr("Filters"), this,
  4640. &OBSBasic::OpenSceneFilters);
  4641. popup.addSeparator();
  4642. delete perSceneTransitionMenu;
  4643. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4644. popup.addMenu(perSceneTransitionMenu);
  4645. /* ---------------------- */
  4646. QAction *multiviewAction =
  4647. popup.addAction(QTStr("ShowInMultiview"));
  4648. OBSSource source = GetCurrentSceneSource();
  4649. OBSDataAutoRelease data =
  4650. obs_source_get_private_settings(source);
  4651. obs_data_set_default_bool(data, "show_in_multiview", true);
  4652. bool show = obs_data_get_bool(data, "show_in_multiview");
  4653. multiviewAction->setCheckable(true);
  4654. multiviewAction->setChecked(show);
  4655. auto showInMultiview = [](OBSData data) {
  4656. bool show =
  4657. obs_data_get_bool(data, "show_in_multiview");
  4658. obs_data_set_bool(data, "show_in_multiview", !show);
  4659. OBSProjector::UpdateMultiviewProjectors();
  4660. };
  4661. connect(multiviewAction, &QAction::triggered,
  4662. std::bind(showInMultiview, data.Get()));
  4663. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4664. }
  4665. popup.addSeparator();
  4666. bool grid = ui->scenes->GetGridMode();
  4667. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4668. : QTStr("Basic.Main.GridMode"),
  4669. this);
  4670. connect(gridAction, &QAction::triggered, this,
  4671. &OBSBasic::GridActionClicked);
  4672. popup.addAction(gridAction);
  4673. popup.exec(QCursor::pos());
  4674. }
  4675. void OBSBasic::on_actionSceneListMode_triggered()
  4676. {
  4677. ui->scenes->SetGridMode(false);
  4678. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4679. false);
  4680. }
  4681. void OBSBasic::on_actionSceneGridMode_triggered()
  4682. {
  4683. ui->scenes->SetGridMode(true);
  4684. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode", true);
  4685. }
  4686. void OBSBasic::GridActionClicked()
  4687. {
  4688. bool gridMode = !ui->scenes->GetGridMode();
  4689. ui->scenes->SetGridMode(gridMode);
  4690. if (gridMode)
  4691. ui->actionSceneGridMode->setChecked(true);
  4692. else
  4693. ui->actionSceneListMode->setChecked(true);
  4694. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4695. gridMode);
  4696. }
  4697. void OBSBasic::on_actionAddScene_triggered()
  4698. {
  4699. string name;
  4700. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4701. int i = 2;
  4702. QString placeHolderText = format.arg(i);
  4703. OBSSourceAutoRelease source = nullptr;
  4704. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4705. placeHolderText = format.arg(++i);
  4706. }
  4707. bool accepted = NameDialog::AskForName(
  4708. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4709. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4710. if (accepted) {
  4711. if (name.empty()) {
  4712. OBSMessageBox::warning(this,
  4713. QTStr("NoNameEntered.Title"),
  4714. QTStr("NoNameEntered.Text"));
  4715. on_actionAddScene_triggered();
  4716. return;
  4717. }
  4718. OBSSourceAutoRelease source =
  4719. obs_get_source_by_name(name.c_str());
  4720. if (source) {
  4721. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4722. QTStr("NameExists.Text"));
  4723. on_actionAddScene_triggered();
  4724. return;
  4725. }
  4726. auto undo_fn = [](const std::string &data) {
  4727. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4728. if (t) {
  4729. obs_source_remove(t);
  4730. obs_source_release(t);
  4731. }
  4732. };
  4733. auto redo_fn = [this](const std::string &data) {
  4734. OBSSceneAutoRelease scene =
  4735. obs_scene_create(data.c_str());
  4736. obs_source_t *source = obs_scene_get_source(scene);
  4737. SetCurrentScene(source, true);
  4738. };
  4739. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4740. undo_fn, redo_fn, name, name);
  4741. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4742. obs_source_t *scene_source = obs_scene_get_source(scene);
  4743. SetCurrentScene(scene_source);
  4744. }
  4745. }
  4746. void OBSBasic::on_actionRemoveScene_triggered()
  4747. {
  4748. RemoveSelectedScene();
  4749. }
  4750. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4751. {
  4752. int idx = ui->scenes->currentRow();
  4753. if (idx == -1 || idx == invalidIdx)
  4754. return;
  4755. ui->scenes->blockSignals(true);
  4756. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4757. if (!relative)
  4758. idx = 0;
  4759. ui->scenes->insertItem(idx + offset, item);
  4760. ui->scenes->setCurrentRow(idx + offset);
  4761. item->setSelected(true);
  4762. currentScene = GetOBSRef<OBSScene>(item).Get();
  4763. ui->scenes->blockSignals(false);
  4764. OBSProjector::UpdateMultiviewProjectors();
  4765. }
  4766. void OBSBasic::on_actionSceneUp_triggered()
  4767. {
  4768. ChangeSceneIndex(true, -1, 0);
  4769. }
  4770. void OBSBasic::on_actionSceneDown_triggered()
  4771. {
  4772. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4773. }
  4774. void OBSBasic::MoveSceneToTop()
  4775. {
  4776. ChangeSceneIndex(false, 0, 0);
  4777. }
  4778. void OBSBasic::MoveSceneToBottom()
  4779. {
  4780. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4781. ui->scenes->count() - 1);
  4782. }
  4783. void OBSBasic::EditSceneItemName()
  4784. {
  4785. int idx = GetTopSelectedSourceItem();
  4786. ui->sources->Edit(idx);
  4787. }
  4788. void OBSBasic::SetDeinterlacingMode()
  4789. {
  4790. QAction *action = reinterpret_cast<QAction *>(sender());
  4791. obs_deinterlace_mode mode =
  4792. (obs_deinterlace_mode)action->property("mode").toInt();
  4793. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4794. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4795. obs_source_set_deinterlace_mode(source, mode);
  4796. }
  4797. void OBSBasic::SetDeinterlacingOrder()
  4798. {
  4799. QAction *action = reinterpret_cast<QAction *>(sender());
  4800. obs_deinterlace_field_order order =
  4801. (obs_deinterlace_field_order)action->property("order").toInt();
  4802. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4803. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4804. obs_source_set_deinterlace_field_order(source, order);
  4805. }
  4806. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4807. {
  4808. obs_deinterlace_mode deinterlaceMode =
  4809. obs_source_get_deinterlace_mode(source);
  4810. obs_deinterlace_field_order deinterlaceOrder =
  4811. obs_source_get_deinterlace_field_order(source);
  4812. QAction *action;
  4813. #define ADD_MODE(name, mode) \
  4814. action = menu->addAction(QTStr("" name), this, \
  4815. &OBSBasic::SetDeinterlacingMode); \
  4816. action->setProperty("mode", (int)mode); \
  4817. action->setCheckable(true); \
  4818. action->setChecked(deinterlaceMode == mode);
  4819. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4820. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4821. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4822. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4823. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4824. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4825. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4826. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4827. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4828. #undef ADD_MODE
  4829. menu->addSeparator();
  4830. #define ADD_ORDER(name, order) \
  4831. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4832. &OBSBasic::SetDeinterlacingOrder); \
  4833. action->setProperty("order", (int)order); \
  4834. action->setCheckable(true); \
  4835. action->setChecked(deinterlaceOrder == order);
  4836. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4837. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4838. #undef ADD_ORDER
  4839. return menu;
  4840. }
  4841. void OBSBasic::SetScaleFilter()
  4842. {
  4843. QAction *action = reinterpret_cast<QAction *>(sender());
  4844. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4845. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4846. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4847. }
  4848. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4849. {
  4850. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4851. QAction *action;
  4852. #define ADD_MODE(name, mode) \
  4853. action = menu->addAction(QTStr("" name), this, \
  4854. &OBSBasic::SetScaleFilter); \
  4855. action->setProperty("mode", (int)mode); \
  4856. action->setCheckable(true); \
  4857. action->setChecked(scaleFilter == mode);
  4858. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4859. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4860. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4861. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4862. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4863. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4864. #undef ADD_MODE
  4865. return menu;
  4866. }
  4867. void OBSBasic::SetBlendingMethod()
  4868. {
  4869. QAction *action = reinterpret_cast<QAction *>(sender());
  4870. obs_blending_method method =
  4871. (obs_blending_method)action->property("method").toInt();
  4872. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4873. obs_sceneitem_set_blending_method(sceneItem, method);
  4874. }
  4875. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4876. {
  4877. obs_blending_method blendingMethod =
  4878. obs_sceneitem_get_blending_method(item);
  4879. QAction *action;
  4880. #define ADD_MODE(name, method) \
  4881. action = menu->addAction(QTStr("" name), this, \
  4882. &OBSBasic::SetBlendingMethod); \
  4883. action->setProperty("method", (int)method); \
  4884. action->setCheckable(true); \
  4885. action->setChecked(blendingMethod == method);
  4886. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4887. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4888. #undef ADD_MODE
  4889. return menu;
  4890. }
  4891. void OBSBasic::SetBlendingMode()
  4892. {
  4893. QAction *action = reinterpret_cast<QAction *>(sender());
  4894. obs_blending_type mode =
  4895. (obs_blending_type)action->property("mode").toInt();
  4896. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4897. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4898. }
  4899. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4900. {
  4901. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4902. QAction *action;
  4903. #define ADD_MODE(name, mode) \
  4904. action = menu->addAction(QTStr("" name), this, \
  4905. &OBSBasic::SetBlendingMode); \
  4906. action->setProperty("mode", (int)mode); \
  4907. action->setCheckable(true); \
  4908. action->setChecked(blendingMode == mode);
  4909. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4910. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4911. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4912. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4913. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4914. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4915. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4916. #undef ADD_MODE
  4917. return menu;
  4918. }
  4919. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4920. QWidgetAction *widgetAction,
  4921. ColorSelect *select,
  4922. obs_sceneitem_t *item)
  4923. {
  4924. QAction *action;
  4925. menu->setStyleSheet(QString(
  4926. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4927. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4928. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4929. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4930. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4931. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4932. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4933. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4934. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4935. obs_data_release(privData);
  4936. obs_data_set_default_int(privData, "color-preset", 0);
  4937. int preset = obs_data_get_int(privData, "color-preset");
  4938. action = menu->addAction(QTStr("Clear"), this, &OBSBasic::ColorChange);
  4939. action->setCheckable(true);
  4940. action->setProperty("bgColor", 0);
  4941. action->setChecked(preset == 0);
  4942. action = menu->addAction(QTStr("CustomColor"), this,
  4943. &OBSBasic::ColorChange);
  4944. action->setCheckable(true);
  4945. action->setProperty("bgColor", 1);
  4946. action->setChecked(preset == 1);
  4947. menu->addSeparator();
  4948. widgetAction->setDefaultWidget(select);
  4949. for (int i = 1; i < 9; i++) {
  4950. stringstream button;
  4951. button << "preset" << i;
  4952. QPushButton *colorButton =
  4953. select->findChild<QPushButton *>(button.str().c_str());
  4954. if (preset == i + 1)
  4955. colorButton->setStyleSheet("border: 2px solid black");
  4956. colorButton->setProperty("bgColor", i);
  4957. select->connect(colorButton, &QPushButton::released, this,
  4958. &OBSBasic::ColorChange);
  4959. }
  4960. menu->addAction(widgetAction);
  4961. return menu;
  4962. }
  4963. ColorSelect::ColorSelect(QWidget *parent)
  4964. : QWidget(parent),
  4965. ui(new Ui::ColorSelect)
  4966. {
  4967. ui->setupUi(this);
  4968. }
  4969. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4970. {
  4971. QMenu popup(this);
  4972. delete previewProjectorSource;
  4973. delete sourceProjector;
  4974. delete scaleFilteringMenu;
  4975. delete blendingMethodMenu;
  4976. delete blendingModeMenu;
  4977. delete colorMenu;
  4978. delete colorWidgetAction;
  4979. delete colorSelect;
  4980. delete deinterlaceMenu;
  4981. if (preview) {
  4982. QAction *action = popup.addAction(
  4983. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4984. &OBSBasic::TogglePreview);
  4985. action->setCheckable(true);
  4986. action->setChecked(
  4987. obs_display_enabled(ui->preview->GetDisplay()));
  4988. if (IsPreviewProgramMode())
  4989. action->setEnabled(false);
  4990. popup.addAction(ui->actionLockPreview);
  4991. popup.addMenu(ui->scalingMenu);
  4992. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4993. AddProjectorMenuMonitors(previewProjectorSource, this,
  4994. &OBSBasic::OpenPreviewProjector);
  4995. popup.addMenu(previewProjectorSource);
  4996. QAction *previewWindow =
  4997. popup.addAction(QTStr("PreviewWindow"), this,
  4998. &OBSBasic::OpenPreviewWindow);
  4999. popup.addAction(previewWindow);
  5000. popup.addAction(QTStr("Screenshot.Preview"), this,
  5001. &OBSBasic::ScreenshotScene);
  5002. popup.addSeparator();
  5003. }
  5004. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  5005. if (addSourceMenu)
  5006. popup.addMenu(addSourceMenu);
  5007. if (ui->sources->MultipleBaseSelected()) {
  5008. popup.addSeparator();
  5009. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  5010. &SourceTree::GroupSelectedItems);
  5011. } else if (ui->sources->GroupsSelected()) {
  5012. popup.addSeparator();
  5013. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  5014. &SourceTree::UngroupSelectedGroups);
  5015. }
  5016. popup.addSeparator();
  5017. popup.addAction(ui->actionCopySource);
  5018. popup.addAction(ui->actionPasteRef);
  5019. popup.addAction(ui->actionPasteDup);
  5020. popup.addSeparator();
  5021. popup.addSeparator();
  5022. popup.addAction(ui->actionCopyFilters);
  5023. popup.addAction(ui->actionPasteFilters);
  5024. popup.addSeparator();
  5025. if (idx != -1) {
  5026. if (addSourceMenu)
  5027. popup.addSeparator();
  5028. OBSSceneItem sceneItem = ui->sources->Get(idx);
  5029. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  5030. uint32_t flags = obs_source_get_output_flags(source);
  5031. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  5032. OBS_SOURCE_ASYNC_VIDEO;
  5033. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  5034. bool hasVideo = (flags & OBS_SOURCE_VIDEO) == OBS_SOURCE_VIDEO;
  5035. colorMenu = new QMenu(QTStr("ChangeBG"));
  5036. colorWidgetAction = new QWidgetAction(colorMenu);
  5037. colorSelect = new ColorSelect(colorMenu);
  5038. popup.addMenu(AddBackgroundColorMenu(
  5039. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  5040. popup.addAction(renameSource);
  5041. popup.addAction(ui->actionRemoveSource);
  5042. popup.addSeparator();
  5043. popup.addMenu(ui->orderMenu);
  5044. if (hasVideo)
  5045. popup.addMenu(ui->transformMenu);
  5046. popup.addSeparator();
  5047. if (hasAudio) {
  5048. QAction *actionHideMixer =
  5049. popup.addAction(QTStr("HideMixer"), this,
  5050. &OBSBasic::ToggleHideMixer);
  5051. actionHideMixer->setCheckable(true);
  5052. actionHideMixer->setChecked(SourceMixerHidden(source));
  5053. popup.addSeparator();
  5054. }
  5055. if (hasVideo) {
  5056. QAction *resizeOutput = popup.addAction(
  5057. QTStr("ResizeOutputSizeOfSource"), this,
  5058. &OBSBasic::ResizeOutputSizeOfSource);
  5059. int width = obs_source_get_width(source);
  5060. int height = obs_source_get_height(source);
  5061. resizeOutput->setEnabled(!obs_video_active());
  5062. if (width < 32 || height < 32)
  5063. resizeOutput->setEnabled(false);
  5064. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  5065. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu,
  5066. sceneItem));
  5067. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  5068. popup.addMenu(AddBlendingModeMenu(blendingModeMenu,
  5069. sceneItem));
  5070. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  5071. popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu,
  5072. sceneItem));
  5073. if (isAsyncVideo) {
  5074. deinterlaceMenu =
  5075. new QMenu(QTStr("Deinterlacing"));
  5076. popup.addMenu(AddDeinterlacingMenu(
  5077. deinterlaceMenu, source));
  5078. }
  5079. popup.addSeparator();
  5080. popup.addMenu(CreateVisibilityTransitionMenu(true));
  5081. popup.addMenu(CreateVisibilityTransitionMenu(false));
  5082. popup.addSeparator();
  5083. sourceProjector = new QMenu(QTStr("SourceProjector"));
  5084. AddProjectorMenuMonitors(
  5085. sourceProjector, this,
  5086. &OBSBasic::OpenSourceProjector);
  5087. popup.addMenu(sourceProjector);
  5088. popup.addAction(QTStr("SourceWindow"), this,
  5089. &OBSBasic::OpenSourceWindow);
  5090. popup.addAction(QTStr("Screenshot.Source"), this,
  5091. &OBSBasic::ScreenshotSelectedSource);
  5092. }
  5093. popup.addSeparator();
  5094. if (flags & OBS_SOURCE_INTERACTION)
  5095. popup.addAction(QTStr("Interact"), this,
  5096. &OBSBasic::on_actionInteract_triggered);
  5097. popup.addAction(QTStr("Filters"), this,
  5098. [&]() { OpenFilters(); });
  5099. QAction *action = popup.addAction(
  5100. QTStr("Properties"), this,
  5101. &OBSBasic::on_actionSourceProperties_triggered);
  5102. action->setEnabled(obs_source_configurable(source));
  5103. }
  5104. popup.exec(QCursor::pos());
  5105. }
  5106. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  5107. {
  5108. if (ui->scenes->count()) {
  5109. QModelIndex idx = ui->sources->indexAt(pos);
  5110. CreateSourcePopupMenu(idx.row(), false);
  5111. }
  5112. }
  5113. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  5114. {
  5115. if (!witem)
  5116. return;
  5117. if (IsPreviewProgramMode()) {
  5118. bool doubleClickSwitch =
  5119. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  5120. "TransitionOnDoubleClick");
  5121. if (doubleClickSwitch)
  5122. TransitionClicked();
  5123. }
  5124. }
  5125. static inline bool should_show_properties(obs_source_t *source, const char *id)
  5126. {
  5127. if (!source)
  5128. return false;
  5129. if (strcmp(id, "group") == 0)
  5130. return false;
  5131. if (!obs_source_configurable(source))
  5132. return false;
  5133. uint32_t caps = obs_source_get_output_flags(source);
  5134. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  5135. return false;
  5136. return true;
  5137. }
  5138. void OBSBasic::AddSource(const char *id)
  5139. {
  5140. if (id && *id) {
  5141. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  5142. sourceSelect.exec();
  5143. if (should_show_properties(sourceSelect.newSource, id)) {
  5144. CreatePropertiesWindow(sourceSelect.newSource);
  5145. }
  5146. }
  5147. }
  5148. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  5149. {
  5150. const char *unversioned_type;
  5151. const char *type;
  5152. bool foundValues = false;
  5153. bool foundDeprecated = false;
  5154. size_t idx = 0;
  5155. QMenu *popup = new QMenu(QTStr("Add"), this);
  5156. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  5157. auto getActionAfter = [](QMenu *menu, const QString &name) {
  5158. QList<QAction *> actions = menu->actions();
  5159. for (QAction *menuAction : actions) {
  5160. if (menuAction->text().compare(
  5161. name, Qt::CaseInsensitive) >= 0)
  5162. return menuAction;
  5163. }
  5164. return (QAction *)nullptr;
  5165. };
  5166. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  5167. const char *name) {
  5168. QString qname = QT_UTF8(name);
  5169. QAction *popupItem = new QAction(qname, this);
  5170. connect(popupItem, &QAction::triggered,
  5171. [this, type]() { AddSource(type); });
  5172. QIcon icon;
  5173. if (strcmp(type, "scene") == 0)
  5174. icon = GetSceneIcon();
  5175. else
  5176. icon = GetSourceIcon(type);
  5177. popupItem->setIcon(icon);
  5178. QAction *after = getActionAfter(popup, qname);
  5179. popup->insertAction(after, popupItem);
  5180. };
  5181. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  5182. const char *name = obs_source_get_display_name(type);
  5183. uint32_t caps = obs_get_source_output_flags(type);
  5184. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  5185. continue;
  5186. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  5187. addSource(popup, unversioned_type, name);
  5188. } else {
  5189. addSource(deprecated, unversioned_type, name);
  5190. foundDeprecated = true;
  5191. }
  5192. foundValues = true;
  5193. }
  5194. addSource(popup, "scene", Str("Basic.Scene"));
  5195. popup->addSeparator();
  5196. QAction *addGroup = new QAction(QTStr("Group"), this);
  5197. addGroup->setIcon(GetGroupIcon());
  5198. connect(addGroup, &QAction::triggered,
  5199. [this]() { AddSource("group"); });
  5200. popup->addAction(addGroup);
  5201. if (!foundDeprecated) {
  5202. delete deprecated;
  5203. deprecated = nullptr;
  5204. }
  5205. if (!foundValues) {
  5206. delete popup;
  5207. popup = nullptr;
  5208. } else if (foundDeprecated) {
  5209. popup->addSeparator();
  5210. popup->addMenu(deprecated);
  5211. }
  5212. return popup;
  5213. }
  5214. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  5215. {
  5216. if (!GetCurrentScene()) {
  5217. // Tell the user he needs a scene first (help beginners).
  5218. OBSMessageBox::information(
  5219. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  5220. QTStr("Basic.Main.AddSourceHelp.Text"));
  5221. return;
  5222. }
  5223. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  5224. if (popup)
  5225. popup->exec(pos);
  5226. }
  5227. void OBSBasic::on_actionAddSource_triggered()
  5228. {
  5229. AddSourcePopupMenu(QCursor::pos());
  5230. }
  5231. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5232. {
  5233. vector<OBSSceneItem> &items =
  5234. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  5235. if (obs_sceneitem_selected(item)) {
  5236. items.emplace_back(item);
  5237. } else if (obs_sceneitem_is_group(item)) {
  5238. obs_sceneitem_group_enum_items(item, remove_items, &items);
  5239. }
  5240. return true;
  5241. };
  5242. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  5243. std::vector<obs_source_t *> *sources)
  5244. {
  5245. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  5246. if (!sources) {
  5247. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  5248. } else {
  5249. for (obs_source_t *source : *sources) {
  5250. obs_data_t *source_data = obs_save_source(source);
  5251. obs_data_array_push_back(undo_array, source_data);
  5252. obs_data_release(source_data);
  5253. }
  5254. }
  5255. OBSDataAutoRelease scene_data =
  5256. obs_save_source(obs_scene_get_source(scene));
  5257. obs_data_array_push_back(undo_array, scene_data);
  5258. OBSDataAutoRelease data = obs_data_create();
  5259. obs_data_set_array(data, "array", undo_array);
  5260. obs_data_get_json(data);
  5261. return data.Get();
  5262. }
  5263. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  5264. {
  5265. auto sources = static_cast<std::vector<OBSSource> *>(p);
  5266. sources->push_back(obs_sceneitem_get_source(item));
  5267. return true;
  5268. }
  5269. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  5270. OBSData undo_data, OBSData redo_data)
  5271. {
  5272. auto undo_redo = [this](const std::string &json) {
  5273. OBSDataAutoRelease base =
  5274. obs_data_create_from_json(json.c_str());
  5275. OBSDataArrayAutoRelease array =
  5276. obs_data_get_array(base, "array");
  5277. std::vector<OBSSource> sources;
  5278. std::vector<OBSSource> old_sources;
  5279. /* create missing sources */
  5280. const size_t count = obs_data_array_count(array);
  5281. sources.reserve(count);
  5282. for (size_t i = 0; i < count; i++) {
  5283. OBSDataAutoRelease data = obs_data_array_item(array, i);
  5284. const char *name = obs_data_get_string(data, "name");
  5285. OBSSourceAutoRelease source =
  5286. obs_get_source_by_name(name);
  5287. if (!source)
  5288. source = obs_load_source(data);
  5289. sources.push_back(source.Get());
  5290. /* update scene/group settings to restore their
  5291. * contents to their saved settings */
  5292. obs_scene_t *scene =
  5293. obs_group_or_scene_from_source(source);
  5294. if (scene) {
  5295. obs_scene_enum_items(scene, add_source_enum,
  5296. &old_sources);
  5297. OBSDataAutoRelease scene_settings =
  5298. obs_data_get_obj(data, "settings");
  5299. obs_source_update(source, scene_settings);
  5300. }
  5301. }
  5302. /* actually load sources now */
  5303. for (obs_source_t *source : sources)
  5304. obs_source_load2(source);
  5305. ui->sources->RefreshItems();
  5306. };
  5307. const char *undo_json = obs_data_get_last_json(undo_data);
  5308. const char *redo_json = obs_data_get_last_json(redo_data);
  5309. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  5310. redo_json);
  5311. }
  5312. void OBSBasic::on_actionRemoveSource_triggered()
  5313. {
  5314. vector<OBSSceneItem> items;
  5315. OBSScene scene = GetCurrentScene();
  5316. obs_source_t *scene_source = obs_scene_get_source(scene);
  5317. obs_scene_enum_items(scene, remove_items, &items);
  5318. if (!items.size())
  5319. return;
  5320. /* ------------------------------------- */
  5321. /* confirm action with user */
  5322. bool confirmed = false;
  5323. if (items.size() > 1) {
  5324. QString text = QTStr("ConfirmRemove.TextMultiple")
  5325. .arg(QString::number(items.size()));
  5326. QMessageBox remove_items(this);
  5327. remove_items.setText(text);
  5328. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  5329. QMessageBox::YesRole);
  5330. remove_items.setDefaultButton(Yes);
  5331. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  5332. remove_items.setIcon(QMessageBox::Question);
  5333. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  5334. remove_items.exec();
  5335. confirmed = Yes == remove_items.clickedButton();
  5336. } else {
  5337. OBSSceneItem &item = items[0];
  5338. obs_source_t *source = obs_sceneitem_get_source(item);
  5339. if (source && QueryRemoveSource(source))
  5340. confirmed = true;
  5341. }
  5342. if (!confirmed)
  5343. return;
  5344. /* ----------------------------------------------- */
  5345. /* save undo data */
  5346. OBSData undo_data = BackupScene(scene_source);
  5347. /* ----------------------------------------------- */
  5348. /* remove items */
  5349. for (auto &item : items)
  5350. obs_sceneitem_remove(item);
  5351. /* ----------------------------------------------- */
  5352. /* save redo data */
  5353. OBSData redo_data = BackupScene(scene_source);
  5354. /* ----------------------------------------------- */
  5355. /* add undo/redo action */
  5356. QString action_name;
  5357. if (items.size() > 1) {
  5358. action_name = QTStr("Undo.Sources.Multi")
  5359. .arg(QString::number(items.size()));
  5360. } else {
  5361. QString str = QTStr("Undo.Delete");
  5362. action_name = str.arg(obs_source_get_name(
  5363. obs_sceneitem_get_source(items[0])));
  5364. }
  5365. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  5366. }
  5367. void OBSBasic::on_actionInteract_triggered()
  5368. {
  5369. OBSSceneItem item = GetCurrentSceneItem();
  5370. OBSSource source = obs_sceneitem_get_source(item);
  5371. if (source)
  5372. CreateInteractionWindow(source);
  5373. }
  5374. void OBSBasic::on_actionSourceProperties_triggered()
  5375. {
  5376. OBSSceneItem item = GetCurrentSceneItem();
  5377. OBSSource source = obs_sceneitem_get_source(item);
  5378. if (source)
  5379. CreatePropertiesWindow(source);
  5380. }
  5381. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  5382. const QString &action_name)
  5383. {
  5384. OBSSceneItem item = GetCurrentSceneItem();
  5385. obs_source_t *source = obs_sceneitem_get_source(item);
  5386. if (!source)
  5387. return;
  5388. OBSScene scene = GetCurrentScene();
  5389. std::vector<obs_source_t *> sources;
  5390. if (scene != obs_sceneitem_get_scene(item))
  5391. sources.push_back(
  5392. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  5393. OBSData undo_data = BackupScene(scene, &sources);
  5394. obs_sceneitem_set_order(item, movement);
  5395. const char *source_name = obs_source_get_name(source);
  5396. const char *scene_name =
  5397. obs_source_get_name(obs_scene_get_source(scene));
  5398. OBSData redo_data = BackupScene(scene, &sources);
  5399. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  5400. undo_data, redo_data);
  5401. }
  5402. void OBSBasic::on_actionSourceUp_triggered()
  5403. {
  5404. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5405. }
  5406. void OBSBasic::on_actionSourceDown_triggered()
  5407. {
  5408. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5409. }
  5410. void OBSBasic::on_actionMoveUp_triggered()
  5411. {
  5412. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5413. }
  5414. void OBSBasic::on_actionMoveDown_triggered()
  5415. {
  5416. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5417. }
  5418. void OBSBasic::on_actionMoveToTop_triggered()
  5419. {
  5420. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  5421. }
  5422. void OBSBasic::on_actionMoveToBottom_triggered()
  5423. {
  5424. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  5425. }
  5426. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  5427. {
  5428. char logDir[512];
  5429. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  5430. return nullptr;
  5431. string path = logDir;
  5432. path += "/";
  5433. path += log;
  5434. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  5435. if (!file)
  5436. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  5437. return file;
  5438. }
  5439. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  5440. {
  5441. BPtr<char> fileString{ReadLogFile(subdir, file)};
  5442. if (!fileString)
  5443. return;
  5444. if (!*fileString)
  5445. return;
  5446. ui->menuLogFiles->setEnabled(false);
  5447. #if defined(_WIN32)
  5448. ui->menuCrashLogs->setEnabled(false);
  5449. #endif
  5450. stringstream ss;
  5451. ss << "OBS " << App()->GetVersionString(false)
  5452. << " log file uploaded at " << CurrentDateTimeString() << "\n\n"
  5453. << fileString;
  5454. if (logUploadThread) {
  5455. logUploadThread->wait();
  5456. }
  5457. RemoteTextThread *thread = new RemoteTextThread(
  5458. "https://obsproject.com/logs/upload", "text/plain", ss.str());
  5459. logUploadThread.reset(thread);
  5460. if (crash) {
  5461. connect(thread, &RemoteTextThread::Result, this,
  5462. &OBSBasic::crashUploadFinished);
  5463. } else {
  5464. connect(thread, &RemoteTextThread::Result, this,
  5465. &OBSBasic::logUploadFinished);
  5466. }
  5467. logUploadThread->start();
  5468. }
  5469. void OBSBasic::on_actionShowLogs_triggered()
  5470. {
  5471. char logDir[512];
  5472. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5473. return;
  5474. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5475. QDesktopServices::openUrl(url);
  5476. }
  5477. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5478. {
  5479. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5480. }
  5481. void OBSBasic::on_actionUploadLastLog_triggered()
  5482. {
  5483. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5484. }
  5485. void OBSBasic::on_actionViewCurrentLog_triggered()
  5486. {
  5487. if (!logView)
  5488. logView = new OBSLogViewer();
  5489. logView->show();
  5490. logView->setWindowState(
  5491. (logView->windowState() & ~Qt::WindowMinimized) |
  5492. Qt::WindowActive);
  5493. logView->activateWindow();
  5494. logView->raise();
  5495. }
  5496. void OBSBasic::on_actionShowCrashLogs_triggered()
  5497. {
  5498. char logDir[512];
  5499. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5500. return;
  5501. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5502. QDesktopServices::openUrl(url);
  5503. }
  5504. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5505. {
  5506. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5507. }
  5508. void OBSBasic::on_actionCheckForUpdates_triggered()
  5509. {
  5510. CheckForUpdates(true);
  5511. }
  5512. void OBSBasic::on_actionRepair_triggered()
  5513. {
  5514. #if defined(_WIN32)
  5515. ui->actionCheckForUpdates->setEnabled(false);
  5516. ui->actionRepair->setEnabled(false);
  5517. if (updateCheckThread && updateCheckThread->isRunning())
  5518. return;
  5519. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5520. updateCheckThread->start();
  5521. #endif
  5522. }
  5523. void OBSBasic::on_actionRestartSafe_triggered()
  5524. {
  5525. QMessageBox::StandardButton button = OBSMessageBox::question(
  5526. this, QTStr("Restart"),
  5527. safe_mode ? QTStr("SafeMode.RestartNormal")
  5528. : QTStr("SafeMode.Restart"));
  5529. if (button == QMessageBox::Yes) {
  5530. restart = safe_mode;
  5531. restart_safe = !safe_mode;
  5532. close();
  5533. }
  5534. }
  5535. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5536. {
  5537. ui->menuLogFiles->setEnabled(true);
  5538. #if defined(_WIN32)
  5539. ui->menuCrashLogs->setEnabled(true);
  5540. #endif
  5541. if (text.isEmpty()) {
  5542. OBSMessageBox::critical(
  5543. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5544. error);
  5545. return;
  5546. }
  5547. openLogDialog(text, false);
  5548. }
  5549. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5550. {
  5551. ui->menuLogFiles->setEnabled(true);
  5552. #if defined(_WIN32)
  5553. ui->menuCrashLogs->setEnabled(true);
  5554. #endif
  5555. if (text.isEmpty()) {
  5556. OBSMessageBox::critical(
  5557. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5558. error);
  5559. return;
  5560. }
  5561. openLogDialog(text, true);
  5562. }
  5563. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5564. {
  5565. OBSDataAutoRelease returnData =
  5566. obs_data_create_from_json(QT_TO_UTF8(text));
  5567. string resURL = obs_data_get_string(returnData, "url");
  5568. QString logURL = resURL.c_str();
  5569. OBSLogReply logDialog(this, logURL, crash);
  5570. logDialog.exec();
  5571. }
  5572. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5573. obs_source_t *source, const string &name)
  5574. {
  5575. const char *prevName = obs_source_get_name(source);
  5576. if (name == prevName)
  5577. return;
  5578. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5579. QListWidgetItem *listItem = listWidget->currentItem();
  5580. if (foundSource || name.empty()) {
  5581. listItem->setText(QT_UTF8(prevName));
  5582. if (foundSource) {
  5583. OBSMessageBox::warning(parent,
  5584. QTStr("NameExists.Title"),
  5585. QTStr("NameExists.Text"));
  5586. } else if (name.empty()) {
  5587. OBSMessageBox::warning(parent,
  5588. QTStr("NoNameEntered.Title"),
  5589. QTStr("NoNameEntered.Text"));
  5590. }
  5591. } else {
  5592. auto undo = [prev = std::string(prevName)](
  5593. const std::string &data) {
  5594. OBSSourceAutoRelease source =
  5595. obs_get_source_by_uuid(data.c_str());
  5596. obs_source_set_name(source, prev.c_str());
  5597. };
  5598. auto redo = [name](const std::string &data) {
  5599. OBSSourceAutoRelease source =
  5600. obs_get_source_by_uuid(data.c_str());
  5601. obs_source_set_name(source, name.c_str());
  5602. };
  5603. std::string source_uuid(obs_source_get_uuid(source));
  5604. parent->undo_s.add_action(
  5605. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5606. source_uuid, source_uuid);
  5607. listItem->setText(QT_UTF8(name.c_str()));
  5608. obs_source_set_name(source, name.c_str());
  5609. }
  5610. }
  5611. void OBSBasic::SceneNameEdited(QWidget *editor)
  5612. {
  5613. OBSScene scene = GetCurrentScene();
  5614. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5615. string text = QT_TO_UTF8(edit->text().trimmed());
  5616. if (!scene)
  5617. return;
  5618. obs_source_t *source = obs_scene_get_source(scene);
  5619. RenameListItem(this, ui->scenes, source, text);
  5620. ui->scenesDock->addAction(renameScene);
  5621. OnEvent(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5622. }
  5623. void OBSBasic::OpenFilters(OBSSource source)
  5624. {
  5625. if (source == nullptr) {
  5626. OBSSceneItem item = GetCurrentSceneItem();
  5627. source = obs_sceneitem_get_source(item);
  5628. }
  5629. CreateFiltersWindow(source);
  5630. }
  5631. void OBSBasic::OpenProperties(OBSSource source)
  5632. {
  5633. if (source == nullptr) {
  5634. OBSSceneItem item = GetCurrentSceneItem();
  5635. source = obs_sceneitem_get_source(item);
  5636. }
  5637. CreatePropertiesWindow(source);
  5638. }
  5639. void OBSBasic::OpenInteraction(OBSSource source)
  5640. {
  5641. if (source == nullptr) {
  5642. OBSSceneItem item = GetCurrentSceneItem();
  5643. source = obs_sceneitem_get_source(item);
  5644. }
  5645. CreateInteractionWindow(source);
  5646. }
  5647. void OBSBasic::OpenEditTransform(OBSSceneItem item)
  5648. {
  5649. if (!item)
  5650. item = GetCurrentSceneItem();
  5651. if (!item)
  5652. return;
  5653. CreateEditTransformWindow(item);
  5654. }
  5655. void OBSBasic::OpenSceneFilters()
  5656. {
  5657. OBSScene scene = GetCurrentScene();
  5658. OBSSource source = obs_scene_get_source(scene);
  5659. CreateFiltersWindow(source);
  5660. }
  5661. #define RECORDING_START \
  5662. "==== Recording Start ==============================================="
  5663. #define RECORDING_STOP \
  5664. "==== Recording Stop ================================================"
  5665. #define REPLAY_BUFFER_START \
  5666. "==== Replay Buffer Start ==========================================="
  5667. #define REPLAY_BUFFER_STOP \
  5668. "==== Replay Buffer Stop ============================================"
  5669. #define STREAMING_START \
  5670. "==== Streaming Start ==============================================="
  5671. #define STREAMING_STOP \
  5672. "==== Streaming Stop ================================================"
  5673. #define VIRTUAL_CAM_START \
  5674. "==== Virtual Camera Start =========================================="
  5675. #define VIRTUAL_CAM_STOP \
  5676. "==== Virtual Camera Stop ==========================================="
  5677. void OBSBasic::DisplayStreamStartError()
  5678. {
  5679. QString message = !outputHandler->lastError.empty()
  5680. ? QTStr(outputHandler->lastError.c_str())
  5681. : QTStr("Output.StartFailedGeneric");
  5682. emit StreamingStopped();
  5683. if (sysTrayStream) {
  5684. sysTrayStream->setText(QTStr("Basic.Main.StartStreaming"));
  5685. sysTrayStream->setEnabled(true);
  5686. }
  5687. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5688. }
  5689. #ifdef YOUTUBE_ENABLED
  5690. void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id,
  5691. const QString &stream_id,
  5692. const QString &key, bool autostart,
  5693. bool autostop, bool start_now)
  5694. {
  5695. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5696. obs_service_t *service_obj = GetService();
  5697. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5698. const std::string a_key = QT_TO_UTF8(key);
  5699. obs_data_set_string(settings, "key", a_key.c_str());
  5700. const std::string b_id = QT_TO_UTF8(broadcast_id);
  5701. obs_data_set_string(settings, "broadcast_id", b_id.c_str());
  5702. const std::string s_id = QT_TO_UTF8(stream_id);
  5703. obs_data_set_string(settings, "stream_id", s_id.c_str());
  5704. obs_service_update(service_obj, settings);
  5705. autoStartBroadcast = autostart;
  5706. autoStopBroadcast = autostop;
  5707. broadcastReady = true;
  5708. emit BroadcastStreamReady(broadcastReady);
  5709. if (start_now)
  5710. QMetaObject::invokeMethod(this, "StartStreaming");
  5711. }
  5712. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5713. {
  5714. YoutubeApiWrappers *apiYouTube(
  5715. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5716. if (!apiYouTube) {
  5717. /* technically we should never get here -Lain */
  5718. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5719. Qt::QueuedConnection);
  5720. youtubeStreamCheckThread->deleteLater();
  5721. blog(LOG_ERROR, "==========================================");
  5722. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5723. blog(LOG_ERROR, "==========================================");
  5724. return;
  5725. }
  5726. int timeout = 0;
  5727. json11::Json json;
  5728. QString id = key.c_str();
  5729. while (StreamingActive()) {
  5730. if (timeout == 14) {
  5731. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5732. Qt::QueuedConnection);
  5733. break;
  5734. }
  5735. if (!apiYouTube->FindStream(id, json)) {
  5736. QMetaObject::invokeMethod(this,
  5737. "DisplayStreamStartError",
  5738. Qt::QueuedConnection);
  5739. QMetaObject::invokeMethod(this, "StopStreaming",
  5740. Qt::QueuedConnection);
  5741. break;
  5742. }
  5743. auto item = json["items"][0];
  5744. auto status = item["status"]["streamStatus"].string_value();
  5745. if (status == "active") {
  5746. emit BroadcastStreamActive();
  5747. break;
  5748. } else {
  5749. QThread::sleep(1);
  5750. timeout++;
  5751. }
  5752. }
  5753. youtubeStreamCheckThread->deleteLater();
  5754. }
  5755. void OBSBasic::ShowYouTubeAutoStartWarning()
  5756. {
  5757. auto msgBox = []() {
  5758. QMessageBox msgbox(App()->GetMainWindow());
  5759. msgbox.setWindowTitle(QTStr(
  5760. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5761. msgbox.setText(
  5762. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5763. msgbox.setIcon(QMessageBox::Icon::Information);
  5764. msgbox.addButton(QMessageBox::Ok);
  5765. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5766. msgbox.setCheckBox(cb);
  5767. msgbox.exec();
  5768. if (cb->isChecked()) {
  5769. config_set_bool(App()->GlobalConfig(), "General",
  5770. "WarnedAboutYouTubeAutoStart", true);
  5771. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5772. }
  5773. };
  5774. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5775. "WarnedAboutYouTubeAutoStart");
  5776. if (!warned) {
  5777. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5778. Q_ARG(VoidFunc, msgBox));
  5779. }
  5780. }
  5781. #endif
  5782. void OBSBasic::StartStreaming()
  5783. {
  5784. if (outputHandler->StreamingActive())
  5785. return;
  5786. if (disableOutputsRef)
  5787. return;
  5788. if (auth && auth->broadcastFlow()) {
  5789. if (!broadcastActive && !broadcastReady) {
  5790. QMessageBox no_broadcast(this);
  5791. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5792. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5793. QTStr("Basic.Main.SetupBroadcast"),
  5794. QMessageBox::YesRole);
  5795. no_broadcast.setDefaultButton(SetupBroadcast);
  5796. no_broadcast.addButton(QTStr("Close"),
  5797. QMessageBox::NoRole);
  5798. no_broadcast.setIcon(QMessageBox::Information);
  5799. no_broadcast.setWindowTitle(
  5800. QTStr("Output.NoBroadcast.Title"));
  5801. no_broadcast.exec();
  5802. if (no_broadcast.clickedButton() == SetupBroadcast)
  5803. QMetaObject::invokeMethod(this,
  5804. "SetupBroadcast");
  5805. return;
  5806. }
  5807. }
  5808. emit StreamingPreparing();
  5809. if (sysTrayStream) {
  5810. sysTrayStream->setEnabled(false);
  5811. sysTrayStream->setText("Basic.Main.PreparingStream");
  5812. }
  5813. auto finish_stream_setup = [&](bool setupStreamingResult) {
  5814. if (!setupStreamingResult) {
  5815. DisplayStreamStartError();
  5816. return;
  5817. }
  5818. OnEvent(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5819. SaveProject();
  5820. emit StreamingStarting(autoStartBroadcast);
  5821. if (sysTrayStream)
  5822. sysTrayStream->setText("Basic.Main.Connecting");
  5823. if (!outputHandler->StartStreaming(service)) {
  5824. DisplayStreamStartError();
  5825. return;
  5826. }
  5827. if (autoStartBroadcast) {
  5828. emit BroadcastStreamStarted(autoStopBroadcast);
  5829. broadcastActive = true;
  5830. }
  5831. bool recordWhenStreaming =
  5832. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5833. "RecordWhenStreaming");
  5834. if (recordWhenStreaming)
  5835. StartRecording();
  5836. bool replayBufferWhileStreaming =
  5837. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5838. "ReplayBufferWhileStreaming");
  5839. if (replayBufferWhileStreaming)
  5840. StartReplayBuffer();
  5841. #ifdef YOUTUBE_ENABLED
  5842. if (!autoStartBroadcast)
  5843. OBSBasic::ShowYouTubeAutoStartWarning();
  5844. #endif
  5845. };
  5846. setupStreamingGuard =
  5847. outputHandler->SetupStreaming(service, finish_stream_setup);
  5848. }
  5849. void OBSBasic::BroadcastButtonClicked()
  5850. {
  5851. if (!broadcastReady ||
  5852. (!broadcastActive && !outputHandler->StreamingActive())) {
  5853. SetupBroadcast();
  5854. return;
  5855. }
  5856. if (!autoStartBroadcast) {
  5857. #ifdef YOUTUBE_ENABLED
  5858. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5859. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5860. if (ytAuth.get()) {
  5861. if (!ytAuth->StartLatestBroadcast()) {
  5862. auto last_error = ytAuth->GetLastError();
  5863. if (last_error.isEmpty())
  5864. last_error = QTStr(
  5865. "YouTube.Actions.Error.YouTubeApi");
  5866. if (!ytAuth->GetTranslatedError(last_error))
  5867. last_error =
  5868. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5869. .arg(last_error,
  5870. ytAuth->GetBroadcastId());
  5871. OBSMessageBox::warning(
  5872. this,
  5873. QTStr("Output.BroadcastStartFailed"),
  5874. last_error, true);
  5875. return;
  5876. }
  5877. }
  5878. #endif
  5879. broadcastActive = true;
  5880. autoStartBroadcast = true; // and clear the flag
  5881. emit BroadcastStreamStarted(autoStopBroadcast);
  5882. } else if (!autoStopBroadcast) {
  5883. #ifdef YOUTUBE_ENABLED
  5884. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5885. "WarnBeforeStoppingStream");
  5886. if (confirm && isVisible()) {
  5887. QMessageBox::StandardButton button = OBSMessageBox::question(
  5888. this, QTStr("ConfirmStop.Title"),
  5889. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5890. QMessageBox::Yes | QMessageBox::No,
  5891. QMessageBox::No);
  5892. if (button == QMessageBox::No)
  5893. return;
  5894. }
  5895. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5896. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5897. if (ytAuth.get()) {
  5898. if (!ytAuth->StopLatestBroadcast()) {
  5899. auto last_error = ytAuth->GetLastError();
  5900. if (last_error.isEmpty())
  5901. last_error = QTStr(
  5902. "YouTube.Actions.Error.YouTubeApi");
  5903. if (!ytAuth->GetTranslatedError(last_error))
  5904. last_error =
  5905. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5906. .arg(last_error,
  5907. ytAuth->GetBroadcastId());
  5908. OBSMessageBox::warning(
  5909. this,
  5910. QTStr("Output.BroadcastStopFailed"),
  5911. last_error, true);
  5912. }
  5913. }
  5914. #endif
  5915. broadcastActive = false;
  5916. broadcastReady = false;
  5917. autoStopBroadcast = true;
  5918. QMetaObject::invokeMethod(this, "StopStreaming");
  5919. emit BroadcastStreamReady(broadcastReady);
  5920. SetBroadcastFlowEnabled(true);
  5921. }
  5922. }
  5923. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5924. {
  5925. emit BroadcastFlowEnabled(enabled);
  5926. }
  5927. void OBSBasic::SetupBroadcast()
  5928. {
  5929. #ifdef YOUTUBE_ENABLED
  5930. Auth *const auth = GetAuth();
  5931. if (IsYouTubeService(auth->service())) {
  5932. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5933. connect(&dialog, &OBSYoutubeActions::ok, this,
  5934. &OBSBasic::YouTubeActionDialogOk);
  5935. dialog.exec();
  5936. }
  5937. #endif
  5938. }
  5939. #ifdef _WIN32
  5940. static inline void UpdateProcessPriority()
  5941. {
  5942. const char *priority = config_get_string(App()->GlobalConfig(),
  5943. "General", "ProcessPriority");
  5944. if (priority && strcmp(priority, "Normal") != 0)
  5945. SetProcessPriority(priority);
  5946. }
  5947. static inline void ClearProcessPriority()
  5948. {
  5949. const char *priority = config_get_string(App()->GlobalConfig(),
  5950. "General", "ProcessPriority");
  5951. if (priority && strcmp(priority, "Normal") != 0)
  5952. SetProcessPriority("Normal");
  5953. }
  5954. #else
  5955. #define UpdateProcessPriority() \
  5956. do { \
  5957. } while (false)
  5958. #define ClearProcessPriority() \
  5959. do { \
  5960. } while (false)
  5961. #endif
  5962. inline void OBSBasic::OnActivate(bool force)
  5963. {
  5964. if (ui->profileMenu->isEnabled() || force) {
  5965. ui->profileMenu->setEnabled(false);
  5966. ui->autoConfigure->setEnabled(false);
  5967. App()->IncrementSleepInhibition();
  5968. UpdateProcessPriority();
  5969. struct obs_video_info ovi;
  5970. obs_get_video_info(&ovi);
  5971. lastOutputResolution = {ovi.base_width, ovi.base_height};
  5972. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5973. if (trayIcon && trayIcon->isVisible()) {
  5974. #ifdef __APPLE__
  5975. QIcon trayMask =
  5976. QIcon(":/res/images/tray_active_macos.svg");
  5977. trayMask.setIsMask(true);
  5978. trayIcon->setIcon(
  5979. QIcon::fromTheme("obs-tray", trayMask));
  5980. #else
  5981. trayIcon->setIcon(QIcon::fromTheme(
  5982. "obs-tray-active",
  5983. QIcon(":/res/images/tray_active.png")));
  5984. #endif
  5985. }
  5986. }
  5987. }
  5988. extern volatile bool recording_paused;
  5989. extern volatile bool replaybuf_active;
  5990. inline void OBSBasic::OnDeactivate()
  5991. {
  5992. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5993. ui->profileMenu->setEnabled(true);
  5994. ui->autoConfigure->setEnabled(true);
  5995. App()->DecrementSleepInhibition();
  5996. ClearProcessPriority();
  5997. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5998. if (trayIcon && trayIcon->isVisible()) {
  5999. #ifdef __APPLE__
  6000. QIcon trayIconFile =
  6001. QIcon(":/res/images/obs_macos.svg");
  6002. trayIconFile.setIsMask(true);
  6003. #else
  6004. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  6005. #endif
  6006. trayIcon->setIcon(
  6007. QIcon::fromTheme("obs-tray", trayIconFile));
  6008. }
  6009. } else if (outputHandler->Active() && trayIcon &&
  6010. trayIcon->isVisible()) {
  6011. if (os_atomic_load_bool(&recording_paused)) {
  6012. #ifdef __APPLE__
  6013. QIcon trayIconFile =
  6014. QIcon(":/res/images/obs_paused_macos.svg");
  6015. trayIconFile.setIsMask(true);
  6016. #else
  6017. QIcon trayIconFile =
  6018. QIcon(":/res/images/obs_paused.png");
  6019. #endif
  6020. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  6021. trayIconFile));
  6022. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  6023. } else {
  6024. #ifdef __APPLE__
  6025. QIcon trayIconFile =
  6026. QIcon(":/res/images/tray_active_macos.svg");
  6027. trayIconFile.setIsMask(true);
  6028. #else
  6029. QIcon trayIconFile =
  6030. QIcon(":/res/images/tray_active.png");
  6031. #endif
  6032. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  6033. trayIconFile));
  6034. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  6035. }
  6036. }
  6037. }
  6038. void OBSBasic::StopStreaming()
  6039. {
  6040. SaveProject();
  6041. if (outputHandler->StreamingActive())
  6042. outputHandler->StopStreaming(streamingStopping);
  6043. // special case: force reset broadcast state if
  6044. // no autostart and no autostop selected
  6045. if (!autoStartBroadcast && !broadcastActive) {
  6046. broadcastActive = false;
  6047. autoStartBroadcast = true;
  6048. autoStopBroadcast = true;
  6049. broadcastReady = false;
  6050. }
  6051. if (autoStopBroadcast) {
  6052. broadcastActive = false;
  6053. broadcastReady = false;
  6054. }
  6055. emit BroadcastStreamReady(broadcastReady);
  6056. OnDeactivate();
  6057. bool recordWhenStreaming = config_get_bool(
  6058. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6059. bool keepRecordingWhenStreamStops =
  6060. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6061. "KeepRecordingWhenStreamStops");
  6062. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6063. StopRecording();
  6064. bool replayBufferWhileStreaming = config_get_bool(
  6065. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6066. bool keepReplayBufferStreamStops =
  6067. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6068. "KeepReplayBufferStreamStops");
  6069. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6070. StopReplayBuffer();
  6071. }
  6072. void OBSBasic::ForceStopStreaming()
  6073. {
  6074. SaveProject();
  6075. if (outputHandler->StreamingActive())
  6076. outputHandler->StopStreaming(true);
  6077. // special case: force reset broadcast state if
  6078. // no autostart and no autostop selected
  6079. if (!autoStartBroadcast && !broadcastActive) {
  6080. broadcastActive = false;
  6081. autoStartBroadcast = true;
  6082. autoStopBroadcast = true;
  6083. broadcastReady = false;
  6084. }
  6085. if (autoStopBroadcast) {
  6086. broadcastActive = false;
  6087. broadcastReady = false;
  6088. }
  6089. emit BroadcastStreamReady(broadcastReady);
  6090. OnDeactivate();
  6091. bool recordWhenStreaming = config_get_bool(
  6092. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6093. bool keepRecordingWhenStreamStops =
  6094. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6095. "KeepRecordingWhenStreamStops");
  6096. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6097. StopRecording();
  6098. bool replayBufferWhileStreaming = config_get_bool(
  6099. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6100. bool keepReplayBufferStreamStops =
  6101. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6102. "KeepReplayBufferStreamStops");
  6103. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6104. StopReplayBuffer();
  6105. }
  6106. void OBSBasic::StreamDelayStarting(int sec)
  6107. {
  6108. emit StreamingStarted(true);
  6109. if (sysTrayStream) {
  6110. sysTrayStream->setText(QTStr("Basic.Main.StopStreaming"));
  6111. sysTrayStream->setEnabled(true);
  6112. }
  6113. ui->statusbar->StreamDelayStarting(sec);
  6114. OnActivate();
  6115. }
  6116. void OBSBasic::StreamDelayStopping(int sec)
  6117. {
  6118. emit StreamingStopped(true);
  6119. if (sysTrayStream) {
  6120. sysTrayStream->setText(QTStr("Basic.Main.StartStreaming"));
  6121. sysTrayStream->setEnabled(true);
  6122. }
  6123. ui->statusbar->StreamDelayStopping(sec);
  6124. OnEvent(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6125. }
  6126. void OBSBasic::StreamingStart()
  6127. {
  6128. emit StreamingStarted();
  6129. OBSOutputAutoRelease output = obs_frontend_get_streaming_output();
  6130. ui->statusbar->StreamStarted(output);
  6131. if (sysTrayStream) {
  6132. sysTrayStream->setText(QTStr("Basic.Main.StopStreaming"));
  6133. sysTrayStream->setEnabled(true);
  6134. }
  6135. #ifdef YOUTUBE_ENABLED
  6136. if (!autoStartBroadcast) {
  6137. // get a current stream key
  6138. obs_service_t *service_obj = GetService();
  6139. OBSDataAutoRelease settings =
  6140. obs_service_get_settings(service_obj);
  6141. std::string key = obs_data_get_string(settings, "stream_id");
  6142. if (!key.empty() && !youtubeStreamCheckThread) {
  6143. youtubeStreamCheckThread = CreateQThread(
  6144. [this, key] { YoutubeStreamCheck(key); });
  6145. youtubeStreamCheckThread->setObjectName(
  6146. "YouTubeStreamCheckThread");
  6147. youtubeStreamCheckThread->start();
  6148. }
  6149. }
  6150. #endif
  6151. OnEvent(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  6152. OnActivate();
  6153. #ifdef YOUTUBE_ENABLED
  6154. if (YouTubeAppDock::IsYTServiceSelected())
  6155. youtubeAppDock->IngestionStarted();
  6156. #endif
  6157. blog(LOG_INFO, STREAMING_START);
  6158. }
  6159. void OBSBasic::StreamStopping()
  6160. {
  6161. emit StreamingStopping();
  6162. if (sysTrayStream)
  6163. sysTrayStream->setText(QTStr("Basic.Main.StoppingStreaming"));
  6164. streamingStopping = true;
  6165. OnEvent(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6166. }
  6167. void OBSBasic::StreamingStop(int code, QString last_error)
  6168. {
  6169. const char *errorDescription = "";
  6170. DStr errorMessage;
  6171. bool use_last_error = false;
  6172. bool encode_error = false;
  6173. switch (code) {
  6174. case OBS_OUTPUT_BAD_PATH:
  6175. errorDescription = Str("Output.ConnectFail.BadPath");
  6176. break;
  6177. case OBS_OUTPUT_CONNECT_FAILED:
  6178. use_last_error = true;
  6179. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  6180. break;
  6181. case OBS_OUTPUT_INVALID_STREAM:
  6182. errorDescription = Str("Output.ConnectFail.InvalidStream");
  6183. break;
  6184. case OBS_OUTPUT_ENCODE_ERROR:
  6185. encode_error = true;
  6186. break;
  6187. case OBS_OUTPUT_HDR_DISABLED:
  6188. errorDescription = Str("Output.ConnectFail.HdrDisabled");
  6189. break;
  6190. default:
  6191. case OBS_OUTPUT_ERROR:
  6192. use_last_error = true;
  6193. errorDescription = Str("Output.ConnectFail.Error");
  6194. break;
  6195. case OBS_OUTPUT_DISCONNECTED:
  6196. /* doesn't happen if output is set to reconnect. note that
  6197. * reconnects are handled in the output, not in the UI */
  6198. use_last_error = true;
  6199. errorDescription = Str("Output.ConnectFail.Disconnected");
  6200. }
  6201. if (use_last_error && !last_error.isEmpty())
  6202. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6203. QT_TO_UTF8(last_error));
  6204. else
  6205. dstr_copy(errorMessage, errorDescription);
  6206. ui->statusbar->StreamStopped();
  6207. emit StreamingStopped();
  6208. if (sysTrayStream) {
  6209. sysTrayStream->setText(QTStr("Basic.Main.StartStreaming"));
  6210. sysTrayStream->setEnabled(true);
  6211. }
  6212. streamingStopping = false;
  6213. OnEvent(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  6214. OnDeactivate();
  6215. #ifdef YOUTUBE_ENABLED
  6216. if (YouTubeAppDock::IsYTServiceSelected())
  6217. youtubeAppDock->IngestionStopped();
  6218. #endif
  6219. blog(LOG_INFO, STREAMING_STOP);
  6220. if (encode_error) {
  6221. QString msg =
  6222. last_error.isEmpty()
  6223. ? QTStr("Output.StreamEncodeError.Msg")
  6224. : QTStr("Output.StreamEncodeError.Msg.LastError")
  6225. .arg(last_error);
  6226. OBSMessageBox::information(
  6227. this, QTStr("Output.StreamEncodeError.Title"), msg);
  6228. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6229. OBSMessageBox::information(this,
  6230. QTStr("Output.ConnectFail.Title"),
  6231. QT_UTF8(errorMessage));
  6232. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6233. SysTrayNotify(QT_UTF8(errorDescription),
  6234. QSystemTrayIcon::Warning);
  6235. }
  6236. // Reset broadcast button state/text
  6237. if (!broadcastActive)
  6238. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  6239. }
  6240. void OBSBasic::AutoRemux(QString input, bool no_show)
  6241. {
  6242. auto config = Config();
  6243. bool autoRemux = config_get_bool(config, "Video", "AutoRemux");
  6244. if (!autoRemux)
  6245. return;
  6246. bool isSimpleMode = false;
  6247. const char *mode = config_get_string(config, "Output", "Mode");
  6248. if (!mode) {
  6249. isSimpleMode = true;
  6250. } else {
  6251. isSimpleMode = strcmp(mode, "Simple") == 0;
  6252. }
  6253. if (!isSimpleMode) {
  6254. const char *recType =
  6255. config_get_string(config, "AdvOut", "RecType");
  6256. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  6257. if (ffmpegOutput)
  6258. return;
  6259. }
  6260. if (input.isEmpty())
  6261. return;
  6262. QFileInfo fi(input);
  6263. QString suffix = fi.suffix();
  6264. /* do not remux if lossless */
  6265. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  6266. return;
  6267. }
  6268. QString path = fi.path();
  6269. QString output = input;
  6270. output.resize(output.size() - suffix.size());
  6271. const obs_encoder_t *videoEncoder =
  6272. obs_output_get_video_encoder(outputHandler->fileOutput);
  6273. const char *vCodecName = obs_encoder_get_codec(videoEncoder);
  6274. const char *format = config_get_string(
  6275. config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2");
  6276. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6277. const obs_encoder_t *audioEncoder =
  6278. obs_output_get_audio_encoder(outputHandler->fileOutput, 0);
  6279. const char *aCodecName = obs_encoder_get_codec(audioEncoder);
  6280. bool audio_is_pcm = strncmp(aCodecName, "pcm", 3) == 0;
  6281. /* FFmpeg <= 6.0 cannot remux AV1+PCM into any supported format. */
  6282. if (audio_is_pcm && strcmp(vCodecName, "av1") == 0)
  6283. return;
  6284. #endif
  6285. /* Retain original container for fMP4/fMOV */
  6286. if (strncmp(format, "fragmented", 10) == 0) {
  6287. output += "remuxed." + suffix;
  6288. } else if (strcmp(vCodecName, "prores") == 0) {
  6289. output += "mov";
  6290. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6291. } else if (audio_is_pcm) {
  6292. output += "mov";
  6293. #endif
  6294. } else {
  6295. output += "mp4";
  6296. }
  6297. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  6298. if (!no_show)
  6299. remux->show();
  6300. remux->AutoRemux(input, output);
  6301. }
  6302. void OBSBasic::StartRecording()
  6303. {
  6304. if (outputHandler->RecordingActive())
  6305. return;
  6306. if (disableOutputsRef)
  6307. return;
  6308. if (!OutputPathValid()) {
  6309. OutputPathInvalidMessage();
  6310. return;
  6311. }
  6312. if (!IsFFmpegOutputToURL() && LowDiskSpace()) {
  6313. DiskSpaceMessage();
  6314. return;
  6315. }
  6316. OnEvent(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  6317. SaveProject();
  6318. outputHandler->StartRecording();
  6319. }
  6320. void OBSBasic::RecordStopping()
  6321. {
  6322. emit RecordingStopping();
  6323. if (sysTrayRecord)
  6324. sysTrayRecord->setText(QTStr("Basic.Main.StoppingRecording"));
  6325. recordingStopping = true;
  6326. OnEvent(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  6327. }
  6328. void OBSBasic::StopRecording()
  6329. {
  6330. SaveProject();
  6331. if (outputHandler->RecordingActive())
  6332. outputHandler->StopRecording(recordingStopping);
  6333. OnDeactivate();
  6334. }
  6335. void OBSBasic::RecordingStart()
  6336. {
  6337. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  6338. emit RecordingStarted(isRecordingPausable);
  6339. if (sysTrayRecord)
  6340. sysTrayRecord->setText(QTStr("Basic.Main.StopRecording"));
  6341. recordingStopping = false;
  6342. OnEvent(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  6343. if (!diskFullTimer->isActive())
  6344. diskFullTimer->start(1000);
  6345. OnActivate();
  6346. blog(LOG_INFO, RECORDING_START);
  6347. }
  6348. void OBSBasic::RecordingStop(int code, QString last_error)
  6349. {
  6350. ui->statusbar->RecordingStopped();
  6351. emit RecordingStopped();
  6352. if (sysTrayRecord)
  6353. sysTrayRecord->setText(QTStr("Basic.Main.StartRecording"));
  6354. blog(LOG_INFO, RECORDING_STOP);
  6355. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6356. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6357. QTStr("Output.RecordFail.Unsupported"));
  6358. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  6359. QString msg =
  6360. last_error.isEmpty()
  6361. ? QTStr("Output.RecordError.EncodeErrorMsg")
  6362. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  6363. .arg(last_error);
  6364. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  6365. msg);
  6366. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6367. OBSMessageBox::warning(this,
  6368. QTStr("Output.RecordNoSpace.Title"),
  6369. QTStr("Output.RecordNoSpace.Msg"));
  6370. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6371. const char *errorDescription;
  6372. DStr errorMessage;
  6373. bool use_last_error = true;
  6374. errorDescription = Str("Output.RecordError.Msg");
  6375. if (use_last_error && !last_error.isEmpty())
  6376. dstr_printf(errorMessage, "%s<br><br>%s",
  6377. errorDescription, QT_TO_UTF8(last_error));
  6378. else
  6379. dstr_copy(errorMessage, errorDescription);
  6380. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6381. QT_UTF8(errorMessage));
  6382. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6383. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6384. QSystemTrayIcon::Warning);
  6385. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6386. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6387. QSystemTrayIcon::Warning);
  6388. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6389. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6390. QSystemTrayIcon::Warning);
  6391. } else if (code == OBS_OUTPUT_SUCCESS) {
  6392. if (outputHandler) {
  6393. std::string path = outputHandler->lastRecordingPath;
  6394. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6395. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  6396. }
  6397. }
  6398. OnEvent(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  6399. if (diskFullTimer->isActive())
  6400. diskFullTimer->stop();
  6401. AutoRemux(outputHandler->lastRecordingPath.c_str());
  6402. OnDeactivate();
  6403. }
  6404. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  6405. {
  6406. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6407. ShowStatusBarMessage(str.arg(lastRecordingPath));
  6408. AutoRemux(lastRecordingPath, true);
  6409. }
  6410. void OBSBasic::ShowReplayBufferPauseWarning()
  6411. {
  6412. auto msgBox = []() {
  6413. QMessageBox msgbox(App()->GetMainWindow());
  6414. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  6415. "PauseWarning.Title"));
  6416. msgbox.setText(QTStr("Output.ReplayBuffer."
  6417. "PauseWarning.Text"));
  6418. msgbox.setIcon(QMessageBox::Icon::Information);
  6419. msgbox.addButton(QMessageBox::Ok);
  6420. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  6421. msgbox.setCheckBox(cb);
  6422. msgbox.exec();
  6423. if (cb->isChecked()) {
  6424. config_set_bool(App()->GlobalConfig(), "General",
  6425. "WarnedAboutReplayBufferPausing", true);
  6426. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  6427. }
  6428. };
  6429. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  6430. "WarnedAboutReplayBufferPausing");
  6431. if (!warned) {
  6432. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  6433. Q_ARG(VoidFunc, msgBox));
  6434. }
  6435. }
  6436. void OBSBasic::StartReplayBuffer()
  6437. {
  6438. if (!outputHandler || !outputHandler->replayBuffer)
  6439. return;
  6440. if (outputHandler->ReplayBufferActive())
  6441. return;
  6442. if (disableOutputsRef)
  6443. return;
  6444. if (!UIValidation::NoSourcesConfirmation(this))
  6445. return;
  6446. if (!OutputPathValid()) {
  6447. OutputPathInvalidMessage();
  6448. return;
  6449. }
  6450. if (LowDiskSpace()) {
  6451. DiskSpaceMessage();
  6452. return;
  6453. }
  6454. OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6455. SaveProject();
  6456. if (outputHandler->StartReplayBuffer() &&
  6457. os_atomic_load_bool(&recording_paused)) {
  6458. ShowReplayBufferPauseWarning();
  6459. }
  6460. }
  6461. void OBSBasic::ReplayBufferStopping()
  6462. {
  6463. if (!outputHandler || !outputHandler->replayBuffer)
  6464. return;
  6465. emit ReplayBufStopping();
  6466. if (sysTrayReplayBuffer)
  6467. sysTrayReplayBuffer->setText(
  6468. QTStr("Basic.Main.StoppingReplayBuffer"));
  6469. replayBufferStopping = true;
  6470. OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6471. }
  6472. void OBSBasic::StopReplayBuffer()
  6473. {
  6474. if (!outputHandler || !outputHandler->replayBuffer)
  6475. return;
  6476. SaveProject();
  6477. if (outputHandler->ReplayBufferActive())
  6478. outputHandler->StopReplayBuffer(replayBufferStopping);
  6479. OnDeactivate();
  6480. }
  6481. void OBSBasic::ReplayBufferStart()
  6482. {
  6483. if (!outputHandler || !outputHandler->replayBuffer)
  6484. return;
  6485. emit ReplayBufStarted();
  6486. if (sysTrayReplayBuffer)
  6487. sysTrayReplayBuffer->setText(
  6488. QTStr("Basic.Main.StopReplayBuffer"));
  6489. replayBufferStopping = false;
  6490. OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6491. OnActivate();
  6492. blog(LOG_INFO, REPLAY_BUFFER_START);
  6493. }
  6494. void OBSBasic::ReplayBufferSave()
  6495. {
  6496. if (!outputHandler || !outputHandler->replayBuffer)
  6497. return;
  6498. if (!outputHandler->ReplayBufferActive())
  6499. return;
  6500. calldata_t cd = {0};
  6501. proc_handler_t *ph =
  6502. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6503. proc_handler_call(ph, "save", &cd);
  6504. calldata_free(&cd);
  6505. }
  6506. void OBSBasic::ReplayBufferSaved()
  6507. {
  6508. if (!outputHandler || !outputHandler->replayBuffer)
  6509. return;
  6510. if (!outputHandler->ReplayBufferActive())
  6511. return;
  6512. calldata_t cd = {0};
  6513. proc_handler_t *ph =
  6514. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6515. proc_handler_call(ph, "get_last_replay", &cd);
  6516. std::string path = calldata_string(&cd, "path");
  6517. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo")
  6518. .arg(QT_UTF8(path.c_str()));
  6519. ShowStatusBarMessage(msg);
  6520. lastReplay = path;
  6521. calldata_free(&cd);
  6522. OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6523. AutoRemux(QT_UTF8(path.c_str()));
  6524. }
  6525. void OBSBasic::ReplayBufferStop(int code)
  6526. {
  6527. if (!outputHandler || !outputHandler->replayBuffer)
  6528. return;
  6529. emit ReplayBufStopped();
  6530. if (sysTrayReplayBuffer)
  6531. sysTrayReplayBuffer->setText(
  6532. QTStr("Basic.Main.StartReplayBuffer"));
  6533. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6534. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6535. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6536. QTStr("Output.RecordFail.Unsupported"));
  6537. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6538. OBSMessageBox::warning(this,
  6539. QTStr("Output.RecordNoSpace.Title"),
  6540. QTStr("Output.RecordNoSpace.Msg"));
  6541. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6542. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6543. QTStr("Output.RecordError.Msg"));
  6544. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6545. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6546. QSystemTrayIcon::Warning);
  6547. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6548. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6549. QSystemTrayIcon::Warning);
  6550. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6551. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6552. QSystemTrayIcon::Warning);
  6553. }
  6554. OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6555. OnDeactivate();
  6556. }
  6557. void OBSBasic::StartVirtualCam()
  6558. {
  6559. if (!outputHandler || !outputHandler->virtualCam)
  6560. return;
  6561. if (outputHandler->VirtualCamActive())
  6562. return;
  6563. if (disableOutputsRef)
  6564. return;
  6565. SaveProject();
  6566. outputHandler->StartVirtualCam();
  6567. }
  6568. void OBSBasic::StopVirtualCam()
  6569. {
  6570. if (!outputHandler || !outputHandler->virtualCam)
  6571. return;
  6572. SaveProject();
  6573. if (outputHandler->VirtualCamActive())
  6574. outputHandler->StopVirtualCam();
  6575. OnDeactivate();
  6576. }
  6577. void OBSBasic::OnVirtualCamStart()
  6578. {
  6579. if (!outputHandler || !outputHandler->virtualCam)
  6580. return;
  6581. emit VirtualCamStarted();
  6582. if (sysTrayVirtualCam)
  6583. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6584. OnEvent(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6585. OnActivate();
  6586. blog(LOG_INFO, VIRTUAL_CAM_START);
  6587. }
  6588. void OBSBasic::OnVirtualCamStop(int)
  6589. {
  6590. if (!outputHandler || !outputHandler->virtualCam)
  6591. return;
  6592. emit VirtualCamStopped();
  6593. if (sysTrayVirtualCam)
  6594. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6595. OnEvent(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6596. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6597. OnDeactivate();
  6598. if (!restartingVCam)
  6599. return;
  6600. /* Restarting needs to be delayed to make sure that the virtual camera
  6601. * implementation is stopped and avoid race condition. */
  6602. QTimer::singleShot(100, this, &OBSBasic::RestartingVirtualCam);
  6603. }
  6604. void OBSBasic::StreamActionTriggered()
  6605. {
  6606. if (outputHandler->StreamingActive()) {
  6607. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6608. "WarnBeforeStoppingStream");
  6609. #ifdef YOUTUBE_ENABLED
  6610. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6611. autoStopBroadcast) {
  6612. QMessageBox::StandardButton button = OBSMessageBox::question(
  6613. this, QTStr("ConfirmStop.Title"),
  6614. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6615. QMessageBox::Yes | QMessageBox::No,
  6616. QMessageBox::No);
  6617. if (button == QMessageBox::No)
  6618. return;
  6619. confirm = false;
  6620. }
  6621. #endif
  6622. if (confirm && isVisible()) {
  6623. QMessageBox::StandardButton button =
  6624. OBSMessageBox::question(
  6625. this, QTStr("ConfirmStop.Title"),
  6626. QTStr("ConfirmStop.Text"),
  6627. QMessageBox::Yes | QMessageBox::No,
  6628. QMessageBox::No);
  6629. if (button == QMessageBox::No)
  6630. return;
  6631. }
  6632. StopStreaming();
  6633. } else {
  6634. if (!UIValidation::NoSourcesConfirmation(this))
  6635. return;
  6636. Auth *auth = GetAuth();
  6637. auto action =
  6638. (auth && auth->external())
  6639. ? StreamSettingsAction::ContinueStream
  6640. : UIValidation::StreamSettingsConfirmation(
  6641. this, service);
  6642. switch (action) {
  6643. case StreamSettingsAction::ContinueStream:
  6644. break;
  6645. case StreamSettingsAction::OpenSettings:
  6646. on_action_Settings_triggered();
  6647. return;
  6648. case StreamSettingsAction::Cancel:
  6649. return;
  6650. }
  6651. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6652. "WarnBeforeStartingStream");
  6653. bool bwtest = false;
  6654. if (this->auth) {
  6655. OBSDataAutoRelease settings =
  6656. obs_service_get_settings(service);
  6657. bwtest = obs_data_get_bool(settings, "bwtest");
  6658. // Disable confirmation if this is going to open broadcast setup
  6659. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6660. !broadcastActive)
  6661. confirm = false;
  6662. }
  6663. if (bwtest && isVisible()) {
  6664. QMessageBox::StandardButton button =
  6665. OBSMessageBox::question(
  6666. this, QTStr("ConfirmBWTest.Title"),
  6667. QTStr("ConfirmBWTest.Text"));
  6668. if (button == QMessageBox::No)
  6669. return;
  6670. } else if (confirm && isVisible()) {
  6671. QMessageBox::StandardButton button =
  6672. OBSMessageBox::question(
  6673. this, QTStr("ConfirmStart.Title"),
  6674. QTStr("ConfirmStart.Text"),
  6675. QMessageBox::Yes | QMessageBox::No,
  6676. QMessageBox::No);
  6677. if (button == QMessageBox::No)
  6678. return;
  6679. }
  6680. StartStreaming();
  6681. }
  6682. }
  6683. void OBSBasic::RecordActionTriggered()
  6684. {
  6685. if (outputHandler->RecordingActive()) {
  6686. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6687. "WarnBeforeStoppingRecord");
  6688. if (confirm && isVisible()) {
  6689. QMessageBox::StandardButton button =
  6690. OBSMessageBox::question(
  6691. this, QTStr("ConfirmStopRecord.Title"),
  6692. QTStr("ConfirmStopRecord.Text"),
  6693. QMessageBox::Yes | QMessageBox::No,
  6694. QMessageBox::No);
  6695. if (button == QMessageBox::No)
  6696. return;
  6697. }
  6698. StopRecording();
  6699. } else {
  6700. if (!UIValidation::NoSourcesConfirmation(this))
  6701. return;
  6702. StartRecording();
  6703. }
  6704. }
  6705. void OBSBasic::VirtualCamActionTriggered()
  6706. {
  6707. if (outputHandler->VirtualCamActive()) {
  6708. StopVirtualCam();
  6709. } else {
  6710. if (!UIValidation::NoSourcesConfirmation(this))
  6711. return;
  6712. StartVirtualCam();
  6713. }
  6714. }
  6715. void OBSBasic::OpenVirtualCamConfig()
  6716. {
  6717. OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(),
  6718. this);
  6719. connect(&dialog, &OBSBasicVCamConfig::Accepted, this,
  6720. &OBSBasic::UpdateVirtualCamConfig);
  6721. connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this,
  6722. &OBSBasic::RestartVirtualCam);
  6723. dialog.exec();
  6724. }
  6725. void log_vcam_changed(const VCamConfig &config, bool starting)
  6726. {
  6727. const char *action = starting ? "Starting" : "Changing";
  6728. switch (config.type) {
  6729. case VCamOutputType::Invalid:
  6730. break;
  6731. case VCamOutputType::ProgramView:
  6732. blog(LOG_INFO, "%s Virtual Camera output to Program", action);
  6733. break;
  6734. case VCamOutputType::PreviewOutput:
  6735. blog(LOG_INFO, "%s Virtual Camera output to Preview", action);
  6736. break;
  6737. case VCamOutputType::SceneOutput:
  6738. blog(LOG_INFO, "%s Virtual Camera output to Scene : %s", action,
  6739. config.scene.c_str());
  6740. break;
  6741. case VCamOutputType::SourceOutput:
  6742. blog(LOG_INFO, "%s Virtual Camera output to Source : %s",
  6743. action, config.source.c_str());
  6744. break;
  6745. }
  6746. }
  6747. void OBSBasic::UpdateVirtualCamConfig(const VCamConfig &config)
  6748. {
  6749. vcamConfig = config;
  6750. outputHandler->UpdateVirtualCamOutputSource();
  6751. log_vcam_changed(config, false);
  6752. }
  6753. void OBSBasic::RestartVirtualCam(const VCamConfig &config)
  6754. {
  6755. restartingVCam = true;
  6756. StopVirtualCam();
  6757. vcamConfig = config;
  6758. }
  6759. void OBSBasic::RestartingVirtualCam()
  6760. {
  6761. if (!restartingVCam)
  6762. return;
  6763. outputHandler->UpdateVirtualCamOutputSource();
  6764. StartVirtualCam();
  6765. restartingVCam = false;
  6766. }
  6767. void OBSBasic::on_actionHelpPortal_triggered()
  6768. {
  6769. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6770. QDesktopServices::openUrl(url);
  6771. }
  6772. void OBSBasic::on_actionWebsite_triggered()
  6773. {
  6774. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6775. QDesktopServices::openUrl(url);
  6776. }
  6777. void OBSBasic::on_actionDiscord_triggered()
  6778. {
  6779. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6780. QDesktopServices::openUrl(url);
  6781. }
  6782. void OBSBasic::on_actionShowWhatsNew_triggered()
  6783. {
  6784. #ifdef WHATSNEW_ENABLED
  6785. if (introCheckThread && introCheckThread->isRunning())
  6786. return;
  6787. if (!cef)
  6788. return;
  6789. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement", -1);
  6790. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  6791. connect(wnit, &WhatsNewInfoThread::Result, this,
  6792. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  6793. introCheckThread.reset(wnit);
  6794. introCheckThread->start();
  6795. #endif
  6796. }
  6797. void OBSBasic::on_actionReleaseNotes_triggered()
  6798. {
  6799. QString addr("https://github.com/obsproject/obs-studio/releases");
  6800. QUrl url(QString("%1/%2").arg(addr, obs_get_version_string()),
  6801. QUrl::TolerantMode);
  6802. QDesktopServices::openUrl(url);
  6803. }
  6804. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6805. {
  6806. char path[512];
  6807. int ret = GetConfigPath(path, 512, "obs-studio");
  6808. if (ret <= 0)
  6809. return;
  6810. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6811. }
  6812. void OBSBasic::on_actionShowProfileFolder_triggered()
  6813. {
  6814. char path[512];
  6815. int ret = GetProfilePath(path, 512, "");
  6816. if (ret <= 0)
  6817. return;
  6818. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6819. }
  6820. int OBSBasic::GetTopSelectedSourceItem()
  6821. {
  6822. QModelIndexList selectedItems =
  6823. ui->sources->selectionModel()->selectedIndexes();
  6824. return selectedItems.count() ? selectedItems[0].row() : -1;
  6825. }
  6826. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6827. {
  6828. return ui->sources->selectionModel()->selectedIndexes();
  6829. }
  6830. void OBSBasic::on_preview_customContextMenuRequested()
  6831. {
  6832. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6833. }
  6834. void OBSBasic::ProgramViewContextMenuRequested()
  6835. {
  6836. QMenu popup(this);
  6837. QPointer<QMenu> studioProgramProjector;
  6838. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6839. AddProjectorMenuMonitors(studioProgramProjector, this,
  6840. &OBSBasic::OpenStudioProgramProjector);
  6841. popup.addMenu(studioProgramProjector);
  6842. popup.addAction(QTStr("StudioProgramWindow"), this,
  6843. &OBSBasic::OpenStudioProgramWindow);
  6844. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6845. &OBSBasic::ScreenshotProgram);
  6846. popup.exec(QCursor::pos());
  6847. }
  6848. void OBSBasic::on_previewDisabledWidget_customContextMenuRequested()
  6849. {
  6850. QMenu popup(this);
  6851. delete previewProjectorMain;
  6852. QAction *action =
  6853. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6854. this, &OBSBasic::TogglePreview);
  6855. action->setCheckable(true);
  6856. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6857. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6858. AddProjectorMenuMonitors(previewProjectorMain, this,
  6859. &OBSBasic::OpenPreviewProjector);
  6860. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6861. &OBSBasic::OpenPreviewWindow);
  6862. popup.addMenu(previewProjectorMain);
  6863. popup.addAction(previewWindow);
  6864. popup.exec(QCursor::pos());
  6865. }
  6866. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6867. {
  6868. #ifndef _WIN32
  6869. /* Make sure all dialogs are safely and successfully closed before
  6870. * switching the always on top mode due to the fact that windows all
  6871. * have to be recreated, so queue the actual toggle to happen after
  6872. * all events related to closing the dialogs have finished */
  6873. CloseDialogs();
  6874. #endif
  6875. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6876. Qt::QueuedConnection);
  6877. }
  6878. void OBSBasic::ToggleAlwaysOnTop()
  6879. {
  6880. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6881. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6882. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6883. show();
  6884. }
  6885. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6886. {
  6887. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6888. if (strcmp(val, "10") == 0) {
  6889. num = 10;
  6890. den = 1;
  6891. } else if (strcmp(val, "20") == 0) {
  6892. num = 20;
  6893. den = 1;
  6894. } else if (strcmp(val, "24 NTSC") == 0) {
  6895. num = 24000;
  6896. den = 1001;
  6897. } else if (strcmp(val, "25 PAL") == 0) {
  6898. num = 25;
  6899. den = 1;
  6900. } else if (strcmp(val, "29.97") == 0) {
  6901. num = 30000;
  6902. den = 1001;
  6903. } else if (strcmp(val, "48") == 0) {
  6904. num = 48;
  6905. den = 1;
  6906. } else if (strcmp(val, "50 PAL") == 0) {
  6907. num = 50;
  6908. den = 1;
  6909. } else if (strcmp(val, "59.94") == 0) {
  6910. num = 60000;
  6911. den = 1001;
  6912. } else if (strcmp(val, "60") == 0) {
  6913. num = 60;
  6914. den = 1;
  6915. } else {
  6916. num = 30;
  6917. den = 1;
  6918. }
  6919. }
  6920. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6921. {
  6922. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6923. den = 1;
  6924. }
  6925. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6926. {
  6927. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6928. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6929. }
  6930. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6931. {
  6932. num = 1000000000;
  6933. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6934. }
  6935. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6936. {
  6937. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6938. if (type == 1) //"Integer"
  6939. GetFPSInteger(num, den);
  6940. else if (type == 2) //"Fraction"
  6941. GetFPSFraction(num, den);
  6942. /*
  6943. * else if (false) //"Nanoseconds", currently not implemented
  6944. * GetFPSNanoseconds(num, den);
  6945. */
  6946. else
  6947. GetFPSCommon(num, den);
  6948. }
  6949. config_t *OBSBasic::Config() const
  6950. {
  6951. return basicConfig;
  6952. }
  6953. #ifdef YOUTUBE_ENABLED
  6954. YouTubeAppDock *OBSBasic::GetYouTubeAppDock()
  6955. {
  6956. return youtubeAppDock;
  6957. }
  6958. #ifndef SEC_TO_NSEC
  6959. #define SEC_TO_NSEC 1000000000
  6960. #endif
  6961. void OBSBasic::NewYouTubeAppDock()
  6962. {
  6963. if (!cef_js_avail)
  6964. return;
  6965. /* make sure that the youtube app dock can't be immediately recreated.
  6966. * dumb hack. blame chromium. or this particular dock. or both. if CEF
  6967. * creates/destroys/creates a widget too quickly it can lead to a
  6968. * crash. */
  6969. uint64_t ts = os_gettime_ns();
  6970. if ((ts - lastYouTubeAppDockCreationTime) < (5ULL * SEC_TO_NSEC))
  6971. return;
  6972. lastYouTubeAppDockCreationTime = ts;
  6973. if (youtubeAppDock)
  6974. RemoveDockWidget(youtubeAppDock->objectName());
  6975. youtubeAppDock = new YouTubeAppDock("YouTube Live Control Panel");
  6976. }
  6977. void OBSBasic::DeleteYouTubeAppDock()
  6978. {
  6979. if (!cef_js_avail)
  6980. return;
  6981. if (youtubeAppDock)
  6982. RemoveDockWidget(youtubeAppDock->objectName());
  6983. youtubeAppDock = nullptr;
  6984. }
  6985. #endif
  6986. void OBSBasic::UpdateEditMenu()
  6987. {
  6988. QModelIndexList items = GetAllSelectedSourceItems();
  6989. int totalCount = items.count();
  6990. size_t filter_count = 0;
  6991. if (totalCount == 1) {
  6992. OBSSceneItem sceneItem =
  6993. ui->sources->Get(GetTopSelectedSourceItem());
  6994. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6995. filter_count = obs_source_filter_count(source);
  6996. }
  6997. bool allowPastingDuplicate = !!clipboard.size();
  6998. for (size_t i = clipboard.size(); i > 0; i--) {
  6999. const size_t idx = i - 1;
  7000. OBSWeakSource &weak = clipboard[idx].weak_source;
  7001. if (obs_weak_source_expired(weak)) {
  7002. clipboard.erase(clipboard.begin() + idx);
  7003. continue;
  7004. }
  7005. OBSSourceAutoRelease strong =
  7006. obs_weak_source_get_source(weak.Get());
  7007. if (allowPastingDuplicate &&
  7008. obs_source_get_output_flags(strong) &
  7009. OBS_SOURCE_DO_NOT_DUPLICATE)
  7010. allowPastingDuplicate = false;
  7011. }
  7012. int videoCount = 0;
  7013. bool canTransformMultiple = false;
  7014. for (int i = 0; i < totalCount; i++) {
  7015. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  7016. OBSSource source = obs_sceneitem_get_source(item);
  7017. const uint32_t flags = obs_source_get_output_flags(source);
  7018. const bool hasVideo = (flags & OBS_SOURCE_VIDEO) != 0;
  7019. if (hasVideo && !obs_sceneitem_locked(item))
  7020. canTransformMultiple = true;
  7021. if (hasVideo)
  7022. videoCount++;
  7023. }
  7024. const bool canTransformSingle = videoCount == 1 && totalCount == 1;
  7025. OBSSceneItem curItem = GetCurrentSceneItem();
  7026. bool locked = curItem && obs_sceneitem_locked(curItem);
  7027. ui->actionCopySource->setEnabled(totalCount > 0);
  7028. ui->actionEditTransform->setEnabled(canTransformSingle && !locked);
  7029. ui->actionCopyTransform->setEnabled(canTransformSingle);
  7030. ui->actionPasteTransform->setEnabled(
  7031. canTransformMultiple && hasCopiedTransform && videoCount > 0);
  7032. ui->actionCopyFilters->setEnabled(filter_count > 0);
  7033. ui->actionPasteFilters->setEnabled(
  7034. !obs_weak_source_expired(copyFiltersSource) && totalCount > 0);
  7035. ui->actionPasteRef->setEnabled(!!clipboard.size());
  7036. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  7037. ui->actionMoveUp->setEnabled(totalCount > 0);
  7038. ui->actionMoveDown->setEnabled(totalCount > 0);
  7039. ui->actionMoveToTop->setEnabled(totalCount > 0);
  7040. ui->actionMoveToBottom->setEnabled(totalCount > 0);
  7041. ui->actionResetTransform->setEnabled(canTransformMultiple);
  7042. ui->actionRotate90CW->setEnabled(canTransformMultiple);
  7043. ui->actionRotate90CCW->setEnabled(canTransformMultiple);
  7044. ui->actionRotate180->setEnabled(canTransformMultiple);
  7045. ui->actionFlipHorizontal->setEnabled(canTransformMultiple);
  7046. ui->actionFlipVertical->setEnabled(canTransformMultiple);
  7047. ui->actionFitToScreen->setEnabled(canTransformMultiple);
  7048. ui->actionStretchToScreen->setEnabled(canTransformMultiple);
  7049. ui->actionCenterToScreen->setEnabled(canTransformMultiple);
  7050. ui->actionVerticalCenter->setEnabled(canTransformMultiple);
  7051. ui->actionHorizontalCenter->setEnabled(canTransformMultiple);
  7052. }
  7053. void OBSBasic::on_actionEditTransform_triggered()
  7054. {
  7055. const auto item = GetCurrentSceneItem();
  7056. if (!item)
  7057. return;
  7058. CreateEditTransformWindow(item);
  7059. }
  7060. void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item)
  7061. {
  7062. if (transformWindow)
  7063. transformWindow->close();
  7064. transformWindow = new OBSBasicTransform(item, this);
  7065. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  7066. &OBSBasicTransform::OnSceneChanged);
  7067. transformWindow->show();
  7068. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  7069. }
  7070. void OBSBasic::on_actionCopyTransform_triggered()
  7071. {
  7072. OBSSceneItem item = GetCurrentSceneItem();
  7073. obs_sceneitem_get_info2(item, &copiedTransformInfo);
  7074. obs_sceneitem_get_crop(item, &copiedCropInfo);
  7075. ui->actionPasteTransform->setEnabled(true);
  7076. hasCopiedTransform = true;
  7077. }
  7078. void undo_redo(const std::string &data)
  7079. {
  7080. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  7081. OBSSourceAutoRelease source =
  7082. obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid"));
  7083. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  7084. ->SetCurrentScene(source.Get(), true);
  7085. obs_scene_load_transform_states(data.c_str());
  7086. }
  7087. void OBSBasic::on_actionPasteTransform_triggered()
  7088. {
  7089. OBSDataAutoRelease wrapper =
  7090. obs_scene_save_transform_states(GetCurrentScene(), false);
  7091. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  7092. if (!obs_sceneitem_selected(item))
  7093. return true;
  7094. if (obs_sceneitem_locked(item))
  7095. return true;
  7096. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  7097. obs_sceneitem_defer_update_begin(item);
  7098. obs_sceneitem_set_info2(item, &main->copiedTransformInfo);
  7099. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  7100. obs_sceneitem_defer_update_end(item);
  7101. return true;
  7102. };
  7103. obs_scene_enum_items(GetCurrentScene(), func, this);
  7104. OBSDataAutoRelease rwrapper =
  7105. obs_scene_save_transform_states(GetCurrentScene(), false);
  7106. std::string undo_data(obs_data_get_json(wrapper));
  7107. std::string redo_data(obs_data_get_json(rwrapper));
  7108. undo_s.add_action(
  7109. QTStr("Undo.Transform.Paste")
  7110. .arg(obs_source_get_name(GetCurrentSceneSource())),
  7111. undo_redo, undo_redo, undo_data, redo_data);
  7112. }
  7113. static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *)
  7114. {
  7115. if (obs_sceneitem_is_group(item))
  7116. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  7117. if (!obs_sceneitem_selected(item))
  7118. return true;
  7119. if (obs_sceneitem_locked(item))
  7120. return true;
  7121. obs_sceneitem_defer_update_begin(item);
  7122. obs_transform_info info;
  7123. vec2_set(&info.pos, 0.0f, 0.0f);
  7124. vec2_set(&info.scale, 1.0f, 1.0f);
  7125. info.rot = 0.0f;
  7126. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  7127. info.bounds_type = OBS_BOUNDS_NONE;
  7128. info.bounds_alignment = OBS_ALIGN_CENTER;
  7129. info.crop_to_bounds = false;
  7130. vec2_set(&info.bounds, 0.0f, 0.0f);
  7131. obs_sceneitem_set_info2(item, &info);
  7132. obs_sceneitem_crop crop = {};
  7133. obs_sceneitem_set_crop(item, &crop);
  7134. obs_sceneitem_defer_update_end(item);
  7135. return true;
  7136. }
  7137. void OBSBasic::on_actionResetTransform_triggered()
  7138. {
  7139. OBSScene scene = GetCurrentScene();
  7140. OBSDataAutoRelease wrapper =
  7141. obs_scene_save_transform_states(scene, false);
  7142. obs_scene_enum_items(scene, reset_tr, nullptr);
  7143. OBSDataAutoRelease rwrapper =
  7144. obs_scene_save_transform_states(scene, false);
  7145. std::string undo_data(obs_data_get_json(wrapper));
  7146. std::string redo_data(obs_data_get_json(rwrapper));
  7147. undo_s.add_action(
  7148. QTStr("Undo.Transform.Reset")
  7149. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  7150. undo_redo, undo_redo, undo_data, redo_data);
  7151. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  7152. }
  7153. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  7154. {
  7155. matrix4 boxTransform;
  7156. obs_sceneitem_get_box_transform(item, &boxTransform);
  7157. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  7158. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  7159. auto GetMinPos = [&](float x, float y) {
  7160. vec3 pos;
  7161. vec3_set(&pos, x, y, 0.0f);
  7162. vec3_transform(&pos, &pos, &boxTransform);
  7163. vec3_min(&tl, &tl, &pos);
  7164. vec3_max(&br, &br, &pos);
  7165. };
  7166. GetMinPos(0.0f, 0.0f);
  7167. GetMinPos(1.0f, 0.0f);
  7168. GetMinPos(0.0f, 1.0f);
  7169. GetMinPos(1.0f, 1.0f);
  7170. }
  7171. static vec3 GetItemTL(obs_sceneitem_t *item)
  7172. {
  7173. vec3 tl, br;
  7174. GetItemBox(item, tl, br);
  7175. return tl;
  7176. }
  7177. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  7178. {
  7179. vec3 newTL;
  7180. vec2 pos;
  7181. obs_sceneitem_get_pos(item, &pos);
  7182. newTL = GetItemTL(item);
  7183. pos.x += tl.x - newTL.x;
  7184. pos.y += tl.y - newTL.y;
  7185. obs_sceneitem_set_pos(item, &pos);
  7186. }
  7187. static bool RotateSelectedSources(obs_scene_t * /* scene */,
  7188. obs_sceneitem_t *item, void *param)
  7189. {
  7190. if (obs_sceneitem_is_group(item))
  7191. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  7192. param);
  7193. if (!obs_sceneitem_selected(item))
  7194. return true;
  7195. if (obs_sceneitem_locked(item))
  7196. return true;
  7197. float rot = *reinterpret_cast<float *>(param);
  7198. vec3 tl = GetItemTL(item);
  7199. rot += obs_sceneitem_get_rot(item);
  7200. if (rot >= 360.0f)
  7201. rot -= 360.0f;
  7202. else if (rot <= -360.0f)
  7203. rot += 360.0f;
  7204. obs_sceneitem_set_rot(item, rot);
  7205. obs_sceneitem_force_update_transform(item);
  7206. SetItemTL(item, tl);
  7207. return true;
  7208. };
  7209. void OBSBasic::on_actionRotate90CW_triggered()
  7210. {
  7211. float f90CW = 90.0f;
  7212. OBSDataAutoRelease wrapper =
  7213. obs_scene_save_transform_states(GetCurrentScene(), false);
  7214. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  7215. OBSDataAutoRelease rwrapper =
  7216. obs_scene_save_transform_states(GetCurrentScene(), false);
  7217. std::string undo_data(obs_data_get_json(wrapper));
  7218. std::string redo_data(obs_data_get_json(rwrapper));
  7219. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7220. .arg(obs_source_get_name(obs_scene_get_source(
  7221. GetCurrentScene()))),
  7222. undo_redo, undo_redo, undo_data, redo_data);
  7223. }
  7224. void OBSBasic::on_actionRotate90CCW_triggered()
  7225. {
  7226. float f90CCW = -90.0f;
  7227. OBSDataAutoRelease wrapper =
  7228. obs_scene_save_transform_states(GetCurrentScene(), false);
  7229. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  7230. OBSDataAutoRelease rwrapper =
  7231. obs_scene_save_transform_states(GetCurrentScene(), false);
  7232. std::string undo_data(obs_data_get_json(wrapper));
  7233. std::string redo_data(obs_data_get_json(rwrapper));
  7234. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7235. .arg(obs_source_get_name(obs_scene_get_source(
  7236. GetCurrentScene()))),
  7237. undo_redo, undo_redo, undo_data, redo_data);
  7238. }
  7239. void OBSBasic::on_actionRotate180_triggered()
  7240. {
  7241. float f180 = 180.0f;
  7242. OBSDataAutoRelease wrapper =
  7243. obs_scene_save_transform_states(GetCurrentScene(), false);
  7244. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  7245. OBSDataAutoRelease rwrapper =
  7246. obs_scene_save_transform_states(GetCurrentScene(), false);
  7247. std::string undo_data(obs_data_get_json(wrapper));
  7248. std::string redo_data(obs_data_get_json(rwrapper));
  7249. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7250. .arg(obs_source_get_name(obs_scene_get_source(
  7251. GetCurrentScene()))),
  7252. undo_redo, undo_redo, undo_data, redo_data);
  7253. }
  7254. static bool MultiplySelectedItemScale(obs_scene_t * /* scene */,
  7255. obs_sceneitem_t *item, void *param)
  7256. {
  7257. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  7258. if (obs_sceneitem_is_group(item))
  7259. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  7260. param);
  7261. if (!obs_sceneitem_selected(item))
  7262. return true;
  7263. if (obs_sceneitem_locked(item))
  7264. return true;
  7265. vec3 tl = GetItemTL(item);
  7266. vec2 scale;
  7267. obs_sceneitem_get_scale(item, &scale);
  7268. vec2_mul(&scale, &scale, &mul);
  7269. obs_sceneitem_set_scale(item, &scale);
  7270. obs_sceneitem_force_update_transform(item);
  7271. SetItemTL(item, tl);
  7272. return true;
  7273. }
  7274. void OBSBasic::on_actionFlipHorizontal_triggered()
  7275. {
  7276. vec2 scale;
  7277. vec2_set(&scale, -1.0f, 1.0f);
  7278. OBSDataAutoRelease wrapper =
  7279. obs_scene_save_transform_states(GetCurrentScene(), false);
  7280. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7281. &scale);
  7282. OBSDataAutoRelease rwrapper =
  7283. obs_scene_save_transform_states(GetCurrentScene(), false);
  7284. std::string undo_data(obs_data_get_json(wrapper));
  7285. std::string redo_data(obs_data_get_json(rwrapper));
  7286. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  7287. .arg(obs_source_get_name(obs_scene_get_source(
  7288. GetCurrentScene()))),
  7289. undo_redo, undo_redo, undo_data, redo_data);
  7290. }
  7291. void OBSBasic::on_actionFlipVertical_triggered()
  7292. {
  7293. vec2 scale;
  7294. vec2_set(&scale, 1.0f, -1.0f);
  7295. OBSDataAutoRelease wrapper =
  7296. obs_scene_save_transform_states(GetCurrentScene(), false);
  7297. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7298. &scale);
  7299. OBSDataAutoRelease rwrapper =
  7300. obs_scene_save_transform_states(GetCurrentScene(), false);
  7301. std::string undo_data(obs_data_get_json(wrapper));
  7302. std::string redo_data(obs_data_get_json(rwrapper));
  7303. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  7304. .arg(obs_source_get_name(obs_scene_get_source(
  7305. GetCurrentScene()))),
  7306. undo_redo, undo_redo, undo_data, redo_data);
  7307. }
  7308. static bool CenterAlignSelectedItems(obs_scene_t * /* scene */,
  7309. obs_sceneitem_t *item, void *param)
  7310. {
  7311. obs_bounds_type boundsType =
  7312. *reinterpret_cast<obs_bounds_type *>(param);
  7313. if (obs_sceneitem_is_group(item))
  7314. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  7315. param);
  7316. if (!obs_sceneitem_selected(item))
  7317. return true;
  7318. if (obs_sceneitem_locked(item))
  7319. return true;
  7320. obs_video_info ovi;
  7321. obs_get_video_info(&ovi);
  7322. obs_transform_info itemInfo;
  7323. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  7324. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  7325. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  7326. itemInfo.rot = 0.0f;
  7327. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  7328. float(ovi.base_height));
  7329. itemInfo.bounds_type = boundsType;
  7330. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  7331. itemInfo.crop_to_bounds = obs_sceneitem_get_bounds_crop(item);
  7332. obs_sceneitem_set_info2(item, &itemInfo);
  7333. return true;
  7334. }
  7335. void OBSBasic::on_actionFitToScreen_triggered()
  7336. {
  7337. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  7338. OBSDataAutoRelease wrapper =
  7339. obs_scene_save_transform_states(GetCurrentScene(), false);
  7340. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7341. &boundsType);
  7342. OBSDataAutoRelease rwrapper =
  7343. obs_scene_save_transform_states(GetCurrentScene(), false);
  7344. std::string undo_data(obs_data_get_json(wrapper));
  7345. std::string redo_data(obs_data_get_json(rwrapper));
  7346. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  7347. .arg(obs_source_get_name(obs_scene_get_source(
  7348. GetCurrentScene()))),
  7349. undo_redo, undo_redo, undo_data, redo_data);
  7350. }
  7351. void OBSBasic::on_actionStretchToScreen_triggered()
  7352. {
  7353. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  7354. OBSDataAutoRelease wrapper =
  7355. obs_scene_save_transform_states(GetCurrentScene(), false);
  7356. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7357. &boundsType);
  7358. OBSDataAutoRelease rwrapper =
  7359. obs_scene_save_transform_states(GetCurrentScene(), false);
  7360. std::string undo_data(obs_data_get_json(wrapper));
  7361. std::string redo_data(obs_data_get_json(rwrapper));
  7362. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  7363. .arg(obs_source_get_name(obs_scene_get_source(
  7364. GetCurrentScene()))),
  7365. undo_redo, undo_redo, undo_data, redo_data);
  7366. }
  7367. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  7368. {
  7369. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  7370. if (!selectedItems.count())
  7371. return;
  7372. vector<OBSSceneItem> items;
  7373. // Filter out items that have no size
  7374. for (int x = 0; x < selectedItems.count(); x++) {
  7375. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  7376. obs_transform_info oti;
  7377. obs_sceneitem_get_info2(item, &oti);
  7378. obs_source_t *source = obs_sceneitem_get_source(item);
  7379. float width = float(obs_source_get_width(source)) * oti.scale.x;
  7380. float height =
  7381. float(obs_source_get_height(source)) * oti.scale.y;
  7382. if (width == 0.0f || height == 0.0f)
  7383. continue;
  7384. items.emplace_back(item);
  7385. }
  7386. if (!items.size())
  7387. return;
  7388. // Get center x, y coordinates of items
  7389. vec3 center;
  7390. float top = M_INFINITE;
  7391. float left = M_INFINITE;
  7392. float right = 0.0f;
  7393. float bottom = 0.0f;
  7394. for (auto &item : items) {
  7395. vec3 tl, br;
  7396. GetItemBox(item, tl, br);
  7397. left = std::min(tl.x, left);
  7398. top = std::min(tl.y, top);
  7399. right = std::max(br.x, right);
  7400. bottom = std::max(br.y, bottom);
  7401. }
  7402. center.x = (right + left) / 2.0f;
  7403. center.y = (top + bottom) / 2.0f;
  7404. center.z = 0.0f;
  7405. // Get coordinates of screen center
  7406. obs_video_info ovi;
  7407. obs_get_video_info(&ovi);
  7408. vec3 screenCenter;
  7409. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  7410. 0.0f);
  7411. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  7412. // Calculate difference between screen center and item center
  7413. vec3 offset;
  7414. vec3_sub(&offset, &screenCenter, &center);
  7415. // Shift items by offset
  7416. for (auto &item : items) {
  7417. vec3 tl, br;
  7418. GetItemBox(item, tl, br);
  7419. vec3_add(&tl, &tl, &offset);
  7420. vec3 itemTL = GetItemTL(item);
  7421. if (centerType == CenterType::Vertical)
  7422. tl.x = itemTL.x;
  7423. else if (centerType == CenterType::Horizontal)
  7424. tl.y = itemTL.y;
  7425. SetItemTL(item, tl);
  7426. }
  7427. }
  7428. void OBSBasic::on_actionCenterToScreen_triggered()
  7429. {
  7430. CenterType centerType = CenterType::Scene;
  7431. OBSDataAutoRelease wrapper =
  7432. obs_scene_save_transform_states(GetCurrentScene(), false);
  7433. CenterSelectedSceneItems(centerType);
  7434. OBSDataAutoRelease rwrapper =
  7435. obs_scene_save_transform_states(GetCurrentScene(), false);
  7436. std::string undo_data(obs_data_get_json(wrapper));
  7437. std::string redo_data(obs_data_get_json(rwrapper));
  7438. undo_s.add_action(QTStr("Undo.Transform.Center")
  7439. .arg(obs_source_get_name(obs_scene_get_source(
  7440. GetCurrentScene()))),
  7441. undo_redo, undo_redo, undo_data, redo_data);
  7442. }
  7443. void OBSBasic::on_actionVerticalCenter_triggered()
  7444. {
  7445. CenterType centerType = CenterType::Vertical;
  7446. OBSDataAutoRelease wrapper =
  7447. obs_scene_save_transform_states(GetCurrentScene(), false);
  7448. CenterSelectedSceneItems(centerType);
  7449. OBSDataAutoRelease rwrapper =
  7450. obs_scene_save_transform_states(GetCurrentScene(), false);
  7451. std::string undo_data(obs_data_get_json(wrapper));
  7452. std::string redo_data(obs_data_get_json(rwrapper));
  7453. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  7454. .arg(obs_source_get_name(obs_scene_get_source(
  7455. GetCurrentScene()))),
  7456. undo_redo, undo_redo, undo_data, redo_data);
  7457. }
  7458. void OBSBasic::on_actionHorizontalCenter_triggered()
  7459. {
  7460. CenterType centerType = CenterType::Horizontal;
  7461. OBSDataAutoRelease wrapper =
  7462. obs_scene_save_transform_states(GetCurrentScene(), false);
  7463. CenterSelectedSceneItems(centerType);
  7464. OBSDataAutoRelease rwrapper =
  7465. obs_scene_save_transform_states(GetCurrentScene(), false);
  7466. std::string undo_data(obs_data_get_json(wrapper));
  7467. std::string redo_data(obs_data_get_json(rwrapper));
  7468. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  7469. .arg(obs_source_get_name(obs_scene_get_source(
  7470. GetCurrentScene()))),
  7471. undo_redo, undo_redo, undo_data, redo_data);
  7472. }
  7473. void OBSBasic::EnablePreviewDisplay(bool enable)
  7474. {
  7475. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  7476. ui->preview->setVisible(enable);
  7477. ui->previewDisabledWidget->setVisible(!enable);
  7478. }
  7479. void OBSBasic::TogglePreview()
  7480. {
  7481. previewEnabled = !previewEnabled;
  7482. EnablePreviewDisplay(previewEnabled);
  7483. }
  7484. void OBSBasic::EnablePreview()
  7485. {
  7486. if (previewProgramMode)
  7487. return;
  7488. previewEnabled = true;
  7489. EnablePreviewDisplay(true);
  7490. }
  7491. void OBSBasic::DisablePreview()
  7492. {
  7493. if (previewProgramMode)
  7494. return;
  7495. previewEnabled = false;
  7496. EnablePreviewDisplay(false);
  7497. }
  7498. void OBSBasic::EnablePreviewProgram()
  7499. {
  7500. SetPreviewProgramMode(true);
  7501. }
  7502. void OBSBasic::DisablePreviewProgram()
  7503. {
  7504. SetPreviewProgramMode(false);
  7505. }
  7506. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  7507. {
  7508. if (obs_sceneitem_locked(item))
  7509. return true;
  7510. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  7511. struct vec2 pos;
  7512. if (!obs_sceneitem_selected(item)) {
  7513. if (obs_sceneitem_is_group(item)) {
  7514. struct vec3 offset3;
  7515. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  7516. struct matrix4 matrix;
  7517. obs_sceneitem_get_draw_transform(item, &matrix);
  7518. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  7519. matrix4_inv(&matrix, &matrix);
  7520. vec3_transform(&offset3, &offset3, &matrix);
  7521. struct vec2 new_offset;
  7522. vec2_set(&new_offset, offset3.x, offset3.y);
  7523. obs_sceneitem_group_enum_items(item, nudge_callback,
  7524. &new_offset);
  7525. }
  7526. return true;
  7527. }
  7528. obs_sceneitem_get_pos(item, &pos);
  7529. vec2_add(&pos, &pos, &offset);
  7530. obs_sceneitem_set_pos(item, &pos);
  7531. return true;
  7532. }
  7533. void OBSBasic::Nudge(int dist, MoveDir dir)
  7534. {
  7535. if (ui->preview->Locked())
  7536. return;
  7537. struct vec2 offset;
  7538. vec2_set(&offset, 0.0f, 0.0f);
  7539. switch (dir) {
  7540. case MoveDir::Up:
  7541. offset.y = (float)-dist;
  7542. break;
  7543. case MoveDir::Down:
  7544. offset.y = (float)dist;
  7545. break;
  7546. case MoveDir::Left:
  7547. offset.x = (float)-dist;
  7548. break;
  7549. case MoveDir::Right:
  7550. offset.x = (float)dist;
  7551. break;
  7552. }
  7553. if (!recent_nudge) {
  7554. recent_nudge = true;
  7555. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7556. GetCurrentScene(), true);
  7557. std::string undo_data(obs_data_get_json(wrapper));
  7558. nudge_timer = new QTimer;
  7559. QObject::connect(
  7560. nudge_timer, &QTimer::timeout,
  7561. [this, &recent_nudge = recent_nudge, undo_data]() {
  7562. OBSDataAutoRelease rwrapper =
  7563. obs_scene_save_transform_states(
  7564. GetCurrentScene(), true);
  7565. std::string redo_data(
  7566. obs_data_get_json(rwrapper));
  7567. undo_s.add_action(
  7568. QTStr("Undo.Transform")
  7569. .arg(obs_source_get_name(
  7570. GetCurrentSceneSource())),
  7571. undo_redo, undo_redo, undo_data,
  7572. redo_data);
  7573. recent_nudge = false;
  7574. });
  7575. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7576. &QTimer::deleteLater);
  7577. nudge_timer->setSingleShot(true);
  7578. }
  7579. if (nudge_timer) {
  7580. nudge_timer->stop();
  7581. nudge_timer->start(1000);
  7582. } else {
  7583. blog(LOG_ERROR, "No nudge timer!");
  7584. }
  7585. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7586. }
  7587. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7588. {
  7589. for (size_t i = 0; i < projectors.size(); i++) {
  7590. if (projectors[i] == projector) {
  7591. projectors[i]->deleteLater();
  7592. projectors.erase(projectors.begin() + i);
  7593. break;
  7594. }
  7595. }
  7596. }
  7597. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7598. ProjectorType type)
  7599. {
  7600. /* seriously? 10 monitors? */
  7601. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7602. return nullptr;
  7603. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7604. "CloseExistingProjectors");
  7605. if (closeProjectors && monitor > -1) {
  7606. for (size_t i = projectors.size(); i > 0; i--) {
  7607. size_t idx = i - 1;
  7608. if (projectors[idx]->GetMonitor() == monitor)
  7609. DeleteProjector(projectors[idx]);
  7610. }
  7611. }
  7612. OBSProjector *projector =
  7613. new OBSProjector(nullptr, source, monitor, type);
  7614. projectors.emplace_back(projector);
  7615. return projector;
  7616. }
  7617. void OBSBasic::OpenStudioProgramProjector()
  7618. {
  7619. int monitor = sender()->property("monitor").toInt();
  7620. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7621. }
  7622. void OBSBasic::OpenPreviewProjector()
  7623. {
  7624. int monitor = sender()->property("monitor").toInt();
  7625. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7626. }
  7627. void OBSBasic::OpenSourceProjector()
  7628. {
  7629. int monitor = sender()->property("monitor").toInt();
  7630. OBSSceneItem item = GetCurrentSceneItem();
  7631. if (!item)
  7632. return;
  7633. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7634. ProjectorType::Source);
  7635. }
  7636. void OBSBasic::OpenMultiviewProjector()
  7637. {
  7638. int monitor = sender()->property("monitor").toInt();
  7639. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7640. }
  7641. void OBSBasic::OpenSceneProjector()
  7642. {
  7643. int monitor = sender()->property("monitor").toInt();
  7644. OBSScene scene = GetCurrentScene();
  7645. if (!scene)
  7646. return;
  7647. OpenProjector(obs_scene_get_source(scene), monitor,
  7648. ProjectorType::Scene);
  7649. }
  7650. void OBSBasic::OpenStudioProgramWindow()
  7651. {
  7652. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7653. }
  7654. void OBSBasic::OpenPreviewWindow()
  7655. {
  7656. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7657. }
  7658. void OBSBasic::OpenSourceWindow()
  7659. {
  7660. OBSSceneItem item = GetCurrentSceneItem();
  7661. if (!item)
  7662. return;
  7663. OBSSource source = obs_sceneitem_get_source(item);
  7664. OpenProjector(obs_sceneitem_get_source(item), -1,
  7665. ProjectorType::Source);
  7666. }
  7667. void OBSBasic::OpenSceneWindow()
  7668. {
  7669. OBSScene scene = GetCurrentScene();
  7670. if (!scene)
  7671. return;
  7672. OBSSource source = obs_scene_get_source(scene);
  7673. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7674. }
  7675. void OBSBasic::OpenSavedProjectors()
  7676. {
  7677. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7678. OpenSavedProjector(info);
  7679. }
  7680. }
  7681. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7682. {
  7683. if (info) {
  7684. OBSProjector *projector = nullptr;
  7685. switch (info->type) {
  7686. case ProjectorType::Source:
  7687. case ProjectorType::Scene: {
  7688. OBSSourceAutoRelease source =
  7689. obs_get_source_by_name(info->name.c_str());
  7690. if (!source)
  7691. return;
  7692. projector = OpenProjector(source, info->monitor,
  7693. info->type);
  7694. break;
  7695. }
  7696. default: {
  7697. projector = OpenProjector(nullptr, info->monitor,
  7698. info->type);
  7699. break;
  7700. }
  7701. }
  7702. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7703. QByteArray byteArray = QByteArray::fromBase64(
  7704. QByteArray(info->geometry.c_str()));
  7705. projector->restoreGeometry(byteArray);
  7706. if (!WindowPositionValid(projector->normalGeometry())) {
  7707. QRect rect = QGuiApplication::primaryScreen()
  7708. ->geometry();
  7709. projector->setGeometry(QStyle::alignedRect(
  7710. Qt::LeftToRight, Qt::AlignCenter,
  7711. size(), rect));
  7712. }
  7713. if (info->alwaysOnTopOverridden)
  7714. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7715. true);
  7716. }
  7717. }
  7718. }
  7719. void OBSBasic::on_actionFullscreenInterface_triggered()
  7720. {
  7721. if (!isFullScreen())
  7722. showFullScreen();
  7723. else
  7724. showNormal();
  7725. }
  7726. void OBSBasic::UpdateTitleBar()
  7727. {
  7728. stringstream name;
  7729. const char *profile =
  7730. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7731. const char *sceneCollection = config_get_string(
  7732. App()->GlobalConfig(), "Basic", "SceneCollection");
  7733. name << "OBS ";
  7734. if (previewProgramMode)
  7735. name << "Studio ";
  7736. name << App()->GetVersionString(false);
  7737. if (safe_mode)
  7738. name << " (" << Str("TitleBar.SafeMode") << ")";
  7739. if (App()->IsPortableMode())
  7740. name << " - " << Str("TitleBar.PortableMode");
  7741. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7742. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7743. setWindowTitle(QT_UTF8(name.str().c_str()));
  7744. }
  7745. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7746. {
  7747. char profiles_path[512];
  7748. const char *profile =
  7749. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7750. int ret;
  7751. if (!profile)
  7752. return -1;
  7753. if (!path)
  7754. return -1;
  7755. if (!file)
  7756. file = "";
  7757. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7758. if (ret <= 0)
  7759. return ret;
  7760. if (!*file)
  7761. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7762. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7763. }
  7764. void OBSBasic::on_resetDocks_triggered(bool force)
  7765. {
  7766. /* prune deleted extra docks */
  7767. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7768. if (!oldExtraDocks[i]) {
  7769. oldExtraDocks.removeAt(i);
  7770. oldExtraDockNames.removeAt(i);
  7771. }
  7772. }
  7773. #ifdef BROWSER_AVAILABLE
  7774. if ((oldExtraDocks.size() || extraDocks.size() ||
  7775. extraCustomDocks.size() || extraBrowserDocks.size()) &&
  7776. !force)
  7777. #else
  7778. if ((oldExtraDocks.size() || extraDocks.size() ||
  7779. extraCustomDocks.size()) &&
  7780. !force)
  7781. #endif
  7782. {
  7783. QMessageBox::StandardButton button = OBSMessageBox::question(
  7784. this, QTStr("ResetUIWarning.Title"),
  7785. QTStr("ResetUIWarning.Text"));
  7786. if (button == QMessageBox::No)
  7787. return;
  7788. }
  7789. /* undock/hide/center extra docks */
  7790. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7791. if (oldExtraDocks[i]) {
  7792. oldExtraDocks[i]->setVisible(true);
  7793. oldExtraDocks[i]->setFloating(true);
  7794. oldExtraDocks[i]->move(
  7795. frameGeometry().topLeft() + rect().center() -
  7796. oldExtraDocks[i]->rect().center());
  7797. oldExtraDocks[i]->setVisible(false);
  7798. }
  7799. }
  7800. #define RESET_DOCKLIST(dockList) \
  7801. for (int i = dockList.size() - 1; i >= 0; i--) { \
  7802. dockList[i]->setVisible(true); \
  7803. dockList[i]->setFloating(true); \
  7804. dockList[i]->move(frameGeometry().topLeft() + \
  7805. rect().center() - \
  7806. dockList[i]->rect().center()); \
  7807. dockList[i]->setVisible(false); \
  7808. }
  7809. RESET_DOCKLIST(extraDocks)
  7810. RESET_DOCKLIST(extraCustomDocks)
  7811. #ifdef BROWSER_AVAILABLE
  7812. RESET_DOCKLIST(extraBrowserDocks)
  7813. #endif
  7814. #undef RESET_DOCKLIST
  7815. restoreState(startingDockLayout);
  7816. int cx = width();
  7817. int cy = height();
  7818. int cx22_5 = cx * 225 / 1000;
  7819. int cx5 = cx * 5 / 100;
  7820. int cx21 = cx * 21 / 100;
  7821. cy = cy * 225 / 1000;
  7822. int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21);
  7823. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7824. ui->mixerDock, ui->transitionsDock,
  7825. controlsDock};
  7826. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx21};
  7827. ui->scenesDock->setVisible(true);
  7828. ui->sourcesDock->setVisible(true);
  7829. ui->mixerDock->setVisible(true);
  7830. ui->transitionsDock->setVisible(true);
  7831. controlsDock->setVisible(true);
  7832. statsDock->setVisible(false);
  7833. statsDock->setFloating(true);
  7834. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7835. resizeDocks(docks, sizes, Qt::Horizontal);
  7836. activateWindow();
  7837. }
  7838. void OBSBasic::on_lockDocks_toggled(bool lock)
  7839. {
  7840. QDockWidget::DockWidgetFeatures features =
  7841. lock ? QDockWidget::NoDockWidgetFeatures
  7842. : (QDockWidget::DockWidgetClosable |
  7843. QDockWidget::DockWidgetMovable |
  7844. QDockWidget::DockWidgetFloatable);
  7845. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7846. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7847. ui->scenesDock->setFeatures(mainFeatures);
  7848. ui->sourcesDock->setFeatures(mainFeatures);
  7849. ui->mixerDock->setFeatures(mainFeatures);
  7850. ui->transitionsDock->setFeatures(mainFeatures);
  7851. controlsDock->setFeatures(mainFeatures);
  7852. statsDock->setFeatures(features);
  7853. for (int i = extraDocks.size() - 1; i >= 0; i--)
  7854. extraDocks[i]->setFeatures(features);
  7855. for (int i = extraCustomDocks.size() - 1; i >= 0; i--)
  7856. extraCustomDocks[i]->setFeatures(features);
  7857. #ifdef BROWSER_AVAILABLE
  7858. for (int i = extraBrowserDocks.size() - 1; i >= 0; i--)
  7859. extraBrowserDocks[i]->setFeatures(features);
  7860. #endif
  7861. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7862. if (!oldExtraDocks[i]) {
  7863. oldExtraDocks.removeAt(i);
  7864. oldExtraDockNames.removeAt(i);
  7865. } else {
  7866. oldExtraDocks[i]->setFeatures(features);
  7867. }
  7868. }
  7869. }
  7870. void OBSBasic::on_sideDocks_toggled(bool side)
  7871. {
  7872. if (side) {
  7873. setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
  7874. setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
  7875. setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
  7876. setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
  7877. } else {
  7878. setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea);
  7879. setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
  7880. setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
  7881. setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
  7882. }
  7883. }
  7884. void OBSBasic::on_resetUI_triggered()
  7885. {
  7886. on_resetDocks_triggered();
  7887. ui->toggleListboxToolbars->setChecked(true);
  7888. ui->toggleContextBar->setChecked(true);
  7889. ui->toggleSourceIcons->setChecked(true);
  7890. ui->toggleStatusBar->setChecked(true);
  7891. ui->scenes->SetGridMode(false);
  7892. ui->actionSceneListMode->setChecked(true);
  7893. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  7894. false);
  7895. }
  7896. void OBSBasic::on_multiviewProjectorWindowed_triggered()
  7897. {
  7898. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7899. }
  7900. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7901. {
  7902. ui->sourcesToolbar->setVisible(visible);
  7903. ui->scenesToolbar->setVisible(visible);
  7904. ui->mixerToolbar->setVisible(visible);
  7905. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7906. "ShowListboxToolbars", visible);
  7907. }
  7908. void OBSBasic::ShowContextBar()
  7909. {
  7910. on_toggleContextBar_toggled(true);
  7911. ui->toggleContextBar->setChecked(true);
  7912. }
  7913. void OBSBasic::HideContextBar()
  7914. {
  7915. on_toggleContextBar_toggled(false);
  7916. ui->toggleContextBar->setChecked(false);
  7917. }
  7918. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7919. {
  7920. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7921. "ShowContextToolbars", visible);
  7922. this->ui->contextContainer->setVisible(visible);
  7923. UpdateContextBar(true);
  7924. }
  7925. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7926. {
  7927. ui->statusbar->setVisible(visible);
  7928. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7929. visible);
  7930. }
  7931. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7932. {
  7933. ui->sources->SetIconsVisible(visible);
  7934. if (advAudioWindow != nullptr)
  7935. advAudioWindow->SetIconsVisible(visible);
  7936. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7937. visible);
  7938. }
  7939. void OBSBasic::on_actionLockPreview_triggered()
  7940. {
  7941. ui->preview->ToggleLocked();
  7942. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7943. }
  7944. void OBSBasic::on_scalingMenu_aboutToShow()
  7945. {
  7946. obs_video_info ovi;
  7947. obs_get_video_info(&ovi);
  7948. QAction *action = ui->actionScaleCanvas;
  7949. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7950. text = text.arg(QString::number(ovi.base_width),
  7951. QString::number(ovi.base_height));
  7952. action->setText(text);
  7953. action = ui->actionScaleOutput;
  7954. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7955. text = text.arg(QString::number(ovi.output_width),
  7956. QString::number(ovi.output_height));
  7957. action->setText(text);
  7958. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7959. ovi.output_height == ovi.base_height));
  7960. UpdatePreviewScalingMenu();
  7961. }
  7962. void OBSBasic::on_actionScaleWindow_triggered()
  7963. {
  7964. ui->preview->SetFixedScaling(false);
  7965. ui->preview->ResetScrollingOffset();
  7966. emit ui->preview->DisplayResized();
  7967. }
  7968. void OBSBasic::on_actionScaleCanvas_triggered()
  7969. {
  7970. ui->preview->SetFixedScaling(true);
  7971. ui->preview->SetScalingLevel(0);
  7972. emit ui->preview->DisplayResized();
  7973. }
  7974. void OBSBasic::on_actionScaleOutput_triggered()
  7975. {
  7976. obs_video_info ovi;
  7977. obs_get_video_info(&ovi);
  7978. ui->preview->SetFixedScaling(true);
  7979. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7980. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7981. int32_t approxScalingLevel =
  7982. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7983. ui->preview->SetScalingLevel(approxScalingLevel);
  7984. ui->preview->SetScalingAmount(scalingAmount);
  7985. emit ui->preview->DisplayResized();
  7986. }
  7987. void OBSBasic::SetShowing(bool showing)
  7988. {
  7989. if (!showing && isVisible()) {
  7990. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7991. "geometry",
  7992. saveGeometry().toBase64().constData());
  7993. /* hide all visible child dialogs */
  7994. visDlgPositions.clear();
  7995. if (!visDialogs.isEmpty()) {
  7996. for (QDialog *dlg : visDialogs) {
  7997. visDlgPositions.append(dlg->pos());
  7998. dlg->hide();
  7999. }
  8000. }
  8001. if (showHide)
  8002. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8003. QTimer::singleShot(0, this, &OBSBasic::hide);
  8004. if (previewEnabled)
  8005. EnablePreviewDisplay(false);
  8006. #ifdef __APPLE__
  8007. EnableOSXDockIcon(false);
  8008. #endif
  8009. } else if (showing && !isVisible()) {
  8010. if (showHide)
  8011. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8012. QTimer::singleShot(0, this, &OBSBasic::show);
  8013. if (previewEnabled)
  8014. EnablePreviewDisplay(true);
  8015. #ifdef __APPLE__
  8016. EnableOSXDockIcon(true);
  8017. #endif
  8018. /* raise and activate window to ensure it is on top */
  8019. raise();
  8020. activateWindow();
  8021. /* show all child dialogs that was visible earlier */
  8022. if (!visDialogs.isEmpty()) {
  8023. for (int i = 0; i < visDialogs.size(); ++i) {
  8024. QDialog *dlg = visDialogs[i];
  8025. dlg->move(visDlgPositions[i]);
  8026. dlg->show();
  8027. }
  8028. }
  8029. /* Unminimize window if it was hidden to tray instead of task
  8030. * bar. */
  8031. if (sysTrayMinimizeToTray()) {
  8032. Qt::WindowStates state;
  8033. state = windowState() & ~Qt::WindowMinimized;
  8034. state |= Qt::WindowActive;
  8035. setWindowState(state);
  8036. }
  8037. }
  8038. }
  8039. void OBSBasic::ToggleShowHide()
  8040. {
  8041. bool showing = isVisible();
  8042. if (showing) {
  8043. /* check for modal dialogs */
  8044. EnumDialogs();
  8045. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  8046. return;
  8047. }
  8048. SetShowing(!showing);
  8049. }
  8050. void OBSBasic::SystemTrayInit()
  8051. {
  8052. #ifdef __APPLE__
  8053. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  8054. trayIconFile.setIsMask(true);
  8055. #else
  8056. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  8057. #endif
  8058. trayIcon.reset(new QSystemTrayIcon(
  8059. QIcon::fromTheme("obs-tray", trayIconFile), this));
  8060. trayIcon->setToolTip("OBS Studio");
  8061. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  8062. sysTrayStream = new QAction(
  8063. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  8064. : QTStr("Basic.Main.StartStreaming"),
  8065. trayIcon.data());
  8066. sysTrayRecord = new QAction(
  8067. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  8068. : QTStr("Basic.Main.StartRecording"),
  8069. trayIcon.data());
  8070. sysTrayReplayBuffer = new QAction(
  8071. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  8072. : QTStr("Basic.Main.StartReplayBuffer"),
  8073. trayIcon.data());
  8074. sysTrayVirtualCam = new QAction(
  8075. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  8076. : QTStr("Basic.Main.StartVirtualCam"),
  8077. trayIcon.data());
  8078. exit = new QAction(QTStr("Exit"), trayIcon.data());
  8079. trayMenu = new QMenu;
  8080. previewProjector = new QMenu(QTStr("PreviewProjector"));
  8081. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  8082. AddProjectorMenuMonitors(previewProjector, this,
  8083. &OBSBasic::OpenPreviewProjector);
  8084. AddProjectorMenuMonitors(studioProgramProjector, this,
  8085. &OBSBasic::OpenStudioProgramProjector);
  8086. trayMenu->addAction(showHide);
  8087. trayMenu->addSeparator();
  8088. trayMenu->addMenu(previewProjector);
  8089. trayMenu->addMenu(studioProgramProjector);
  8090. trayMenu->addSeparator();
  8091. trayMenu->addAction(sysTrayStream);
  8092. trayMenu->addAction(sysTrayRecord);
  8093. trayMenu->addAction(sysTrayReplayBuffer);
  8094. trayMenu->addAction(sysTrayVirtualCam);
  8095. trayMenu->addSeparator();
  8096. trayMenu->addAction(exit);
  8097. trayIcon->setContextMenu(trayMenu);
  8098. trayIcon->show();
  8099. if (outputHandler && !outputHandler->replayBuffer)
  8100. sysTrayReplayBuffer->setEnabled(false);
  8101. sysTrayVirtualCam->setEnabled(vcamEnabled);
  8102. if (Active())
  8103. OnActivate(true);
  8104. connect(trayIcon.data(), &QSystemTrayIcon::activated, this,
  8105. &OBSBasic::IconActivated);
  8106. connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide);
  8107. connect(sysTrayStream, &QAction::triggered, this,
  8108. &OBSBasic::StreamActionTriggered);
  8109. connect(sysTrayRecord, &QAction::triggered, this,
  8110. &OBSBasic::RecordActionTriggered);
  8111. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  8112. &OBSBasic::ReplayBufferActionTriggered);
  8113. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  8114. &OBSBasic::VirtualCamActionTriggered);
  8115. connect(exit, &QAction::triggered, this, &OBSBasic::close);
  8116. }
  8117. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  8118. {
  8119. // Refresh projector list
  8120. previewProjector->clear();
  8121. studioProgramProjector->clear();
  8122. AddProjectorMenuMonitors(previewProjector, this,
  8123. &OBSBasic::OpenPreviewProjector);
  8124. AddProjectorMenuMonitors(studioProgramProjector, this,
  8125. &OBSBasic::OpenStudioProgramProjector);
  8126. #ifdef __APPLE__
  8127. UNUSED_PARAMETER(reason);
  8128. #else
  8129. if (reason == QSystemTrayIcon::Trigger) {
  8130. EnablePreviewDisplay(previewEnabled && !isVisible());
  8131. ToggleShowHide();
  8132. }
  8133. #endif
  8134. }
  8135. void OBSBasic::SysTrayNotify(const QString &text,
  8136. QSystemTrayIcon::MessageIcon n)
  8137. {
  8138. if (trayIcon && trayIcon->isVisible() &&
  8139. QSystemTrayIcon::supportsMessages()) {
  8140. QSystemTrayIcon::MessageIcon icon =
  8141. QSystemTrayIcon::MessageIcon(n);
  8142. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  8143. }
  8144. }
  8145. void OBSBasic::SystemTray(bool firstStarted)
  8146. {
  8147. if (!QSystemTrayIcon::isSystemTrayAvailable())
  8148. return;
  8149. if (!trayIcon && !firstStarted)
  8150. return;
  8151. bool sysTrayWhenStarted = config_get_bool(
  8152. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  8153. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  8154. "SysTrayEnabled");
  8155. if (firstStarted)
  8156. SystemTrayInit();
  8157. if (!sysTrayEnabled) {
  8158. trayIcon->hide();
  8159. } else {
  8160. trayIcon->show();
  8161. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  8162. EnablePreviewDisplay(false);
  8163. #ifdef __APPLE__
  8164. EnableOSXDockIcon(false);
  8165. #endif
  8166. opt_minimize_tray = false;
  8167. }
  8168. }
  8169. if (isVisible())
  8170. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8171. else
  8172. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8173. }
  8174. bool OBSBasic::sysTrayMinimizeToTray()
  8175. {
  8176. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  8177. "SysTrayMinimizeToTray");
  8178. }
  8179. void OBSBasic::on_actionMainUndo_triggered()
  8180. {
  8181. undo_s.undo();
  8182. }
  8183. void OBSBasic::on_actionMainRedo_triggered()
  8184. {
  8185. undo_s.redo();
  8186. }
  8187. void OBSBasic::on_actionCopySource_triggered()
  8188. {
  8189. clipboard.clear();
  8190. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  8191. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  8192. if (!item)
  8193. continue;
  8194. OBSSource source = obs_sceneitem_get_source(item);
  8195. SourceCopyInfo copyInfo;
  8196. copyInfo.weak_source = OBSGetWeakRef(source);
  8197. obs_sceneitem_get_info2(item, &copyInfo.transform);
  8198. obs_sceneitem_get_crop(item, &copyInfo.crop);
  8199. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  8200. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  8201. copyInfo.visible = obs_sceneitem_visible(item);
  8202. clipboard.push_back(copyInfo);
  8203. }
  8204. UpdateEditMenu();
  8205. }
  8206. void OBSBasic::on_actionPasteRef_triggered()
  8207. {
  8208. OBSSource scene_source = GetCurrentSceneSource();
  8209. OBSData undo_data = BackupScene(scene_source);
  8210. OBSScene scene = GetCurrentScene();
  8211. undo_s.push_disabled();
  8212. for (size_t i = clipboard.size(); i > 0; i--) {
  8213. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8214. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  8215. if (!source)
  8216. continue;
  8217. const char *name = obs_source_get_name(source);
  8218. /* do not allow duplicate refs of the same group in the same
  8219. * scene */
  8220. if (!!obs_scene_get_group(scene, name)) {
  8221. continue;
  8222. }
  8223. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  8224. }
  8225. undo_s.pop_disabled();
  8226. QString action_name = QTStr("Undo.PasteSourceRef");
  8227. const char *scene_name = obs_source_get_name(scene_source);
  8228. OBSData redo_data = BackupScene(scene_source);
  8229. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8230. redo_data);
  8231. }
  8232. void OBSBasic::on_actionPasteDup_triggered()
  8233. {
  8234. OBSSource scene_source = GetCurrentSceneSource();
  8235. OBSData undo_data = BackupScene(scene_source);
  8236. undo_s.push_disabled();
  8237. for (size_t i = clipboard.size(); i > 0; i--) {
  8238. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8239. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  8240. }
  8241. undo_s.pop_disabled();
  8242. QString action_name = QTStr("Undo.PasteSource");
  8243. const char *scene_name = obs_source_get_name(scene_source);
  8244. OBSData redo_data = BackupScene(scene_source);
  8245. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8246. redo_data);
  8247. }
  8248. void OBSBasic::SourcePasteFilters(OBSSource source, OBSSource dstSource)
  8249. {
  8250. if (source == dstSource)
  8251. return;
  8252. OBSDataArrayAutoRelease undo_array =
  8253. obs_source_backup_filters(dstSource);
  8254. obs_source_copy_filters(dstSource, source);
  8255. OBSDataArrayAutoRelease redo_array =
  8256. obs_source_backup_filters(dstSource);
  8257. const char *srcName = obs_source_get_name(source);
  8258. const char *dstName = obs_source_get_name(dstSource);
  8259. QString text =
  8260. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  8261. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  8262. redo_array);
  8263. }
  8264. void OBSBasic::AudioMixerCopyFilters()
  8265. {
  8266. QAction *action = reinterpret_cast<QAction *>(sender());
  8267. VolControl *vol = action->property("volControl").value<VolControl *>();
  8268. obs_source_t *source = vol->GetSource();
  8269. copyFiltersSource = obs_source_get_weak_source(source);
  8270. ui->actionPasteFilters->setEnabled(true);
  8271. }
  8272. void OBSBasic::AudioMixerPasteFilters()
  8273. {
  8274. QAction *action = reinterpret_cast<QAction *>(sender());
  8275. VolControl *vol = action->property("volControl").value<VolControl *>();
  8276. obs_source_t *dstSource = vol->GetSource();
  8277. OBSSourceAutoRelease source =
  8278. obs_weak_source_get_source(copyFiltersSource);
  8279. SourcePasteFilters(source.Get(), dstSource);
  8280. }
  8281. void OBSBasic::SceneCopyFilters()
  8282. {
  8283. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  8284. ui->actionPasteFilters->setEnabled(true);
  8285. }
  8286. void OBSBasic::ScenePasteFilters()
  8287. {
  8288. OBSSourceAutoRelease source =
  8289. obs_weak_source_get_source(copyFiltersSource);
  8290. OBSSource dstSource = GetCurrentSceneSource();
  8291. SourcePasteFilters(source.Get(), dstSource);
  8292. }
  8293. void OBSBasic::on_actionCopyFilters_triggered()
  8294. {
  8295. OBSSceneItem item = GetCurrentSceneItem();
  8296. if (!item)
  8297. return;
  8298. OBSSource source = obs_sceneitem_get_source(item);
  8299. copyFiltersSource = obs_source_get_weak_source(source);
  8300. ui->actionPasteFilters->setEnabled(true);
  8301. }
  8302. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  8303. obs_source_t *source,
  8304. obs_data_array_t *undo_array,
  8305. obs_data_array_t *redo_array)
  8306. {
  8307. auto undo_redo = [this](const std::string &json) {
  8308. OBSDataAutoRelease data =
  8309. obs_data_create_from_json(json.c_str());
  8310. OBSDataArrayAutoRelease array =
  8311. obs_data_get_array(data, "array");
  8312. OBSSourceAutoRelease source = obs_get_source_by_uuid(
  8313. obs_data_get_string(data, "uuid"));
  8314. obs_source_restore_filters(source, array);
  8315. if (filters)
  8316. filters->UpdateSource(source);
  8317. };
  8318. const char *uuid = obs_source_get_uuid(source);
  8319. OBSDataAutoRelease undo_data = obs_data_create();
  8320. OBSDataAutoRelease redo_data = obs_data_create();
  8321. obs_data_set_array(undo_data, "array", undo_array);
  8322. obs_data_set_array(redo_data, "array", redo_array);
  8323. obs_data_set_string(undo_data, "uuid", uuid);
  8324. obs_data_set_string(redo_data, "uuid", uuid);
  8325. undo_s.add_action(text, undo_redo, undo_redo,
  8326. obs_data_get_json(undo_data),
  8327. obs_data_get_json(redo_data));
  8328. }
  8329. void OBSBasic::on_actionPasteFilters_triggered()
  8330. {
  8331. OBSSourceAutoRelease source =
  8332. obs_weak_source_get_source(copyFiltersSource);
  8333. OBSSceneItem sceneItem = GetCurrentSceneItem();
  8334. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  8335. SourcePasteFilters(source.Get(), dstSource);
  8336. }
  8337. static void ConfirmColor(SourceTree *sources, const QColor &color,
  8338. QModelIndexList selectedItems)
  8339. {
  8340. for (int x = 0; x < selectedItems.count(); x++) {
  8341. SourceTreeItem *treeItem =
  8342. sources->GetItemWidget(selectedItems[x].row());
  8343. treeItem->setStyleSheet("background: " +
  8344. color.name(QColor::HexArgb));
  8345. treeItem->style()->unpolish(treeItem);
  8346. treeItem->style()->polish(treeItem);
  8347. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  8348. OBSDataAutoRelease privData =
  8349. obs_sceneitem_get_private_settings(sceneItem);
  8350. obs_data_set_int(privData, "color-preset", 1);
  8351. obs_data_set_string(privData, "color",
  8352. QT_TO_UTF8(color.name(QColor::HexArgb)));
  8353. }
  8354. }
  8355. void OBSBasic::ColorChange()
  8356. {
  8357. QModelIndexList selectedItems =
  8358. ui->sources->selectionModel()->selectedIndexes();
  8359. QAction *action = qobject_cast<QAction *>(sender());
  8360. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  8361. if (selectedItems.count() == 0)
  8362. return;
  8363. if (colorButton) {
  8364. int preset = colorButton->property("bgColor").value<int>();
  8365. for (int x = 0; x < selectedItems.count(); x++) {
  8366. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  8367. selectedItems[x].row());
  8368. treeItem->setStyleSheet("");
  8369. treeItem->setProperty("bgColor", preset);
  8370. treeItem->style()->unpolish(treeItem);
  8371. treeItem->style()->polish(treeItem);
  8372. OBSSceneItem sceneItem =
  8373. ui->sources->Get(selectedItems[x].row());
  8374. OBSDataAutoRelease privData =
  8375. obs_sceneitem_get_private_settings(sceneItem);
  8376. obs_data_set_int(privData, "color-preset", preset + 1);
  8377. obs_data_set_string(privData, "color", "");
  8378. }
  8379. for (int i = 1; i < 9; i++) {
  8380. stringstream button;
  8381. button << "preset" << i;
  8382. QPushButton *cButton =
  8383. colorButton->parentWidget()
  8384. ->findChild<QPushButton *>(
  8385. button.str().c_str());
  8386. cButton->setStyleSheet("border: 1px solid black");
  8387. }
  8388. colorButton->setStyleSheet("border: 2px solid black");
  8389. } else if (action) {
  8390. int preset = action->property("bgColor").value<int>();
  8391. if (preset == 1) {
  8392. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  8393. SourceTreeItem *curTreeItem =
  8394. GetItemWidgetFromSceneItem(curSceneItem);
  8395. OBSDataAutoRelease curPrivData =
  8396. obs_sceneitem_get_private_settings(
  8397. curSceneItem);
  8398. int oldPreset =
  8399. obs_data_get_int(curPrivData, "color-preset");
  8400. const QString oldSheet = curTreeItem->styleSheet();
  8401. auto liveChangeColor = [=](const QColor &color) {
  8402. if (color.isValid()) {
  8403. curTreeItem->setStyleSheet(
  8404. "background: " +
  8405. color.name(QColor::HexArgb));
  8406. }
  8407. };
  8408. auto changedColor = [=](const QColor &color) {
  8409. if (color.isValid()) {
  8410. ConfirmColor(ui->sources, color,
  8411. selectedItems);
  8412. }
  8413. };
  8414. auto rejected = [=]() {
  8415. if (oldPreset == 1) {
  8416. curTreeItem->setStyleSheet(oldSheet);
  8417. curTreeItem->setProperty("bgColor", 0);
  8418. } else if (oldPreset == 0) {
  8419. curTreeItem->setStyleSheet(
  8420. "background: none");
  8421. curTreeItem->setProperty("bgColor", 0);
  8422. } else {
  8423. curTreeItem->setStyleSheet("");
  8424. curTreeItem->setProperty("bgColor",
  8425. oldPreset - 1);
  8426. }
  8427. curTreeItem->style()->unpolish(curTreeItem);
  8428. curTreeItem->style()->polish(curTreeItem);
  8429. };
  8430. QColorDialog::ColorDialogOptions options =
  8431. QColorDialog::ShowAlphaChannel;
  8432. const char *oldColor =
  8433. obs_data_get_string(curPrivData, "color");
  8434. const char *customColor = *oldColor != 0 ? oldColor
  8435. : "#55FF0000";
  8436. #ifdef __linux__
  8437. // TODO: Revisit hang on Ubuntu with native dialog
  8438. options |= QColorDialog::DontUseNativeDialog;
  8439. #endif
  8440. QColorDialog *colorDialog = new QColorDialog(this);
  8441. colorDialog->setOptions(options);
  8442. colorDialog->setCurrentColor(QColor(customColor));
  8443. connect(colorDialog, &QColorDialog::currentColorChanged,
  8444. liveChangeColor);
  8445. connect(colorDialog, &QColorDialog::colorSelected,
  8446. changedColor);
  8447. connect(colorDialog, &QColorDialog::rejected, rejected);
  8448. colorDialog->open();
  8449. } else {
  8450. for (int x = 0; x < selectedItems.count(); x++) {
  8451. SourceTreeItem *treeItem =
  8452. ui->sources->GetItemWidget(
  8453. selectedItems[x].row());
  8454. treeItem->setStyleSheet("background: none");
  8455. treeItem->setProperty("bgColor", preset);
  8456. treeItem->style()->unpolish(treeItem);
  8457. treeItem->style()->polish(treeItem);
  8458. OBSSceneItem sceneItem = ui->sources->Get(
  8459. selectedItems[x].row());
  8460. OBSDataAutoRelease privData =
  8461. obs_sceneitem_get_private_settings(
  8462. sceneItem);
  8463. obs_data_set_int(privData, "color-preset",
  8464. preset);
  8465. obs_data_set_string(privData, "color", "");
  8466. }
  8467. }
  8468. }
  8469. }
  8470. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  8471. {
  8472. int i = 0;
  8473. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  8474. OBSSceneItem item = ui->sources->Get(i);
  8475. int64_t id = obs_sceneitem_get_id(sceneItem);
  8476. while (treeItem && obs_sceneitem_get_id(item) != id) {
  8477. i++;
  8478. treeItem = ui->sources->GetItemWidget(i);
  8479. item = ui->sources->Get(i);
  8480. }
  8481. if (treeItem)
  8482. return treeItem;
  8483. return nullptr;
  8484. }
  8485. void OBSBasic::on_autoConfigure_triggered()
  8486. {
  8487. AutoConfig test(this);
  8488. test.setModal(true);
  8489. test.show();
  8490. test.exec();
  8491. }
  8492. void OBSBasic::on_stats_triggered()
  8493. {
  8494. if (!stats.isNull()) {
  8495. stats->show();
  8496. stats->raise();
  8497. return;
  8498. }
  8499. OBSBasicStats *statsDlg;
  8500. statsDlg = new OBSBasicStats(nullptr);
  8501. statsDlg->show();
  8502. stats = statsDlg;
  8503. }
  8504. void OBSBasic::on_actionShowAbout_triggered()
  8505. {
  8506. if (about)
  8507. about->close();
  8508. about = new OBSAbout(this);
  8509. about->show();
  8510. about->setAttribute(Qt::WA_DeleteOnClose, true);
  8511. }
  8512. void OBSBasic::ResizeOutputSizeOfSource()
  8513. {
  8514. if (obs_video_active())
  8515. return;
  8516. QMessageBox resize_output(this);
  8517. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  8518. QTStr("ResizeOutputSizeOfSource.Continue"));
  8519. QAbstractButton *Yes =
  8520. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  8521. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  8522. resize_output.setIcon(QMessageBox::Warning);
  8523. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  8524. resize_output.exec();
  8525. if (resize_output.clickedButton() != Yes)
  8526. return;
  8527. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  8528. int width = obs_source_get_width(source);
  8529. int height = obs_source_get_height(source);
  8530. config_set_uint(basicConfig, "Video", "BaseCX", width);
  8531. config_set_uint(basicConfig, "Video", "BaseCY", height);
  8532. config_set_uint(basicConfig, "Video", "OutputCX", width);
  8533. config_set_uint(basicConfig, "Video", "OutputCY", height);
  8534. ResetVideo();
  8535. ResetOutputs();
  8536. config_save_safe(basicConfig, "tmp", nullptr);
  8537. on_actionFitToScreen_triggered();
  8538. }
  8539. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  8540. {
  8541. // Prevent the object name from being changed
  8542. connect(dock, &QObject::objectNameChanged, this,
  8543. &OBSBasic::RepairOldExtraDockName);
  8544. #ifdef BROWSER_AVAILABLE
  8545. QAction *action = new QAction(dock->windowTitle(), ui->menuDocks);
  8546. if (!extraBrowserMenuDocksSeparator.isNull())
  8547. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8548. action);
  8549. else
  8550. ui->menuDocks->addAction(action);
  8551. #else
  8552. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  8553. #endif
  8554. action->setCheckable(true);
  8555. assignDockToggle(dock, action);
  8556. oldExtraDocks.push_back(dock);
  8557. oldExtraDockNames.push_back(dock->objectName());
  8558. bool lock = ui->lockDocks->isChecked();
  8559. QDockWidget::DockWidgetFeatures features =
  8560. lock ? QDockWidget::NoDockWidgetFeatures
  8561. : (QDockWidget::DockWidgetClosable |
  8562. QDockWidget::DockWidgetMovable |
  8563. QDockWidget::DockWidgetFloatable);
  8564. dock->setFeatures(features);
  8565. /* prune deleted docks */
  8566. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  8567. if (!oldExtraDocks[i]) {
  8568. oldExtraDocks.removeAt(i);
  8569. oldExtraDockNames.removeAt(i);
  8570. }
  8571. }
  8572. return action;
  8573. }
  8574. void OBSBasic::RepairOldExtraDockName()
  8575. {
  8576. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8577. int idx = oldExtraDocks.indexOf(dock);
  8578. QSignalBlocker block(dock);
  8579. if (idx == -1) {
  8580. blog(LOG_WARNING, "A dock got its object name changed");
  8581. return;
  8582. }
  8583. blog(LOG_WARNING, "The dock '%s' got its object name restored",
  8584. QT_TO_UTF8(oldExtraDockNames[idx]));
  8585. dock->setObjectName(oldExtraDockNames[idx]);
  8586. }
  8587. void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area,
  8588. bool extraBrowser)
  8589. {
  8590. if (dock->objectName().isEmpty())
  8591. return;
  8592. bool lock = ui->lockDocks->isChecked();
  8593. QDockWidget::DockWidgetFeatures features =
  8594. lock ? QDockWidget::NoDockWidgetFeatures
  8595. : (QDockWidget::DockWidgetClosable |
  8596. QDockWidget::DockWidgetMovable |
  8597. QDockWidget::DockWidgetFloatable);
  8598. setupDockAction(dock);
  8599. dock->setFeatures(features);
  8600. addDockWidget(area, dock);
  8601. #ifdef BROWSER_AVAILABLE
  8602. if (extraBrowser && extraBrowserMenuDocksSeparator.isNull())
  8603. extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator();
  8604. if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull())
  8605. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8606. dock->toggleViewAction());
  8607. else
  8608. ui->menuDocks->addAction(dock->toggleViewAction());
  8609. if (extraBrowser)
  8610. return;
  8611. #else
  8612. UNUSED_PARAMETER(extraBrowser);
  8613. ui->menuDocks->addAction(dock->toggleViewAction());
  8614. #endif
  8615. extraDockNames.push_back(dock->objectName());
  8616. extraDocks.push_back(std::shared_ptr<QDockWidget>(dock));
  8617. }
  8618. void OBSBasic::RemoveDockWidget(const QString &name)
  8619. {
  8620. if (extraDockNames.contains(name)) {
  8621. int idx = extraDockNames.indexOf(name);
  8622. extraDockNames.removeAt(idx);
  8623. extraDocks[idx].reset();
  8624. extraDocks.removeAt(idx);
  8625. } else if (extraCustomDockNames.contains(name)) {
  8626. int idx = extraCustomDockNames.indexOf(name);
  8627. extraCustomDockNames.removeAt(idx);
  8628. removeDockWidget(extraCustomDocks[idx]);
  8629. extraCustomDocks.removeAt(idx);
  8630. }
  8631. }
  8632. bool OBSBasic::IsDockObjectNameUsed(const QString &name)
  8633. {
  8634. QStringList list;
  8635. list << "scenesDock"
  8636. << "sourcesDock"
  8637. << "mixerDock"
  8638. << "transitionsDock"
  8639. << "controlsDock"
  8640. << "statsDock";
  8641. list << oldExtraDockNames;
  8642. list << extraDockNames;
  8643. list << extraCustomDockNames;
  8644. return list.contains(name);
  8645. }
  8646. void OBSBasic::AddCustomDockWidget(QDockWidget *dock)
  8647. {
  8648. // Prevent the object name from being changed
  8649. connect(dock, &QObject::objectNameChanged, this,
  8650. &OBSBasic::RepairCustomExtraDockName);
  8651. bool lock = ui->lockDocks->isChecked();
  8652. QDockWidget::DockWidgetFeatures features =
  8653. lock ? QDockWidget::NoDockWidgetFeatures
  8654. : (QDockWidget::DockWidgetClosable |
  8655. QDockWidget::DockWidgetMovable |
  8656. QDockWidget::DockWidgetFloatable);
  8657. dock->setFeatures(features);
  8658. addDockWidget(Qt::RightDockWidgetArea, dock);
  8659. extraCustomDockNames.push_back(dock->objectName());
  8660. extraCustomDocks.push_back(dock);
  8661. }
  8662. void OBSBasic::RepairCustomExtraDockName()
  8663. {
  8664. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8665. int idx = extraCustomDocks.indexOf(dock);
  8666. QSignalBlocker block(dock);
  8667. if (idx == -1) {
  8668. blog(LOG_WARNING, "A custom dock got its object name changed");
  8669. return;
  8670. }
  8671. blog(LOG_WARNING, "The custom dock '%s' got its object name restored",
  8672. QT_TO_UTF8(extraCustomDockNames[idx]));
  8673. dock->setObjectName(extraCustomDockNames[idx]);
  8674. }
  8675. OBSBasic *OBSBasic::Get()
  8676. {
  8677. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  8678. }
  8679. bool OBSBasic::StreamingActive()
  8680. {
  8681. if (!outputHandler)
  8682. return false;
  8683. return outputHandler->StreamingActive();
  8684. }
  8685. bool OBSBasic::RecordingActive()
  8686. {
  8687. if (!outputHandler)
  8688. return false;
  8689. return outputHandler->RecordingActive();
  8690. }
  8691. bool OBSBasic::ReplayBufferActive()
  8692. {
  8693. if (!outputHandler)
  8694. return false;
  8695. return outputHandler->ReplayBufferActive();
  8696. }
  8697. bool OBSBasic::VirtualCamActive()
  8698. {
  8699. if (!outputHandler)
  8700. return false;
  8701. return outputHandler->VirtualCamActive();
  8702. }
  8703. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  8704. : QStyledItemDelegate(parent)
  8705. {
  8706. }
  8707. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8708. const QModelIndex &index) const
  8709. {
  8710. QStyledItemDelegate::setEditorData(editor, index);
  8711. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8712. if (lineEdit)
  8713. lineEdit->selectAll();
  8714. }
  8715. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8716. {
  8717. if (event->type() == QEvent::KeyPress) {
  8718. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8719. switch (keyEvent->key()) {
  8720. case Qt::Key_Escape: {
  8721. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8722. if (lineEdit)
  8723. lineEdit->undo();
  8724. break;
  8725. }
  8726. case Qt::Key_Tab:
  8727. case Qt::Key_Backtab:
  8728. return false;
  8729. }
  8730. }
  8731. return QStyledItemDelegate::eventFilter(editor, event);
  8732. }
  8733. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8734. {
  8735. if (!error.isEmpty())
  8736. return;
  8737. patronJson = QT_TO_UTF8(text);
  8738. }
  8739. void OBSBasic::PauseRecording()
  8740. {
  8741. if (!isRecordingPausable || !outputHandler ||
  8742. !outputHandler->fileOutput ||
  8743. os_atomic_load_bool(&recording_paused))
  8744. return;
  8745. obs_output_t *output = outputHandler->fileOutput;
  8746. if (obs_output_pause(output, true)) {
  8747. os_atomic_set_bool(&recording_paused, true);
  8748. emit RecordingPaused();
  8749. ui->statusbar->RecordingPaused();
  8750. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8751. if (trayIcon && trayIcon->isVisible()) {
  8752. #ifdef __APPLE__
  8753. QIcon trayIconFile =
  8754. QIcon(":/res/images/obs_paused_macos.svg");
  8755. trayIconFile.setIsMask(true);
  8756. #else
  8757. QIcon trayIconFile =
  8758. QIcon(":/res/images/obs_paused.png");
  8759. #endif
  8760. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8761. trayIconFile));
  8762. }
  8763. OnEvent(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8764. if (os_atomic_load_bool(&replaybuf_active))
  8765. ShowReplayBufferPauseWarning();
  8766. }
  8767. }
  8768. void OBSBasic::UnpauseRecording()
  8769. {
  8770. if (!isRecordingPausable || !outputHandler ||
  8771. !outputHandler->fileOutput ||
  8772. !os_atomic_load_bool(&recording_paused))
  8773. return;
  8774. obs_output_t *output = outputHandler->fileOutput;
  8775. if (obs_output_pause(output, false)) {
  8776. os_atomic_set_bool(&recording_paused, false);
  8777. emit RecordingUnpaused();
  8778. ui->statusbar->RecordingUnpaused();
  8779. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8780. if (trayIcon && trayIcon->isVisible()) {
  8781. #ifdef __APPLE__
  8782. QIcon trayIconFile =
  8783. QIcon(":/res/images/tray_active_macos.svg");
  8784. trayIconFile.setIsMask(true);
  8785. #else
  8786. QIcon trayIconFile =
  8787. QIcon(":/res/images/tray_active.png");
  8788. #endif
  8789. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8790. trayIconFile));
  8791. }
  8792. OnEvent(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8793. }
  8794. }
  8795. void OBSBasic::RecordPauseToggled()
  8796. {
  8797. if (!isRecordingPausable || !outputHandler ||
  8798. !outputHandler->fileOutput)
  8799. return;
  8800. obs_output_t *output = outputHandler->fileOutput;
  8801. bool enable = !obs_output_paused(output);
  8802. if (enable)
  8803. PauseRecording();
  8804. else
  8805. UnpauseRecording();
  8806. }
  8807. void OBSBasic::UpdateIsRecordingPausable()
  8808. {
  8809. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8810. bool adv = astrcmpi(mode, "Advanced") == 0;
  8811. bool shared = true;
  8812. if (adv) {
  8813. const char *recType =
  8814. config_get_string(basicConfig, "AdvOut", "RecType");
  8815. if (astrcmpi(recType, "FFmpeg") == 0) {
  8816. shared = config_get_bool(basicConfig, "AdvOut",
  8817. "FFOutputToFile");
  8818. } else {
  8819. const char *recordEncoder = config_get_string(
  8820. basicConfig, "AdvOut", "RecEncoder");
  8821. shared = astrcmpi(recordEncoder, "none") == 0;
  8822. }
  8823. } else {
  8824. const char *quality = config_get_string(
  8825. basicConfig, "SimpleOutput", "RecQuality");
  8826. shared = strcmp(quality, "Stream") == 0;
  8827. }
  8828. isRecordingPausable = !shared;
  8829. }
  8830. #define MBYTE (1024ULL * 1024ULL)
  8831. #define MBYTES_LEFT_STOP_REC 50ULL
  8832. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8833. const char *OBSBasic::GetCurrentOutputPath()
  8834. {
  8835. const char *path = nullptr;
  8836. const char *mode = config_get_string(Config(), "Output", "Mode");
  8837. if (strcmp(mode, "Advanced") == 0) {
  8838. const char *advanced_mode =
  8839. config_get_string(Config(), "AdvOut", "RecType");
  8840. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8841. path = config_get_string(Config(), "AdvOut",
  8842. "FFFilePath");
  8843. } else {
  8844. path = config_get_string(Config(), "AdvOut",
  8845. "RecFilePath");
  8846. }
  8847. } else {
  8848. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8849. }
  8850. return path;
  8851. }
  8852. void OBSBasic::OutputPathInvalidMessage()
  8853. {
  8854. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8855. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8856. QTStr("Output.BadPath.Text"));
  8857. }
  8858. bool OBSBasic::IsFFmpegOutputToURL() const
  8859. {
  8860. const char *mode = config_get_string(Config(), "Output", "Mode");
  8861. if (strcmp(mode, "Advanced") == 0) {
  8862. const char *advanced_mode =
  8863. config_get_string(Config(), "AdvOut", "RecType");
  8864. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8865. bool is_local = config_get_bool(Config(), "AdvOut",
  8866. "FFOutputToFile");
  8867. if (!is_local)
  8868. return true;
  8869. }
  8870. }
  8871. return false;
  8872. }
  8873. bool OBSBasic::OutputPathValid()
  8874. {
  8875. if (IsFFmpegOutputToURL())
  8876. return true;
  8877. const char *path = GetCurrentOutputPath();
  8878. return path && *path && QDir(path).exists();
  8879. }
  8880. void OBSBasic::DiskSpaceMessage()
  8881. {
  8882. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8883. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8884. QTStr("Output.RecordNoSpace.Msg"));
  8885. }
  8886. bool OBSBasic::LowDiskSpace()
  8887. {
  8888. const char *path;
  8889. path = GetCurrentOutputPath();
  8890. if (!path)
  8891. return false;
  8892. uint64_t num_bytes = os_get_free_disk_space(path);
  8893. if (num_bytes < (MAX_BYTES_LEFT))
  8894. return true;
  8895. else
  8896. return false;
  8897. }
  8898. void OBSBasic::CheckDiskSpaceRemaining()
  8899. {
  8900. if (LowDiskSpace()) {
  8901. StopRecording();
  8902. StopReplayBuffer();
  8903. DiskSpaceMessage();
  8904. }
  8905. }
  8906. void OBSBasic::ResetStatsHotkey()
  8907. {
  8908. const QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8909. for (OBSBasicStats *s : list) {
  8910. s->Reset();
  8911. }
  8912. }
  8913. void OBSBasic::on_OBSBasic_customContextMenuRequested(const QPoint &pos)
  8914. {
  8915. QWidget *widget = childAt(pos);
  8916. const char *className = nullptr;
  8917. QString objName;
  8918. if (widget != nullptr) {
  8919. className = widget->metaObject()->className();
  8920. objName = widget->objectName();
  8921. }
  8922. QPoint globalPos = mapToGlobal(pos);
  8923. if (className && strstr(className, "Dock") != nullptr &&
  8924. !objName.isEmpty()) {
  8925. if (objName.compare("scenesDock") == 0) {
  8926. ui->scenes->customContextMenuRequested(globalPos);
  8927. } else if (objName.compare("sourcesDock") == 0) {
  8928. ui->sources->customContextMenuRequested(globalPos);
  8929. } else if (objName.compare("mixerDock") == 0) {
  8930. StackedMixerAreaContextMenuRequested();
  8931. }
  8932. } else if (!className) {
  8933. ui->menuDocks->exec(globalPos);
  8934. }
  8935. }
  8936. void OBSBasic::UpdateProjectorHideCursor()
  8937. {
  8938. for (size_t i = 0; i < projectors.size(); i++)
  8939. projectors[i]->SetHideCursor();
  8940. }
  8941. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8942. {
  8943. for (size_t i = 0; i < projectors.size(); i++)
  8944. SetAlwaysOnTop(projectors[i], top);
  8945. }
  8946. void OBSBasic::ResetProjectors()
  8947. {
  8948. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8949. ClearProjectors();
  8950. LoadSavedProjectors(savedProjectorList);
  8951. OpenSavedProjectors();
  8952. }
  8953. void OBSBasic::on_sourcePropertiesButton_clicked()
  8954. {
  8955. on_actionSourceProperties_triggered();
  8956. }
  8957. void OBSBasic::on_sourceFiltersButton_clicked()
  8958. {
  8959. OpenFilters();
  8960. }
  8961. void OBSBasic::on_actionSceneFilters_triggered()
  8962. {
  8963. OBSSource sceneSource = GetCurrentSceneSource();
  8964. if (sceneSource)
  8965. OpenFilters(sceneSource);
  8966. }
  8967. void OBSBasic::on_sourceInteractButton_clicked()
  8968. {
  8969. on_actionInteract_triggered();
  8970. }
  8971. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8972. {
  8973. ui->statusbar->clearMessage();
  8974. ui->statusbar->showMessage(message, 10000);
  8975. }
  8976. void OBSBasic::UpdatePreviewSafeAreas()
  8977. {
  8978. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8979. "ShowSafeAreas");
  8980. }
  8981. void OBSBasic::UpdatePreviewOverflowSettings()
  8982. {
  8983. bool hidden = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8984. "OverflowHidden");
  8985. bool select = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8986. "OverflowSelectionHidden");
  8987. bool always = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8988. "OverflowAlwaysVisible");
  8989. ui->preview->SetOverflowHidden(hidden);
  8990. ui->preview->SetOverflowSelectionHidden(select);
  8991. ui->preview->SetOverflowAlwaysVisible(always);
  8992. }
  8993. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8994. {
  8995. if (!SetDisplayAffinitySupported())
  8996. return;
  8997. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8998. "BasicWindow",
  8999. "HideOBSWindowsFromCapture");
  9000. // Don't hide projectors, those are designed to be visible / captured
  9001. if (window->property("isOBSProjectorWindow") == true)
  9002. return;
  9003. #ifdef _WIN32
  9004. HWND hwnd = (HWND)window->winId();
  9005. DWORD curAffinity;
  9006. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  9007. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  9008. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  9009. else if (!hideFromCapture && curAffinity != WDA_NONE)
  9010. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  9011. }
  9012. #else
  9013. // TODO: Implement for other platforms if possible. Don't forget to
  9014. // implement SetDisplayAffinitySupported too!
  9015. UNUSED_PARAMETER(hideFromCapture);
  9016. #endif
  9017. }
  9018. static inline QColor color_from_int(long long val)
  9019. {
  9020. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  9021. (val >> 24) & 0xff);
  9022. }
  9023. QColor OBSBasic::GetSelectionColor() const
  9024. {
  9025. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9026. "OverrideColors")) {
  9027. return color_from_int(config_get_int(
  9028. GetGlobalConfig(), "Accessibility", "SelectRed"));
  9029. } else {
  9030. return QColor::fromRgb(255, 0, 0);
  9031. }
  9032. }
  9033. QColor OBSBasic::GetCropColor() const
  9034. {
  9035. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9036. "OverrideColors")) {
  9037. return color_from_int(config_get_int(
  9038. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  9039. } else {
  9040. return QColor::fromRgb(0, 255, 0);
  9041. }
  9042. }
  9043. QColor OBSBasic::GetHoverColor() const
  9044. {
  9045. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9046. "OverrideColors")) {
  9047. return color_from_int(config_get_int(
  9048. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  9049. } else {
  9050. return QColor::fromRgb(0, 127, 255);
  9051. }
  9052. }
  9053. void OBSBasic::UpdatePreviewSpacingHelpers()
  9054. {
  9055. drawSpacingHelpers = config_get_bool(
  9056. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  9057. }
  9058. float OBSBasic::GetDevicePixelRatio()
  9059. {
  9060. return dpi;
  9061. }
  9062. void OBSBasic::OnEvent(enum obs_frontend_event event)
  9063. {
  9064. if (api)
  9065. api->on_event(event);
  9066. }