window-basic-main.cpp 90 KB

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