window-basic-main.cpp 102 KB

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