window-basic-main.cpp 91 KB

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