window-basic-main.cpp 136 KB

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