1
0

window-basic-main.cpp 106 KB

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