window-basic-main.cpp 91 KB

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