window-basic-main.cpp 107 KB

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