window-basic-main.cpp 172 KB

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