window-basic-main.cpp 90 KB

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