window-basic-main.cpp 102 KB

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