window-basic-main.cpp 147 KB

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