window-basic-main.cpp 85 KB

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