window-basic-main.cpp 91 KB

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