window-basic-main.cpp 175 KB

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