window-basic-main.cpp 97 KB

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