window-basic-main.cpp 86 KB

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