window-basic-main.cpp 164 KB

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