window-basic-main.cpp 182 KB

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