window-basic-main.cpp 154 KB

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