window-basic-main.cpp 138 KB

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