window-basic-main.cpp 85 KB

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