window-basic-main.cpp 86 KB

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