window-basic-main.cpp 85 KB

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