window-basic-main.cpp 115 KB

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