window-basic-main.cpp 85 KB

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