window-basic-main.cpp 182 KB

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