window-basic-main.cpp 130 KB

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