window-basic-main.cpp 102 KB

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