window-basic-main.cpp 85 KB

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