window-basic-main.cpp 97 KB

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