window-basic-main.cpp 90 KB

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