window-basic-main.cpp 84 KB

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