window-basic-main.cpp 86 KB

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