window-basic-main.cpp 106 KB

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