window-basic-main.cpp 91 KB

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