window-basic-main.cpp 90 KB

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