window-basic-main.cpp 89 KB

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