window-basic-main.cpp 97 KB

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