window-basic-main.cpp 203 KB

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