window-basic-main.cpp 91 KB

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