1
0

window-basic-main.cpp 91 KB

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