window-basic-main.cpp 84 KB

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