window-basic-main.cpp 114 KB

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