window-basic-main.cpp 93 KB

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