window-basic-main.cpp 86 KB

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