window-basic-main.cpp 105 KB

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