window-basic-main.cpp 91 KB

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