window-basic-main.cpp 109 KB

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