window-basic-main.cpp 123 KB

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