window-basic-main.cpp 90 KB

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