window-basic-main.cpp 101 KB

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