window-basic-main.cpp 201 KB

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