window-basic-main.cpp 93 KB

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