window-basic-main.cpp 302 KB

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