window-basic-main.cpp 86 KB

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