window-basic-main.cpp 165 KB

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