window-basic-main.cpp 93 KB

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