window-basic-main.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745
  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 <QNetworkRequest>
  23. #include <QNetworkReply>
  24. #include <util/dstr.h>
  25. #include <util/util.hpp>
  26. #include <util/platform.h>
  27. #include <graphics/math-defs.h>
  28. #include "obs-app.hpp"
  29. #include "platform.hpp"
  30. #include "visibility-item-widget.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-remux.hpp"
  39. #include "qt-wrappers.hpp"
  40. #include "display-helpers.hpp"
  41. #include "volume-control.hpp"
  42. #include "ui_OBSBasic.h"
  43. #include <fstream>
  44. #include <sstream>
  45. #include <QScreen>
  46. #include <QWindow>
  47. #define PREVIEW_EDGE_SIZE 10
  48. using namespace std;
  49. Q_DECLARE_METATYPE(OBSScene);
  50. Q_DECLARE_METATYPE(OBSSceneItem);
  51. Q_DECLARE_METATYPE(OBSSource);
  52. Q_DECLARE_METATYPE(obs_order_movement);
  53. static void AddExtraModulePaths()
  54. {
  55. char base_module_dir[512];
  56. int ret = os_get_config_path(base_module_dir, sizeof(base_module_dir),
  57. "obs-studio/plugins/%module%");
  58. if (ret <= 0)
  59. return;
  60. string path = (char*)base_module_dir;
  61. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  62. }
  63. static QList<QKeySequence> DeleteKeys;
  64. OBSBasic::OBSBasic(QWidget *parent)
  65. : OBSMainWindow (parent),
  66. ui (new Ui::OBSBasic)
  67. {
  68. ui->setupUi(this);
  69. copyActionsDynamicProperties();
  70. ui->sources->setItemDelegate(new VisibilityItemDelegate(ui->sources));
  71. int width = config_get_int(App()->GlobalConfig(), "BasicWindow", "cx");
  72. // Check if no values are saved (new installation).
  73. if (width != 0) {
  74. int height = config_get_int(App()->GlobalConfig(),
  75. "BasicWindow", "cy");
  76. int posx = config_get_int(App()->GlobalConfig(), "BasicWindow",
  77. "posx");
  78. int posy = config_get_int(App()->GlobalConfig(), "BasicWindow",
  79. "posy");
  80. setGeometry(posx, posy, width, height);
  81. }
  82. char styleSheetPath[512];
  83. int ret = os_get_config_path(styleSheetPath, sizeof(styleSheetPath),
  84. "obs-studio/basic/stylesheet.qss");
  85. if (ret > 0) {
  86. if (QFile::exists(styleSheetPath)) {
  87. QString path = QString("file:///") +
  88. QT_UTF8(styleSheetPath);
  89. App()->setStyleSheet(path);
  90. }
  91. }
  92. qRegisterMetaType<OBSScene> ("OBSScene");
  93. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  94. qRegisterMetaType<OBSSource> ("OBSSource");
  95. connect(windowHandle(), &QWindow::screenChanged, [this]() {
  96. struct obs_video_info ovi;
  97. if (obs_get_video_info(&ovi))
  98. ResizePreview(ovi.base_width, ovi.base_height);
  99. });
  100. stringstream name;
  101. name << "OBS " << App()->GetVersionString();
  102. blog(LOG_INFO, "%s", name.str().c_str());
  103. setWindowTitle(QT_UTF8(name.str().c_str()));
  104. connect(ui->scenes->itemDelegate(),
  105. SIGNAL(closeEditor(QWidget*,
  106. QAbstractItemDelegate::EndEditHint)),
  107. this,
  108. SLOT(SceneNameEdited(QWidget*,
  109. QAbstractItemDelegate::EndEditHint)));
  110. connect(ui->sources->itemDelegate(),
  111. SIGNAL(closeEditor(QWidget*,
  112. QAbstractItemDelegate::EndEditHint)),
  113. this,
  114. SLOT(SceneItemNameEdited(QWidget*,
  115. QAbstractItemDelegate::EndEditHint)));
  116. cpuUsageInfo = os_cpu_usage_info_start();
  117. cpuUsageTimer = new QTimer(this);
  118. connect(cpuUsageTimer, SIGNAL(timeout()),
  119. ui->statusbar, SLOT(UpdateCPUUsage()));
  120. cpuUsageTimer->start(3000);
  121. DeleteKeys =
  122. #ifdef __APPLE__
  123. QList<QKeySequence>{{Qt::Key_Backspace}} <<
  124. #endif
  125. QKeySequence::keyBindings(QKeySequence::Delete);
  126. #ifdef __APPLE__
  127. ui->actionRemoveSource->setShortcuts(DeleteKeys);
  128. ui->actionRemoveScene->setShortcuts(DeleteKeys);
  129. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  130. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  131. #endif
  132. }
  133. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent)
  134. {
  135. obs_source_t *source = obs_get_output_source(channel);
  136. if (!source)
  137. return;
  138. obs_data_t *data = obs_save_source(source);
  139. obs_data_set_obj(parent, name, data);
  140. obs_data_release(data);
  141. obs_source_release(source);
  142. }
  143. static obs_data_t *GenerateSaveData()
  144. {
  145. obs_data_t *saveData = obs_data_create();
  146. obs_data_array_t *sourcesArray = obs_save_sources();
  147. obs_source_t *currentScene = obs_get_output_source(0);
  148. const char *sceneName = obs_source_get_name(currentScene);
  149. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData);
  150. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData);
  151. SaveAudioDevice(AUX_AUDIO_1, 3, saveData);
  152. SaveAudioDevice(AUX_AUDIO_2, 4, saveData);
  153. SaveAudioDevice(AUX_AUDIO_3, 5, saveData);
  154. obs_data_set_string(saveData, "current_scene", sceneName);
  155. obs_data_set_array(saveData, "sources", sourcesArray);
  156. obs_data_array_release(sourcesArray);
  157. obs_source_release(currentScene);
  158. return saveData;
  159. }
  160. void OBSBasic::copyActionsDynamicProperties()
  161. {
  162. // Themes need the QAction dynamic properties
  163. for (QAction *x : ui->scenesToolbar->actions()) {
  164. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  165. for (QByteArray &y : x->dynamicPropertyNames()) {
  166. temp->setProperty(y, x->property(y));
  167. }
  168. }
  169. for (QAction *x : ui->sourcesToolbar->actions()) {
  170. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  171. for (QByteArray &y : x->dynamicPropertyNames()) {
  172. temp->setProperty(y, x->property(y));
  173. }
  174. }
  175. }
  176. void OBSBasic::ClearVolumeControls()
  177. {
  178. VolControl *control;
  179. for (size_t i = 0; i < volumes.size(); i++) {
  180. control = volumes[i];
  181. delete control;
  182. }
  183. volumes.clear();
  184. }
  185. void OBSBasic::Save(const char *file)
  186. {
  187. obs_data_t *saveData = GenerateSaveData();
  188. const char *jsonData = obs_data_get_json(saveData);
  189. if (!!jsonData) {
  190. /* TODO: maybe a message box here? */
  191. bool success = os_quick_write_utf8_file(file, jsonData,
  192. strlen(jsonData), false);
  193. if (!success)
  194. blog(LOG_ERROR, "Could not save scene data to %s",
  195. file);
  196. }
  197. obs_data_release(saveData);
  198. }
  199. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  200. {
  201. obs_data_t *data = obs_data_get_obj(parent, name);
  202. if (!data)
  203. return;
  204. obs_source_t *source = obs_load_source(data);
  205. if (source) {
  206. obs_set_output_source(channel, source);
  207. obs_source_release(source);
  208. }
  209. obs_data_release(data);
  210. }
  211. void OBSBasic::CreateDefaultScene()
  212. {
  213. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  214. obs_source_t *source = obs_scene_get_source(scene);
  215. obs_add_source(source);
  216. #ifdef __APPLE__
  217. source = obs_source_create(OBS_SOURCE_TYPE_INPUT, "display_capture",
  218. Str("Basic.DisplayCapture"), NULL);
  219. if (source) {
  220. obs_scene_add(scene, source);
  221. obs_add_source(source);
  222. obs_source_release(source);
  223. }
  224. #endif
  225. obs_set_output_source(0, obs_scene_get_source(scene));
  226. obs_scene_release(scene);
  227. }
  228. void OBSBasic::Load(const char *file)
  229. {
  230. if (!file) {
  231. blog(LOG_ERROR, "Could not find file %s", file);
  232. return;
  233. }
  234. BPtr<char> jsonData = os_quick_read_utf8_file(file);
  235. if (!jsonData) {
  236. CreateDefaultScene();
  237. return;
  238. }
  239. obs_data_t *data = obs_data_create_from_json(jsonData);
  240. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  241. const char *sceneName = obs_data_get_string(data,
  242. "current_scene");
  243. obs_source_t *curScene;
  244. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  245. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  246. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  247. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  248. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  249. obs_load_sources(sources);
  250. curScene = obs_get_source_by_name(sceneName);
  251. obs_set_output_source(0, curScene);
  252. obs_source_release(curScene);
  253. obs_data_array_release(sources);
  254. obs_data_release(data);
  255. }
  256. static inline bool HasAudioDevices(const char *source_id)
  257. {
  258. const char *output_id = source_id;
  259. obs_properties_t *props = obs_get_source_properties(
  260. OBS_SOURCE_TYPE_INPUT, output_id);
  261. size_t count = 0;
  262. if (!props)
  263. return false;
  264. obs_property_t *devices = obs_properties_get(props, "device_id");
  265. if (devices)
  266. count = obs_property_list_item_count(devices);
  267. obs_properties_destroy(props);
  268. return count != 0;
  269. }
  270. #define SERVICE_PATH "obs-studio/basic/service.json"
  271. void OBSBasic::SaveService()
  272. {
  273. if (!service)
  274. return;
  275. char serviceJsonPath[512];
  276. int ret = os_get_config_path(serviceJsonPath, sizeof(serviceJsonPath),
  277. SERVICE_PATH);
  278. if (ret <= 0)
  279. return;
  280. obs_data_t *data = obs_data_create();
  281. obs_data_t *settings = obs_service_get_settings(service);
  282. obs_data_set_string(data, "type", obs_service_get_type(service));
  283. obs_data_set_obj(data, "settings", settings);
  284. const char *json = obs_data_get_json(data);
  285. os_quick_write_utf8_file(serviceJsonPath, json, strlen(json), false);
  286. obs_data_release(settings);
  287. obs_data_release(data);
  288. }
  289. bool OBSBasic::LoadService()
  290. {
  291. const char *type;
  292. if (service) {
  293. obs_service_destroy(service);
  294. service = nullptr;
  295. }
  296. char serviceJsonPath[512];
  297. int ret = os_get_config_path(serviceJsonPath, sizeof(serviceJsonPath),
  298. SERVICE_PATH);
  299. if (ret <= 0)
  300. return false;
  301. BPtr<char> jsonText = os_quick_read_utf8_file(serviceJsonPath);
  302. if (!jsonText)
  303. return false;
  304. obs_data_t *data = obs_data_create_from_json(jsonText);
  305. obs_data_set_default_string(data, "type", "rtmp_common");
  306. type = obs_data_get_string(data, "type");
  307. obs_data_t *settings = obs_data_get_obj(data, "settings");
  308. service = obs_service_create(type, "default_service", settings);
  309. obs_data_release(settings);
  310. obs_data_release(data);
  311. return !!service;
  312. }
  313. bool OBSBasic::InitService()
  314. {
  315. if (LoadService())
  316. return true;
  317. service = obs_service_create("rtmp_common", "default_service", nullptr);
  318. if (!service)
  319. return false;
  320. return true;
  321. }
  322. bool OBSBasic::InitBasicConfigDefaults()
  323. {
  324. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  325. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  326. vector<MonitorInfo> monitors;
  327. GetMonitors(monitors);
  328. if (!monitors.size()) {
  329. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  330. "technically shouldn't be possible.");
  331. return false;
  332. }
  333. uint32_t cx = monitors[0].cx;
  334. uint32_t cy = monitors[0].cy;
  335. config_set_default_string(basicConfig, "Output", "Type", "Simple");
  336. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  337. GetDefaultVideoSavePath().c_str());
  338. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  339. 2500);
  340. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 128);
  341. config_set_default_bool (basicConfig, "SimpleOutput", "Reconnect",
  342. true);
  343. config_set_default_uint (basicConfig, "SimpleOutput", "RetryDelay",
  344. 10);
  345. config_set_default_uint (basicConfig, "SimpleOutput", "MaxRetries",
  346. 20);
  347. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  348. false);
  349. config_set_default_bool (basicConfig, "SimpleOutput", "UseCBR", true);
  350. config_set_default_bool (basicConfig, "SimpleOutput", "UseBufsize",
  351. false);
  352. config_set_default_int (basicConfig, "SimpleOutput", "Bufsize", 2500);
  353. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  354. "veryfast");
  355. config_set_default_bool (basicConfig, "AdvOut", "Reconnect", true);
  356. config_set_default_uint (basicConfig, "AdvOut", "RetryDelay", 10);
  357. config_set_default_uint (basicConfig, "AdvOut", "MaxRetries", 20);
  358. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  359. true);
  360. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  361. config_set_default_bool (basicConfig, "AdvOut", "Multitrack", false);
  362. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  363. config_set_default_uint (basicConfig, "AdvOut", "TrackCount", 1);
  364. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  365. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  366. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  367. GetDefaultVideoSavePath().c_str());
  368. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  369. false);
  370. config_set_default_bool (basicConfig, "AdvOut", "RecMultitrack",
  371. false);
  372. config_set_default_uint (basicConfig, "AdvOut", "RecTrackIndex", 1);
  373. config_set_default_uint (basicConfig, "AdvOut", "RecTrackCount", 1);
  374. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  375. "none");
  376. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  377. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  378. false);
  379. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  380. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  381. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  382. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  383. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  384. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  385. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  386. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  387. cx = cx * 10 / 15;
  388. cy = cy * 10 / 15;
  389. config_set_default_uint (basicConfig, "Video", "OutputCX", cx);
  390. config_set_default_uint (basicConfig, "Video", "OutputCY", cy);
  391. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  392. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  393. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  394. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  395. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  396. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  397. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  398. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  399. config_set_default_string(basicConfig, "Video", "ColorRange",
  400. "Partial");
  401. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  402. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  403. "Stereo");
  404. config_set_default_uint (basicConfig, "Audio", "BufferingTime", 1000);
  405. config_set_default_string(basicConfig, "Audio", "DesktopDevice1",
  406. hasDesktopAudio ? "default" : "disabled");
  407. config_set_default_string(basicConfig, "Audio", "DesktopDevice2",
  408. "disabled");
  409. config_set_default_string(basicConfig, "Audio", "AuxDevice1",
  410. hasInputAudio ? "default" : "disabled");
  411. config_set_default_string(basicConfig, "Audio", "AuxDevice2",
  412. "disabled");
  413. config_set_default_string(basicConfig, "Audio", "AuxDevice3",
  414. "disabled");
  415. return true;
  416. }
  417. bool OBSBasic::InitBasicConfig()
  418. {
  419. char configPath[512];
  420. int ret = os_get_config_path(configPath, sizeof(configPath),
  421. "obs-studio/basic/basic.ini");
  422. if (ret <= 0) {
  423. OBSErrorBox(nullptr, "Failed to get base.ini path");
  424. return false;
  425. }
  426. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  427. if (code != CONFIG_SUCCESS) {
  428. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  429. return false;
  430. }
  431. return InitBasicConfigDefaults();
  432. }
  433. void OBSBasic::InitOBSCallbacks()
  434. {
  435. signal_handler_connect(obs_get_signal_handler(), "source_add",
  436. OBSBasic::SourceAdded, this);
  437. signal_handler_connect(obs_get_signal_handler(), "source_remove",
  438. OBSBasic::SourceRemoved, this);
  439. signal_handler_connect(obs_get_signal_handler(), "channel_change",
  440. OBSBasic::ChannelChanged, this);
  441. signal_handler_connect(obs_get_signal_handler(), "source_activate",
  442. OBSBasic::SourceActivated, this);
  443. signal_handler_connect(obs_get_signal_handler(), "source_deactivate",
  444. OBSBasic::SourceDeactivated, this);
  445. signal_handler_connect(obs_get_signal_handler(), "source_rename",
  446. OBSBasic::SourceRenamed, this);
  447. }
  448. void OBSBasic::InitPrimitives()
  449. {
  450. obs_enter_graphics();
  451. gs_render_start(true);
  452. gs_vertex2f(0.0f, 0.0f);
  453. gs_vertex2f(0.0f, 1.0f);
  454. gs_vertex2f(1.0f, 1.0f);
  455. gs_vertex2f(1.0f, 0.0f);
  456. gs_vertex2f(0.0f, 0.0f);
  457. box = gs_render_save();
  458. gs_render_start(true);
  459. for (int i = 0; i <= 360; i += (360/20)) {
  460. float pos = RAD(float(i));
  461. gs_vertex2f(cosf(pos), sinf(pos));
  462. }
  463. circle = gs_render_save();
  464. obs_leave_graphics();
  465. }
  466. void OBSBasic::ResetOutputs()
  467. {
  468. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  469. bool advOut = astrcmpi(mode, "Advanced") == 0;
  470. if (!outputHandler || !outputHandler->Active()) {
  471. outputHandler.reset();
  472. outputHandler.reset(advOut ?
  473. CreateAdvancedOutputHandler(this) :
  474. CreateSimpleOutputHandler(this));
  475. } else {
  476. outputHandler->Update();
  477. }
  478. }
  479. void OBSBasic::OBSInit()
  480. {
  481. char savePath[512];
  482. int ret = os_get_config_path(savePath, sizeof(savePath),
  483. "obs-studio/basic/scenes.json");
  484. if (ret <= 0)
  485. throw "Failed to get scenes.json file path";
  486. /* make sure it's fully displayed before doing any initialization */
  487. show();
  488. App()->processEvents();
  489. if (!obs_startup(App()->GetLocale()))
  490. throw "Failed to initialize libobs";
  491. if (!InitBasicConfig())
  492. throw "Failed to load basic.ini";
  493. if (!ResetAudio())
  494. throw "Failed to initialize audio";
  495. ret = ResetVideo();
  496. switch (ret) {
  497. case OBS_VIDEO_MODULE_NOT_FOUND:
  498. throw "Failed to initialize video: Graphics module not found";
  499. case OBS_VIDEO_NOT_SUPPORTED:
  500. throw "Failed to initialize video: Required graphics API "
  501. "functionality not found on these drivers or "
  502. "unavailable on this equipment";
  503. case OBS_VIDEO_INVALID_PARAM:
  504. throw "Failed to initialize video: Invalid parameters";
  505. default:
  506. if (ret != OBS_VIDEO_SUCCESS)
  507. throw "Failed to initialize video: Unspecified error";
  508. }
  509. InitOBSCallbacks();
  510. AddExtraModulePaths();
  511. obs_load_all_modules();
  512. ResetOutputs();
  513. if (!InitService())
  514. throw "Failed to initialize service";
  515. InitPrimitives();
  516. Load(savePath);
  517. ResetAudioDevices();
  518. TimedCheckForUpdates();
  519. loaded = true;
  520. saveTimer = new QTimer(this);
  521. connect(saveTimer, SIGNAL(timeout()), this, SLOT(SaveProject()));
  522. saveTimer->start(20000);
  523. }
  524. OBSBasic::~OBSBasic()
  525. {
  526. /* XXX: any obs data must be released before calling obs_shutdown.
  527. * currently, we can't automate this with C++ RAII because of the
  528. * delicate nature of obs_shutdown needing to be freed before the UI
  529. * can be freed, and we have no control over the destruction order of
  530. * the Qt UI stuff, so we have to manually clear any references to
  531. * libobs. */
  532. delete cpuUsageTimer;
  533. os_cpu_usage_info_destroy(cpuUsageInfo);
  534. outputHandler.reset();
  535. if (interaction)
  536. delete interaction;
  537. if (properties)
  538. delete properties;
  539. if (filters)
  540. delete filters;
  541. if (transformWindow)
  542. delete transformWindow;
  543. if (advAudioWindow)
  544. delete advAudioWindow;
  545. obs_enter_graphics();
  546. gs_vertexbuffer_destroy(box);
  547. gs_vertexbuffer_destroy(circle);
  548. obs_leave_graphics();
  549. /* When shutting down, sometimes source references can get in to the
  550. * event queue, and if we don't forcibly process those events they
  551. * won't get processed until after obs_shutdown has been called. I
  552. * really wish there were a more elegant way to deal with this via C++,
  553. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  554. * normal C++ behavior for your data to be freed in the order that you
  555. * expect or want it to. */
  556. QApplication::sendPostedEvents(this);
  557. obs_shutdown();
  558. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  559. LIBOBS_API_VER);
  560. QRect lastGeom = normalGeometry();
  561. config_set_int(App()->GlobalConfig(), "BasicWindow", "cx",
  562. lastGeom.width());
  563. config_set_int(App()->GlobalConfig(), "BasicWindow", "cy",
  564. lastGeom.height());
  565. config_set_int(App()->GlobalConfig(), "BasicWindow", "posx",
  566. lastGeom.x());
  567. config_set_int(App()->GlobalConfig(), "BasicWindow", "posy",
  568. lastGeom.y());
  569. config_save(App()->GlobalConfig());
  570. }
  571. void OBSBasic::SaveProject()
  572. {
  573. char savePath[512];
  574. int ret = os_get_config_path(savePath, sizeof(savePath),
  575. "obs-studio/basic/scenes.json");
  576. if (ret <= 0)
  577. return;
  578. Save(savePath);
  579. }
  580. OBSScene OBSBasic::GetCurrentScene()
  581. {
  582. QListWidgetItem *item = ui->scenes->currentItem();
  583. return item ? item->data(Qt::UserRole).value<OBSScene>() : nullptr;
  584. }
  585. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  586. {
  587. return item ? item->data(Qt::UserRole).value<OBSSceneItem>() : nullptr;
  588. }
  589. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  590. {
  591. return GetSceneItem(ui->sources->currentItem());
  592. }
  593. void OBSBasic::UpdateSources(OBSScene scene)
  594. {
  595. ui->sources->clear();
  596. obs_scene_enum_items(scene,
  597. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  598. {
  599. OBSBasic *window = static_cast<OBSBasic*>(p);
  600. window->InsertSceneItem(item);
  601. UNUSED_PARAMETER(scene);
  602. return true;
  603. }, this);
  604. }
  605. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  606. {
  607. obs_source_t *source = obs_sceneitem_get_source(item);
  608. QListWidgetItem *listItem = new QListWidgetItem();
  609. listItem->setData(Qt::UserRole,
  610. QVariant::fromValue(OBSSceneItem(item)));
  611. ui->sources->insertItem(0, listItem);
  612. ui->sources->setCurrentRow(0);
  613. SetupVisibilityItem(ui->sources, listItem, item);
  614. /* if the source was just created, open properties dialog */
  615. if (sourceSceneRefs[source] == 0 && loaded)
  616. CreatePropertiesWindow(source);
  617. }
  618. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  619. {
  620. if (interaction)
  621. interaction->close();
  622. interaction = new OBSBasicInteraction(this, source);
  623. interaction->Init();
  624. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  625. }
  626. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  627. {
  628. if (properties)
  629. properties->close();
  630. properties = new OBSBasicProperties(this, source);
  631. properties->Init();
  632. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  633. }
  634. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  635. {
  636. if (filters)
  637. filters->close();
  638. filters = new OBSBasicFilters(this, source);
  639. filters->Init();
  640. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  641. }
  642. /* Qt callbacks for invokeMethod */
  643. void OBSBasic::AddScene(OBSSource source)
  644. {
  645. const char *name = obs_source_get_name(source);
  646. obs_scene_t *scene = obs_scene_from_source(source);
  647. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  648. item->setData(Qt::UserRole, QVariant::fromValue(OBSScene(scene)));
  649. ui->scenes->addItem(item);
  650. signal_handler_t *handler = obs_source_get_signal_handler(source);
  651. signal_handler_connect(handler, "item_add",
  652. OBSBasic::SceneItemAdded, this);
  653. signal_handler_connect(handler, "item_remove",
  654. OBSBasic::SceneItemRemoved, this);
  655. signal_handler_connect(handler, "item_select",
  656. OBSBasic::SceneItemSelected, this);
  657. signal_handler_connect(handler, "item_deselect",
  658. OBSBasic::SceneItemDeselected, this);
  659. signal_handler_connect(handler, "reorder",
  660. OBSBasic::SceneReordered, this);
  661. }
  662. void OBSBasic::RemoveScene(OBSSource source)
  663. {
  664. const char *name = obs_source_get_name(source);
  665. QListWidgetItem *sel = ui->scenes->currentItem();
  666. QList<QListWidgetItem*> items = ui->scenes->findItems(QT_UTF8(name),
  667. Qt::MatchExactly);
  668. if (sel != nullptr) {
  669. if (items.contains(sel))
  670. ui->sources->clear();
  671. delete sel;
  672. }
  673. }
  674. void OBSBasic::AddSceneItem(OBSSceneItem item)
  675. {
  676. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  677. obs_source_t *source = obs_sceneitem_get_source(item);
  678. if (GetCurrentScene() == scene)
  679. InsertSceneItem(item);
  680. sourceSceneRefs[source] = sourceSceneRefs[source] + 1;
  681. }
  682. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  683. {
  684. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  685. if (GetCurrentScene() == scene) {
  686. for (int i = 0; i < ui->sources->count(); i++) {
  687. QListWidgetItem *listItem = ui->sources->item(i);
  688. QVariant userData = listItem->data(Qt::UserRole);
  689. if (userData.value<OBSSceneItem>() == item) {
  690. delete listItem;
  691. break;
  692. }
  693. }
  694. }
  695. obs_source_t *source = obs_sceneitem_get_source(item);
  696. int scenes = sourceSceneRefs[source] - 1;
  697. sourceSceneRefs[source] = scenes;
  698. if (scenes == 0) {
  699. obs_source_remove(source);
  700. sourceSceneRefs.erase(source);
  701. }
  702. }
  703. void OBSBasic::UpdateSceneSelection(OBSSource source)
  704. {
  705. if (source) {
  706. obs_scene_t *scene = obs_scene_from_source(source);
  707. const char *name = obs_source_get_name(source);
  708. if (!scene)
  709. return;
  710. QList<QListWidgetItem*> items =
  711. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  712. if (items.count()) {
  713. sceneChanging = true;
  714. ui->scenes->setCurrentItem(items.first());
  715. sceneChanging = false;
  716. UpdateSources(scene);
  717. }
  718. }
  719. }
  720. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  721. const QString &prevName)
  722. {
  723. QList<QListWidgetItem*> items =
  724. listWidget->findItems(prevName, Qt::MatchExactly);
  725. for (int i = 0; i < items.count(); i++)
  726. items[i]->setText(newName);
  727. }
  728. void OBSBasic::RenameSources(QString newName, QString prevName)
  729. {
  730. RenameListValues(ui->scenes, newName, prevName);
  731. for (size_t i = 0; i < volumes.size(); i++) {
  732. if (volumes[i]->GetName().compare(prevName) == 0)
  733. volumes[i]->SetName(newName);
  734. }
  735. }
  736. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  737. {
  738. if (scene != GetCurrentScene())
  739. return;
  740. for (int i = 0; i < ui->sources->count(); i++) {
  741. QListWidgetItem *witem = ui->sources->item(i);
  742. QVariant data = witem->data(Qt::UserRole);
  743. if (!data.canConvert<OBSSceneItem>())
  744. continue;
  745. if (item != data.value<OBSSceneItem>())
  746. continue;
  747. if (select) {
  748. ui->sources->setCurrentItem(witem);
  749. } else if (ui->sources->currentItem() == witem) {
  750. ui->sources->setCurrentItem(nullptr);
  751. }
  752. break;
  753. }
  754. }
  755. void OBSBasic::MoveSceneItem(OBSSceneItem item, obs_order_movement movement)
  756. {
  757. OBSScene scene = obs_sceneitem_get_scene(item);
  758. if (scene != GetCurrentScene())
  759. return;
  760. int curRow = ui->sources->currentRow();
  761. if (curRow == -1)
  762. return;
  763. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  764. switch (movement) {
  765. case OBS_ORDER_MOVE_UP:
  766. if (curRow > 0)
  767. curRow--;
  768. break;
  769. case OBS_ORDER_MOVE_DOWN:
  770. if (curRow < ui->sources->count())
  771. curRow++;
  772. break;
  773. case OBS_ORDER_MOVE_TOP:
  774. curRow = 0;
  775. break;
  776. case OBS_ORDER_MOVE_BOTTOM:
  777. curRow = ui->sources->count();
  778. break;
  779. }
  780. ui->sources->insertItem(curRow, listItem);
  781. ui->sources->setCurrentRow(curRow);
  782. }
  783. void OBSBasic::ActivateAudioSource(OBSSource source)
  784. {
  785. VolControl *vol = new VolControl(source);
  786. volumes.push_back(vol);
  787. ui->volumeWidgets->layout()->addWidget(vol);
  788. }
  789. void OBSBasic::DeactivateAudioSource(OBSSource source)
  790. {
  791. for (size_t i = 0; i < volumes.size(); i++) {
  792. if (volumes[i]->GetSource() == source) {
  793. delete volumes[i];
  794. volumes.erase(volumes.begin() + i);
  795. break;
  796. }
  797. }
  798. }
  799. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  800. {
  801. const char *name = obs_source_get_name(source);
  802. QString text = QTStr("ConfirmRemove.Text");
  803. text.replace("$1", QT_UTF8(name));
  804. QMessageBox remove_source(this);
  805. remove_source.setText(text);
  806. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  807. QMessageBox::YesRole);
  808. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  809. remove_source.setIcon(QMessageBox::Question);
  810. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  811. remove_source.exec();
  812. return Yes == remove_source.clickedButton();
  813. }
  814. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  815. #ifdef UPDATE_SPARKLE
  816. void init_sparkle_updater(bool update_to_undeployed);
  817. void trigger_sparkle_update();
  818. #endif
  819. void OBSBasic::TimedCheckForUpdates()
  820. {
  821. #ifdef UPDATE_SPARKLE
  822. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  823. "UpdateToUndeployed"));
  824. #else
  825. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  826. "LastUpdateCheck");
  827. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  828. "LastVersion");
  829. if (lastVersion < LIBOBS_API_VER) {
  830. lastUpdate = 0;
  831. config_set_int(App()->GlobalConfig(), "General",
  832. "LastUpdateCheck", 0);
  833. }
  834. long long t = (long long)time(nullptr);
  835. long long secs = t - lastUpdate;
  836. if (secs > UPDATE_CHECK_INTERVAL)
  837. CheckForUpdates();
  838. #endif
  839. }
  840. void OBSBasic::CheckForUpdates()
  841. {
  842. #ifdef UPDATE_SPARKLE
  843. trigger_sparkle_update();
  844. #else
  845. ui->actionCheckForUpdates->setEnabled(false);
  846. string versionString("obs-basic ");
  847. versionString += App()->GetVersionString();
  848. QNetworkRequest request;
  849. request.setUrl(QUrl("https://obsproject.com/obs2_update/basic.json"));
  850. request.setRawHeader("User-Agent", versionString.c_str());
  851. QNetworkReply *reply = networkManager.get(request);
  852. connect(reply, SIGNAL(finished()),
  853. this, SLOT(updateFileFinished()));
  854. #endif
  855. }
  856. #ifdef __APPLE__
  857. #define VERSION_ENTRY "mac"
  858. #elif _WIN32
  859. #define VERSION_ENTRY "windows"
  860. #else
  861. #define VERSION_ENTRY "other"
  862. #endif
  863. void OBSBasic::updateFileFinished()
  864. {
  865. ui->actionCheckForUpdates->setEnabled(true);
  866. QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
  867. if (!reply || reply->error()) {
  868. blog(LOG_WARNING, "Update check failed: %s",
  869. QT_TO_UTF8(reply->errorString()));
  870. return;
  871. }
  872. QByteArray raw = reply->readAll();
  873. if (!raw.length())
  874. return;
  875. obs_data_t *returnData = obs_data_create_from_json(raw.constData());
  876. obs_data_t *versionData = obs_data_get_obj(returnData, VERSION_ENTRY);
  877. const char *description = obs_data_get_string(returnData,
  878. "description");
  879. const char *download = obs_data_get_string(versionData, "download");
  880. if (returnData && versionData && description && download) {
  881. long major = obs_data_get_int(versionData, "major");
  882. long minor = obs_data_get_int(versionData, "minor");
  883. long patch = obs_data_get_int(versionData, "patch");
  884. long version = MAKE_SEMANTIC_VERSION(major, minor, patch);
  885. blog(LOG_INFO, "Update check: latest version is: %ld.%ld.%ld",
  886. major, minor, patch);
  887. if (version > LIBOBS_API_VER) {
  888. QString str = QTStr("UpdateAvailable.Text");
  889. QMessageBox messageBox(this);
  890. str = str.arg(QString::number(major),
  891. QString::number(minor),
  892. QString::number(patch),
  893. download);
  894. messageBox.setWindowTitle(QTStr("UpdateAvailable"));
  895. messageBox.setTextFormat(Qt::RichText);
  896. messageBox.setText(str);
  897. messageBox.setInformativeText(QT_UTF8(description));
  898. messageBox.exec();
  899. long long t = (long long)time(nullptr);
  900. config_set_int(App()->GlobalConfig(), "General",
  901. "LastUpdateCheck", t);
  902. config_save(App()->GlobalConfig());
  903. }
  904. } else {
  905. blog(LOG_WARNING, "Bad JSON file received from server");
  906. }
  907. obs_data_release(versionData);
  908. obs_data_release(returnData);
  909. reply->deleteLater();
  910. }
  911. void OBSBasic::RemoveSelectedScene()
  912. {
  913. OBSScene scene = GetCurrentScene();
  914. if (scene) {
  915. obs_source_t *source = obs_scene_get_source(scene);
  916. if (QueryRemoveSource(source))
  917. obs_source_remove(source);
  918. }
  919. }
  920. void OBSBasic::RemoveSelectedSceneItem()
  921. {
  922. OBSSceneItem item = GetCurrentSceneItem();
  923. if (item) {
  924. obs_source_t *source = obs_sceneitem_get_source(item);
  925. if (QueryRemoveSource(source))
  926. obs_sceneitem_remove(item);
  927. }
  928. }
  929. struct ReorderInfo {
  930. int idx = 0;
  931. OBSBasic *window;
  932. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  933. };
  934. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  935. {
  936. int count = ui->sources->count();
  937. int idx_inv = count - (int)idx - 1;
  938. for (int i = 0; i < count; i++) {
  939. QListWidgetItem *listItem = ui->sources->item(i);
  940. QVariant v = listItem->data(Qt::UserRole);
  941. OBSSceneItem sceneItem = v.value<OBSSceneItem>();
  942. if (sceneItem == item) {
  943. if ((int)idx_inv != i) {
  944. bool sel = (ui->sources->currentRow() == i);
  945. listItem = ui->sources->takeItem(i);
  946. if (listItem) {
  947. ui->sources->insertItem(idx_inv,
  948. listItem);
  949. SetupVisibilityItem(ui->sources,
  950. listItem, item);
  951. if (sel)
  952. ui->sources->setCurrentRow(
  953. idx_inv);
  954. }
  955. }
  956. break;
  957. }
  958. }
  959. }
  960. void OBSBasic::ReorderSources(OBSScene scene)
  961. {
  962. ReorderInfo info(this);
  963. if (scene != GetCurrentScene())
  964. return;
  965. obs_scene_enum_items(scene,
  966. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  967. {
  968. ReorderInfo *info =
  969. reinterpret_cast<ReorderInfo*>(p);
  970. info->window->ReorderSceneItem(item,
  971. info->idx++);
  972. return true;
  973. }, &info);
  974. }
  975. /* OBS Callbacks */
  976. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  977. {
  978. OBSBasic *window = static_cast<OBSBasic*>(data);
  979. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  980. QMetaObject::invokeMethod(window, "ReorderSources",
  981. Q_ARG(OBSScene, OBSScene(scene)));
  982. }
  983. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  984. {
  985. OBSBasic *window = static_cast<OBSBasic*>(data);
  986. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  987. QMetaObject::invokeMethod(window, "AddSceneItem",
  988. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  989. }
  990. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  991. {
  992. OBSBasic *window = static_cast<OBSBasic*>(data);
  993. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  994. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  995. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  996. }
  997. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  998. {
  999. OBSBasic *window = static_cast<OBSBasic*>(data);
  1000. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  1001. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  1002. QMetaObject::invokeMethod(window, "SelectSceneItem",
  1003. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  1004. Q_ARG(bool, true));
  1005. }
  1006. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  1007. {
  1008. OBSBasic *window = static_cast<OBSBasic*>(data);
  1009. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  1010. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  1011. QMetaObject::invokeMethod(window, "SelectSceneItem",
  1012. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  1013. Q_ARG(bool, false));
  1014. }
  1015. void OBSBasic::SourceAdded(void *data, calldata_t *params)
  1016. {
  1017. OBSBasic *window = static_cast<OBSBasic*>(data);
  1018. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1019. if (obs_scene_from_source(source) != NULL)
  1020. QMetaObject::invokeMethod(window,
  1021. "AddScene",
  1022. Q_ARG(OBSSource, OBSSource(source)));
  1023. }
  1024. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  1025. {
  1026. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1027. if (obs_scene_from_source(source) != NULL)
  1028. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1029. "RemoveScene",
  1030. Q_ARG(OBSSource, OBSSource(source)));
  1031. }
  1032. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  1033. {
  1034. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1035. uint32_t flags = obs_source_get_output_flags(source);
  1036. if (flags & OBS_SOURCE_AUDIO)
  1037. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1038. "ActivateAudioSource",
  1039. Q_ARG(OBSSource, OBSSource(source)));
  1040. }
  1041. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  1042. {
  1043. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1044. uint32_t flags = obs_source_get_output_flags(source);
  1045. if (flags & OBS_SOURCE_AUDIO)
  1046. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1047. "DeactivateAudioSource",
  1048. Q_ARG(OBSSource, OBSSource(source)));
  1049. }
  1050. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  1051. {
  1052. const char *newName = calldata_string(params, "new_name");
  1053. const char *prevName = calldata_string(params, "prev_name");
  1054. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1055. "RenameSources",
  1056. Q_ARG(QString, QT_UTF8(newName)),
  1057. Q_ARG(QString, QT_UTF8(prevName)));
  1058. }
  1059. void OBSBasic::ChannelChanged(void *data, calldata_t *params)
  1060. {
  1061. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1062. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  1063. if (channel == 0)
  1064. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1065. "UpdateSceneSelection",
  1066. Q_ARG(OBSSource, OBSSource(source)));
  1067. }
  1068. void OBSBasic::DrawBackdrop(float cx, float cy)
  1069. {
  1070. if (!box)
  1071. return;
  1072. gs_effect_t *solid = obs_get_solid_effect();
  1073. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  1074. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  1075. vec4 colorVal;
  1076. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  1077. gs_effect_set_vec4(color, &colorVal);
  1078. gs_technique_begin(tech);
  1079. gs_technique_begin_pass(tech, 0);
  1080. gs_matrix_push();
  1081. gs_matrix_identity();
  1082. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  1083. gs_load_vertexbuffer(box);
  1084. gs_draw(GS_TRISTRIP, 0, 0);
  1085. gs_matrix_pop();
  1086. gs_technique_end_pass(tech);
  1087. gs_technique_end(tech);
  1088. gs_load_vertexbuffer(nullptr);
  1089. }
  1090. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  1091. {
  1092. OBSBasic *window = static_cast<OBSBasic*>(data);
  1093. obs_video_info ovi;
  1094. obs_get_video_info(&ovi);
  1095. window->previewCX = int(window->previewScale * float(ovi.base_width));
  1096. window->previewCY = int(window->previewScale * float(ovi.base_height));
  1097. gs_viewport_push();
  1098. gs_projection_push();
  1099. /* --------------------------------------- */
  1100. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  1101. -100.0f, 100.0f);
  1102. gs_set_viewport(window->previewX, window->previewY,
  1103. window->previewCX, window->previewCY);
  1104. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  1105. obs_render_main_view();
  1106. gs_load_vertexbuffer(nullptr);
  1107. /* --------------------------------------- */
  1108. QSize previewSize = GetPixelSize(window->ui->preview);
  1109. float right = float(previewSize.width()) - window->previewX;
  1110. float bottom = float(previewSize.height()) - window->previewY;
  1111. gs_ortho(-window->previewX, right,
  1112. -window->previewY, bottom,
  1113. -100.0f, 100.0f);
  1114. gs_reset_viewport();
  1115. window->ui->preview->DrawSceneEditing();
  1116. /* --------------------------------------- */
  1117. gs_projection_pop();
  1118. gs_viewport_pop();
  1119. UNUSED_PARAMETER(cx);
  1120. UNUSED_PARAMETER(cy);
  1121. }
  1122. /* Main class functions */
  1123. obs_service_t *OBSBasic::GetService()
  1124. {
  1125. if (!service)
  1126. service = obs_service_create("rtmp_common", NULL, NULL);
  1127. return service;
  1128. }
  1129. void OBSBasic::SetService(obs_service_t *newService)
  1130. {
  1131. if (newService) {
  1132. if (service)
  1133. obs_service_destroy(service);
  1134. service = newService;
  1135. }
  1136. }
  1137. bool OBSBasic::StreamingActive()
  1138. {
  1139. if (!outputHandler)
  1140. return false;
  1141. return outputHandler->StreamingActive();
  1142. }
  1143. #ifdef _WIN32
  1144. #define IS_WIN32 1
  1145. #else
  1146. #define IS_WIN32 0
  1147. #endif
  1148. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  1149. {
  1150. int ret = obs_reset_video(ovi);
  1151. if (ret == OBS_VIDEO_INVALID_PARAM) {
  1152. struct obs_video_info new_params = *ovi;
  1153. if (new_params.window_width == 0)
  1154. new_params.window_width = 512;
  1155. if (new_params.window_height == 0)
  1156. new_params.window_height = 512;
  1157. new_params.output_width = new_params.window_width;
  1158. new_params.output_height = new_params.window_height;
  1159. new_params.base_width = new_params.window_width;
  1160. new_params.base_height = new_params.window_height;
  1161. ret = obs_reset_video(&new_params);
  1162. }
  1163. return ret;
  1164. }
  1165. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  1166. {
  1167. const char *scaleTypeStr = config_get_string(basicConfig,
  1168. "Video", "ScaleType");
  1169. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  1170. return OBS_SCALE_BILINEAR;
  1171. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  1172. return OBS_SCALE_LANCZOS;
  1173. else
  1174. return OBS_SCALE_BICUBIC;
  1175. }
  1176. static inline enum video_format GetVideoFormatFromName(const char *name)
  1177. {
  1178. if (astrcmpi(name, "I420") == 0)
  1179. return VIDEO_FORMAT_I420;
  1180. else if (astrcmpi(name, "NV12") == 0)
  1181. return VIDEO_FORMAT_NV12;
  1182. #if 0 //currently unsupported
  1183. else if (astrcmpi(name, "YVYU") == 0)
  1184. return VIDEO_FORMAT_YVYU;
  1185. else if (astrcmpi(name, "YUY2") == 0)
  1186. return VIDEO_FORMAT_YUY2;
  1187. else if (astrcmpi(name, "UYVY") == 0)
  1188. return VIDEO_FORMAT_UYVY;
  1189. #endif
  1190. else
  1191. return VIDEO_FORMAT_BGRA;
  1192. }
  1193. int OBSBasic::ResetVideo()
  1194. {
  1195. struct obs_video_info ovi;
  1196. int ret;
  1197. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  1198. const char *colorFormat = config_get_string(basicConfig, "Video",
  1199. "ColorFormat");
  1200. const char *colorSpace = config_get_string(basicConfig, "Video",
  1201. "ColorSpace");
  1202. const char *colorRange = config_get_string(basicConfig, "Video",
  1203. "ColorRange");
  1204. ovi.graphics_module = App()->GetRenderModule();
  1205. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  1206. "Video", "BaseCX");
  1207. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  1208. "Video", "BaseCY");
  1209. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  1210. "Video", "OutputCX");
  1211. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  1212. "Video", "OutputCY");
  1213. ovi.output_format = GetVideoFormatFromName(colorFormat);
  1214. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  1215. VIDEO_CS_601 : VIDEO_CS_709;
  1216. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  1217. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  1218. ovi.adapter = 0;
  1219. ovi.gpu_conversion = true;
  1220. ovi.scale_type = GetScaleType(basicConfig);
  1221. QTToGSWindow(ui->preview->winId(), ovi.window);
  1222. //required to make opengl display stuff on osx(?)
  1223. ResizePreview(ovi.base_width, ovi.base_height);
  1224. QSize size = GetPixelSize(ui->preview);
  1225. ovi.window_width = size.width();
  1226. ovi.window_height = size.height();
  1227. ret = AttemptToResetVideo(&ovi);
  1228. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  1229. /* Try OpenGL if DirectX fails on windows */
  1230. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  1231. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  1232. "with graphics_module='%s', retrying "
  1233. "with graphics_module='%s'",
  1234. ret, ovi.graphics_module,
  1235. DL_OPENGL);
  1236. ovi.graphics_module = DL_OPENGL;
  1237. ret = AttemptToResetVideo(&ovi);
  1238. }
  1239. }
  1240. if (ret == OBS_VIDEO_SUCCESS)
  1241. obs_add_draw_callback(OBSBasic::RenderMain, this);
  1242. return ret;
  1243. }
  1244. bool OBSBasic::ResetAudio()
  1245. {
  1246. struct obs_audio_info ai;
  1247. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  1248. "SampleRate");
  1249. const char *channelSetupStr = config_get_string(basicConfig,
  1250. "Audio", "ChannelSetup");
  1251. if (strcmp(channelSetupStr, "Mono") == 0)
  1252. ai.speakers = SPEAKERS_MONO;
  1253. else
  1254. ai.speakers = SPEAKERS_STEREO;
  1255. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  1256. return obs_reset_audio(&ai);
  1257. }
  1258. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  1259. const char *deviceDesc, int channel)
  1260. {
  1261. const char *deviceId = config_get_string(basicConfig, "Audio",
  1262. deviceName);
  1263. obs_source_t *source;
  1264. obs_data_t *settings;
  1265. bool same = false;
  1266. source = obs_get_output_source(channel);
  1267. if (source) {
  1268. settings = obs_source_get_settings(source);
  1269. const char *curId = obs_data_get_string(settings, "device_id");
  1270. same = (strcmp(curId, deviceId) == 0);
  1271. obs_data_release(settings);
  1272. obs_source_release(source);
  1273. }
  1274. if (!same)
  1275. obs_set_output_source(channel, nullptr);
  1276. if (!same && strcmp(deviceId, "disabled") != 0) {
  1277. obs_data_t *settings = obs_data_create();
  1278. obs_data_set_string(settings, "device_id", deviceId);
  1279. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  1280. sourceId, deviceDesc, settings);
  1281. obs_data_release(settings);
  1282. obs_set_output_source(channel, source);
  1283. obs_source_release(source);
  1284. }
  1285. }
  1286. void OBSBasic::ResetAudioDevices()
  1287. {
  1288. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  1289. Str("Basic.DesktopDevice1"), 1);
  1290. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  1291. Str("Basic.DesktopDevice2"), 2);
  1292. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  1293. Str("Basic.AuxDevice1"), 3);
  1294. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  1295. Str("Basic.AuxDevice2"), 4);
  1296. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  1297. Str("Basic.AuxDevice3"), 5);
  1298. }
  1299. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  1300. {
  1301. QSize targetSize;
  1302. /* resize preview panel to fix to the top section of the window */
  1303. targetSize = GetPixelSize(ui->preview);
  1304. GetScaleAndCenterPos(int(cx), int(cy),
  1305. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  1306. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  1307. previewX, previewY, previewScale);
  1308. previewX += float(PREVIEW_EDGE_SIZE);
  1309. previewY += float(PREVIEW_EDGE_SIZE);
  1310. if (isVisible()) {
  1311. if (resizeTimer)
  1312. killTimer(resizeTimer);
  1313. resizeTimer = startTimer(100);
  1314. }
  1315. }
  1316. void OBSBasic::closeEvent(QCloseEvent *event)
  1317. {
  1318. if (outputHandler && outputHandler->Active()) {
  1319. QMessageBox::StandardButton button = QMessageBox::question(
  1320. this, QTStr("ConfirmExit.Title"),
  1321. QTStr("ConfirmExit.Text"));
  1322. if (button == QMessageBox::No) {
  1323. event->ignore();
  1324. return;
  1325. }
  1326. }
  1327. QWidget::closeEvent(event);
  1328. if (!event->isAccepted())
  1329. return;
  1330. /* Check all child dialogs and ensure they run their proper closeEvent
  1331. * methods before exiting the application. Otherwise Qt doesn't send
  1332. * the proper QCloseEvent messages. */
  1333. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  1334. if (!childDialogs.isEmpty()) {
  1335. for (int i = 0; i < childDialogs.size(); ++i) {
  1336. childDialogs.at(i)->close();
  1337. }
  1338. }
  1339. // remove draw callback in case our drawable surfaces go away before
  1340. // the destructor gets called
  1341. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  1342. /* Delete the save timer so it doesn't trigger after this point while
  1343. * the program data is being freed */
  1344. delete saveTimer;
  1345. SaveProject();
  1346. /* Clear the list boxes in ::closeEvent to ensure that we can process
  1347. * any ->deleteLater events in this window created by Qt in relation to
  1348. * their internal data */
  1349. ClearVolumeControls();
  1350. ui->sources->clear();
  1351. ui->scenes->clear();
  1352. }
  1353. void OBSBasic::changeEvent(QEvent *event)
  1354. {
  1355. /* TODO */
  1356. UNUSED_PARAMETER(event);
  1357. }
  1358. void OBSBasic::resizeEvent(QResizeEvent *event)
  1359. {
  1360. struct obs_video_info ovi;
  1361. if (obs_get_video_info(&ovi))
  1362. ResizePreview(ovi.base_width, ovi.base_height);
  1363. UNUSED_PARAMETER(event);
  1364. }
  1365. void OBSBasic::timerEvent(QTimerEvent *event)
  1366. {
  1367. if (event->timerId() == resizeTimer) {
  1368. killTimer(resizeTimer);
  1369. resizeTimer = 0;
  1370. QSize size = GetPixelSize(ui->preview);
  1371. obs_resize(size.width(), size.height());
  1372. }
  1373. }
  1374. void OBSBasic::on_action_New_triggered()
  1375. {
  1376. /* TODO */
  1377. }
  1378. void OBSBasic::on_action_Open_triggered()
  1379. {
  1380. /* TODO */
  1381. }
  1382. void OBSBasic::on_action_Save_triggered()
  1383. {
  1384. /* TODO */
  1385. }
  1386. void OBSBasic::on_actionShow_Recordings_triggered()
  1387. {
  1388. const char *path = config_get_string(basicConfig,
  1389. "SimpleOutput", "FilePath");
  1390. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  1391. }
  1392. void OBSBasic::on_actionRemux_triggered()
  1393. {
  1394. const char *path = config_get_string(basicConfig,
  1395. "SimpleOutput", "FilePath");
  1396. OBSRemux remux(path, this);
  1397. remux.exec();
  1398. }
  1399. void OBSBasic::on_action_Settings_triggered()
  1400. {
  1401. OBSBasicSettings settings(this);
  1402. settings.exec();
  1403. }
  1404. void OBSBasic::on_actionAdvAudioProperties_triggered()
  1405. {
  1406. if (advAudioWindow != nullptr) {
  1407. advAudioWindow->raise();
  1408. return;
  1409. }
  1410. advAudioWindow = new OBSBasicAdvAudio(this);
  1411. advAudioWindow->show();
  1412. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1413. connect(advAudioWindow, SIGNAL(destroyed()),
  1414. this, SLOT(on_advAudioProps_destroyed()));
  1415. }
  1416. void OBSBasic::on_advAudioProps_clicked()
  1417. {
  1418. on_actionAdvAudioProperties_triggered();
  1419. }
  1420. void OBSBasic::on_advAudioProps_destroyed()
  1421. {
  1422. advAudioWindow = nullptr;
  1423. }
  1424. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  1425. QListWidgetItem *prev)
  1426. {
  1427. obs_source_t *source = NULL;
  1428. if (sceneChanging)
  1429. return;
  1430. if (current) {
  1431. obs_scene_t *scene;
  1432. scene = current->data(Qt::UserRole).value<OBSScene>();
  1433. source = obs_scene_get_source(scene);
  1434. }
  1435. /* TODO: allow transitions */
  1436. obs_set_output_source(0, source);
  1437. UNUSED_PARAMETER(prev);
  1438. }
  1439. void OBSBasic::EditSceneName()
  1440. {
  1441. QListWidgetItem *item = ui->scenes->currentItem();
  1442. Qt::ItemFlags flags = item->flags();
  1443. item->setFlags(flags | Qt::ItemIsEditable);
  1444. ui->scenes->editItem(item);
  1445. item->setFlags(flags);
  1446. }
  1447. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  1448. {
  1449. QListWidgetItem *item = ui->scenes->itemAt(pos);
  1450. QMenu popup(this);
  1451. popup.addAction(QTStr("Add"),
  1452. this, SLOT(on_actionAddScene_triggered()));
  1453. if (item) {
  1454. popup.addSeparator();
  1455. popup.addAction(QTStr("Rename"),
  1456. this, SLOT(EditSceneName()));
  1457. popup.addAction(QTStr("Remove"),
  1458. this, SLOT(RemoveSelectedScene()),
  1459. DeleteKeys.front());
  1460. popup.addSeparator();
  1461. popup.addAction(QTStr("Filters"), this,
  1462. SLOT(OpenSceneFilters()));
  1463. }
  1464. popup.exec(QCursor::pos());
  1465. }
  1466. void OBSBasic::on_actionAddScene_triggered()
  1467. {
  1468. string name;
  1469. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1470. int i = 1;
  1471. QString placeHolderText = format.arg(i);
  1472. obs_source_t *source = nullptr;
  1473. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1474. obs_source_release(source);
  1475. placeHolderText = format.arg(++i);
  1476. }
  1477. bool accepted = NameDialog::AskForName(this,
  1478. QTStr("Basic.Main.AddSceneDlg.Title"),
  1479. QTStr("Basic.Main.AddSceneDlg.Text"),
  1480. name,
  1481. placeHolderText);
  1482. if (accepted) {
  1483. if (name.empty()) {
  1484. QMessageBox::information(this,
  1485. QTStr("NoNameEntered.Title"),
  1486. QTStr("NoNameEntered.Text"));
  1487. on_actionAddScene_triggered();
  1488. return;
  1489. }
  1490. obs_source_t *source = obs_get_source_by_name(name.c_str());
  1491. if (source) {
  1492. QMessageBox::information(this,
  1493. QTStr("NameExists.Title"),
  1494. QTStr("NameExists.Text"));
  1495. obs_source_release(source);
  1496. on_actionAddScene_triggered();
  1497. return;
  1498. }
  1499. obs_scene_t *scene = obs_scene_create(name.c_str());
  1500. source = obs_scene_get_source(scene);
  1501. obs_add_source(source);
  1502. obs_scene_release(scene);
  1503. obs_set_output_source(0, source);
  1504. }
  1505. }
  1506. void OBSBasic::on_actionRemoveScene_triggered()
  1507. {
  1508. OBSScene scene = GetCurrentScene();
  1509. obs_source_t *source = obs_scene_get_source(scene);
  1510. if (source && QueryRemoveSource(source))
  1511. obs_source_remove(source);
  1512. }
  1513. void OBSBasic::on_actionSceneProperties_triggered()
  1514. {
  1515. /* TODO */
  1516. }
  1517. void OBSBasic::on_actionSceneUp_triggered()
  1518. {
  1519. /* TODO */
  1520. }
  1521. void OBSBasic::on_actionSceneDown_triggered()
  1522. {
  1523. /* TODO */
  1524. }
  1525. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1526. QListWidgetItem *prev)
  1527. {
  1528. auto select_one = [] (obs_scene_t *scene, obs_sceneitem_t *item,
  1529. void *param)
  1530. {
  1531. obs_sceneitem_t *selectedItem =
  1532. *reinterpret_cast<OBSSceneItem*>(param);
  1533. obs_sceneitem_select(item, (selectedItem == item));
  1534. UNUSED_PARAMETER(scene);
  1535. return true;
  1536. };
  1537. if (!current)
  1538. return;
  1539. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1540. obs_source_t *source = obs_sceneitem_get_source(item);
  1541. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1542. return;
  1543. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1544. UNUSED_PARAMETER(prev);
  1545. }
  1546. void OBSBasic::EditSceneItemName()
  1547. {
  1548. QListWidgetItem *item = ui->sources->currentItem();
  1549. Qt::ItemFlags flags = item->flags();
  1550. OBSSceneItem sceneItem= item->data(Qt::UserRole).value<OBSSceneItem>();
  1551. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  1552. const char *name = obs_source_get_name(source);
  1553. item->setText(QT_UTF8(name));
  1554. item->setFlags(flags | Qt::ItemIsEditable);
  1555. ui->sources->removeItemWidget(item);
  1556. ui->sources->editItem(item);
  1557. item->setFlags(flags);
  1558. }
  1559. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1560. {
  1561. QListWidgetItem *item = ui->sources->itemAt(pos);
  1562. QMenu popup(this);
  1563. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1564. if (addSourceMenu)
  1565. popup.addMenu(addSourceMenu);
  1566. if (item) {
  1567. if (addSourceMenu)
  1568. popup.addSeparator();
  1569. OBSSceneItem sceneItem = GetSceneItem(item);
  1570. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  1571. QAction *action;
  1572. popup.addAction(QTStr("Rename"), this,
  1573. SLOT(EditSceneItemName()));
  1574. popup.addAction(QTStr("Remove"), this,
  1575. SLOT(on_actionRemoveSource_triggered()),
  1576. DeleteKeys.front());
  1577. popup.addSeparator();
  1578. popup.addMenu(ui->orderMenu);
  1579. popup.addMenu(ui->transformMenu);
  1580. popup.addSeparator();
  1581. action = popup.addAction(QTStr("Interact"), this,
  1582. SLOT(on_actionInteract_triggered()));
  1583. action->setEnabled(obs_source_get_output_flags(source) &
  1584. OBS_SOURCE_INTERACTION);
  1585. popup.addAction(QTStr("Filters"), this,
  1586. SLOT(OpenFilters()));
  1587. popup.addAction(QTStr("Properties"), this,
  1588. SLOT(on_actionSourceProperties_triggered()));
  1589. }
  1590. popup.exec(QCursor::pos());
  1591. }
  1592. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  1593. {
  1594. if (!witem)
  1595. return;
  1596. OBSSceneItem item = GetSceneItem(witem);
  1597. OBSSource source = obs_sceneitem_get_source(item);
  1598. if (source)
  1599. CreatePropertiesWindow(source);
  1600. }
  1601. void OBSBasic::AddSource(const char *id)
  1602. {
  1603. if (id && *id) {
  1604. OBSBasicSourceSelect sourceSelect(this, id);
  1605. sourceSelect.exec();
  1606. }
  1607. }
  1608. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1609. {
  1610. const char *type;
  1611. bool foundValues = false;
  1612. size_t idx = 0;
  1613. QMenu *popup = new QMenu(QTStr("Add"), this);
  1614. while (obs_enum_input_types(idx++, &type)) {
  1615. const char *name = obs_source_get_display_name(
  1616. OBS_SOURCE_TYPE_INPUT, type);
  1617. if (strcmp(type, "scene") == 0)
  1618. continue;
  1619. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1620. popupItem->setData(QT_UTF8(type));
  1621. connect(popupItem, SIGNAL(triggered(bool)),
  1622. this, SLOT(AddSourceFromAction()));
  1623. popup->addAction(popupItem);
  1624. foundValues = true;
  1625. }
  1626. if (!foundValues) {
  1627. delete popup;
  1628. popup = nullptr;
  1629. }
  1630. return popup;
  1631. }
  1632. void OBSBasic::AddSourceFromAction()
  1633. {
  1634. QAction *action = qobject_cast<QAction*>(sender());
  1635. if (!action)
  1636. return;
  1637. AddSource(QT_TO_UTF8(action->data().toString()));
  1638. }
  1639. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1640. {
  1641. if (!GetCurrentScene()) {
  1642. // Tell the user he needs a scene first (help beginners).
  1643. QMessageBox::information(this,
  1644. QTStr("Basic.Main.AddSourceHelp.Title"),
  1645. QTStr("Basic.Main.AddSourceHelp.Text"));
  1646. return;
  1647. }
  1648. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1649. if (popup)
  1650. popup->exec(pos);
  1651. }
  1652. void OBSBasic::on_actionAddSource_triggered()
  1653. {
  1654. AddSourcePopupMenu(QCursor::pos());
  1655. }
  1656. void OBSBasic::on_actionRemoveSource_triggered()
  1657. {
  1658. OBSSceneItem item = GetCurrentSceneItem();
  1659. obs_source_t *source = obs_sceneitem_get_source(item);
  1660. if (source && QueryRemoveSource(source))
  1661. obs_sceneitem_remove(item);
  1662. }
  1663. void OBSBasic::on_actionInteract_triggered()
  1664. {
  1665. OBSSceneItem item = GetCurrentSceneItem();
  1666. OBSSource source = obs_sceneitem_get_source(item);
  1667. if (source)
  1668. CreateInteractionWindow(source);
  1669. }
  1670. void OBSBasic::on_actionSourceProperties_triggered()
  1671. {
  1672. OBSSceneItem item = GetCurrentSceneItem();
  1673. OBSSource source = obs_sceneitem_get_source(item);
  1674. if (source)
  1675. CreatePropertiesWindow(source);
  1676. }
  1677. void OBSBasic::on_actionSourceUp_triggered()
  1678. {
  1679. OBSSceneItem item = GetCurrentSceneItem();
  1680. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1681. }
  1682. void OBSBasic::on_actionSourceDown_triggered()
  1683. {
  1684. OBSSceneItem item = GetCurrentSceneItem();
  1685. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1686. }
  1687. void OBSBasic::on_actionMoveUp_triggered()
  1688. {
  1689. OBSSceneItem item = GetCurrentSceneItem();
  1690. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1691. }
  1692. void OBSBasic::on_actionMoveDown_triggered()
  1693. {
  1694. OBSSceneItem item = GetCurrentSceneItem();
  1695. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1696. }
  1697. void OBSBasic::on_actionMoveToTop_triggered()
  1698. {
  1699. OBSSceneItem item = GetCurrentSceneItem();
  1700. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  1701. }
  1702. void OBSBasic::on_actionMoveToBottom_triggered()
  1703. {
  1704. OBSSceneItem item = GetCurrentSceneItem();
  1705. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  1706. }
  1707. static BPtr<char> ReadLogFile(const char *log)
  1708. {
  1709. char logDir[512];
  1710. if (os_get_config_path(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  1711. return nullptr;
  1712. string path = (char*)logDir;
  1713. path += "/";
  1714. path += log;
  1715. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  1716. if (!file)
  1717. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1718. return file;
  1719. }
  1720. void OBSBasic::UploadLog(const char *file)
  1721. {
  1722. BPtr<char> fileString{ReadLogFile(file)};
  1723. if (!fileString)
  1724. return;
  1725. if (!*fileString)
  1726. return;
  1727. ui->menuLogFiles->setEnabled(false);
  1728. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  1729. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  1730. data_t content{obs_data_create(), data_deleter};
  1731. data_t files{obs_data_create(), data_deleter};
  1732. data_t request{obs_data_create(), data_deleter};
  1733. obs_data_set_string(content.get(), "content", fileString);
  1734. obs_data_set_obj(files.get(), file, content.get());
  1735. stringstream ss;
  1736. ss << "OBS " << App()->GetVersionString()
  1737. << " log file uploaded at " << CurrentDateTimeString();
  1738. obs_data_set_string(request.get(), "description", ss.str().c_str());
  1739. obs_data_set_bool(request.get(), "public", false);
  1740. obs_data_set_obj(request.get(), "files", files.get());
  1741. const char *json = obs_data_get_json(request.get());
  1742. if (!json) {
  1743. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  1744. return;
  1745. }
  1746. QBuffer *postData = new QBuffer();
  1747. postData->setData(json, (int) strlen(json));
  1748. QNetworkRequest postReq(QUrl("https://api.github.com/gists"));
  1749. postReq.setHeader(QNetworkRequest::ContentTypeHeader,
  1750. "application/json");
  1751. QNetworkReply *reply = networkManager.post(postReq, postData);
  1752. /* set the reply as parent, so the buffer is deleted with the reply */
  1753. postData->setParent(reply);
  1754. connect(reply, SIGNAL(finished()),
  1755. this, SLOT(logUploadFinished()));
  1756. }
  1757. void OBSBasic::on_actionShowLogs_triggered()
  1758. {
  1759. char logDir[512];
  1760. if (os_get_config_path(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  1761. return;
  1762. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  1763. QDesktopServices::openUrl(url);
  1764. }
  1765. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1766. {
  1767. UploadLog(App()->GetCurrentLog());
  1768. }
  1769. void OBSBasic::on_actionUploadLastLog_triggered()
  1770. {
  1771. UploadLog(App()->GetLastLog());
  1772. }
  1773. void OBSBasic::on_actionViewCurrentLog_triggered()
  1774. {
  1775. char logDir[512];
  1776. if (os_get_config_path(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  1777. return;
  1778. const char* log = App()->GetCurrentLog();
  1779. string path = (char*)logDir;
  1780. path += "/";
  1781. path += log;
  1782. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  1783. QDesktopServices::openUrl(url);
  1784. }
  1785. void OBSBasic::on_actionCheckForUpdates_triggered()
  1786. {
  1787. CheckForUpdates();
  1788. }
  1789. void OBSBasic::logUploadFinished()
  1790. {
  1791. ui->menuLogFiles->setEnabled(true);
  1792. QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
  1793. if (!reply || reply->error()) {
  1794. QMessageBox::information(this,
  1795. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1796. reply->errorString());
  1797. return;
  1798. }
  1799. QByteArray raw = reply->readAll();
  1800. if (!raw.length())
  1801. return;
  1802. obs_data_t *returnData = obs_data_create_from_json(raw.constData());
  1803. QString logURL = obs_data_get_string(returnData, "html_url");
  1804. obs_data_release(returnData);
  1805. OBSLogReply logDialog(this, logURL);
  1806. logDialog.exec();
  1807. reply->deleteLater();
  1808. }
  1809. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  1810. obs_source_t *source, const string &name)
  1811. {
  1812. const char *prevName = obs_source_get_name(source);
  1813. if (name == prevName)
  1814. return;
  1815. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  1816. QListWidgetItem *listItem = listWidget->currentItem();
  1817. if (foundSource || name.empty()) {
  1818. listItem->setText(QT_UTF8(prevName));
  1819. if (foundSource) {
  1820. QMessageBox::information(parent,
  1821. QTStr("NameExists.Title"),
  1822. QTStr("NameExists.Text"));
  1823. } else if (name.empty()) {
  1824. QMessageBox::information(parent,
  1825. QTStr("NoNameEntered.Title"),
  1826. QTStr("NoNameEntered.Text"));
  1827. }
  1828. obs_source_release(foundSource);
  1829. } else {
  1830. listItem->setText(QT_UTF8(name.c_str()));
  1831. obs_source_set_name(source, name.c_str());
  1832. }
  1833. }
  1834. void OBSBasic::SceneNameEdited(QWidget *editor,
  1835. QAbstractItemDelegate::EndEditHint endHint)
  1836. {
  1837. OBSScene scene = GetCurrentScene();
  1838. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1839. string text = QT_TO_UTF8(edit->text().trimmed());
  1840. if (!scene)
  1841. return;
  1842. obs_source_t *source = obs_scene_get_source(scene);
  1843. RenameListItem(this, ui->scenes, source, text);
  1844. UNUSED_PARAMETER(endHint);
  1845. }
  1846. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1847. QAbstractItemDelegate::EndEditHint endHint)
  1848. {
  1849. OBSSceneItem item = GetCurrentSceneItem();
  1850. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1851. string text = QT_TO_UTF8(edit->text().trimmed());
  1852. if (!item)
  1853. return;
  1854. obs_source_t *source = obs_sceneitem_get_source(item);
  1855. RenameListItem(this, ui->sources, source, text);
  1856. QListWidgetItem *listItem = ui->sources->currentItem();
  1857. listItem->setText(QString());
  1858. SetupVisibilityItem(ui->sources, listItem, item);
  1859. UNUSED_PARAMETER(endHint);
  1860. }
  1861. void OBSBasic::OpenFilters()
  1862. {
  1863. OBSSceneItem item = GetCurrentSceneItem();
  1864. OBSSource source = obs_sceneitem_get_source(item);
  1865. CreateFiltersWindow(source);
  1866. }
  1867. void OBSBasic::OpenSceneFilters()
  1868. {
  1869. OBSScene scene = GetCurrentScene();
  1870. OBSSource source = obs_scene_get_source(scene);
  1871. CreateFiltersWindow(source);
  1872. }
  1873. void OBSBasic::StreamingStart()
  1874. {
  1875. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  1876. ui->streamButton->setEnabled(true);
  1877. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  1878. }
  1879. void OBSBasic::StreamingStop(int code)
  1880. {
  1881. const char *errorMessage;
  1882. switch (code) {
  1883. case OBS_OUTPUT_BAD_PATH:
  1884. errorMessage = Str("Output.ConnectFail.BadPath");
  1885. break;
  1886. case OBS_OUTPUT_CONNECT_FAILED:
  1887. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1888. break;
  1889. case OBS_OUTPUT_INVALID_STREAM:
  1890. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1891. break;
  1892. default:
  1893. case OBS_OUTPUT_ERROR:
  1894. errorMessage = Str("Output.ConnectFail.Error");
  1895. break;
  1896. case OBS_OUTPUT_DISCONNECTED:
  1897. /* doesn't happen if output is set to reconnect. note that
  1898. * reconnects are handled in the output, not in the UI */
  1899. errorMessage = Str("Output.ConnectFail.Disconnected");
  1900. }
  1901. ui->statusbar->StreamStopped();
  1902. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1903. ui->streamButton->setEnabled(true);
  1904. if (code != OBS_OUTPUT_SUCCESS)
  1905. QMessageBox::information(this,
  1906. QTStr("Output.ConnectFail.Title"),
  1907. QT_UTF8(errorMessage));
  1908. }
  1909. void OBSBasic::RecordingStart()
  1910. {
  1911. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  1912. }
  1913. void OBSBasic::RecordingStop()
  1914. {
  1915. ui->statusbar->RecordingStopped();
  1916. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1917. }
  1918. void OBSBasic::on_streamButton_clicked()
  1919. {
  1920. SaveProject();
  1921. if (outputHandler->StreamingActive()) {
  1922. outputHandler->StopStreaming();
  1923. } else {
  1924. if (outputHandler->StartStreaming(service)) {
  1925. ui->streamButton->setEnabled(false);
  1926. ui->streamButton->setText(
  1927. QTStr("Basic.Main.Connecting"));
  1928. }
  1929. }
  1930. }
  1931. void OBSBasic::on_recordButton_clicked()
  1932. {
  1933. SaveProject();
  1934. if (outputHandler->RecordingActive()) {
  1935. outputHandler->StopRecording();
  1936. } else {
  1937. if (outputHandler->StartRecording()) {
  1938. ui->recordButton->setText(
  1939. QTStr("Basic.Main.StopRecording"));
  1940. }
  1941. }
  1942. }
  1943. void OBSBasic::on_settingsButton_clicked()
  1944. {
  1945. OBSBasicSettings settings(this);
  1946. settings.exec();
  1947. }
  1948. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1949. {
  1950. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1951. if (strcmp(val, "10") == 0) {
  1952. num = 10;
  1953. den = 1;
  1954. } else if (strcmp(val, "20") == 0) {
  1955. num = 20;
  1956. den = 1;
  1957. } else if (strcmp(val, "25") == 0) {
  1958. num = 25;
  1959. den = 1;
  1960. } else if (strcmp(val, "29.97") == 0) {
  1961. num = 30000;
  1962. den = 1001;
  1963. } else if (strcmp(val, "48") == 0) {
  1964. num = 48;
  1965. den = 1;
  1966. } else if (strcmp(val, "59.94") == 0) {
  1967. num = 60000;
  1968. den = 1001;
  1969. } else if (strcmp(val, "60") == 0) {
  1970. num = 60;
  1971. den = 1;
  1972. } else {
  1973. num = 30;
  1974. den = 1;
  1975. }
  1976. }
  1977. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1978. {
  1979. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1980. den = 1;
  1981. }
  1982. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1983. {
  1984. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1985. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1986. }
  1987. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1988. {
  1989. num = 1000000000;
  1990. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1991. }
  1992. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1993. {
  1994. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1995. if (type == 1) //"Integer"
  1996. GetFPSInteger(num, den);
  1997. else if (type == 2) //"Fraction"
  1998. GetFPSFraction(num, den);
  1999. else if (false) //"Nanoseconds", currently not implemented
  2000. GetFPSNanoseconds(num, den);
  2001. else
  2002. GetFPSCommon(num, den);
  2003. }
  2004. config_t *OBSBasic::Config() const
  2005. {
  2006. return basicConfig;
  2007. }
  2008. void OBSBasic::on_actionEditTransform_triggered()
  2009. {
  2010. if (transformWindow)
  2011. transformWindow->close();
  2012. transformWindow = new OBSBasicTransform(this);
  2013. transformWindow->show();
  2014. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2015. }
  2016. void OBSBasic::on_actionResetTransform_triggered()
  2017. {
  2018. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2019. {
  2020. if (!obs_sceneitem_selected(item))
  2021. return true;
  2022. obs_transform_info info;
  2023. vec2_set(&info.pos, 0.0f, 0.0f);
  2024. vec2_set(&info.scale, 1.0f, 1.0f);
  2025. info.rot = 0.0f;
  2026. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  2027. info.bounds_type = OBS_BOUNDS_NONE;
  2028. info.bounds_alignment = OBS_ALIGN_CENTER;
  2029. vec2_set(&info.bounds, 0.0f, 0.0f);
  2030. obs_sceneitem_set_info(item, &info);
  2031. UNUSED_PARAMETER(scene);
  2032. UNUSED_PARAMETER(param);
  2033. return true;
  2034. };
  2035. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  2036. }
  2037. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  2038. {
  2039. matrix4 boxTransform;
  2040. obs_sceneitem_get_box_transform(item, &boxTransform);
  2041. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  2042. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  2043. auto GetMinPos = [&] (float x, float y)
  2044. {
  2045. vec3 pos;
  2046. vec3_set(&pos, x, y, 0.0f);
  2047. vec3_transform(&pos, &pos, &boxTransform);
  2048. vec3_min(&tl, &tl, &pos);
  2049. vec3_max(&br, &br, &pos);
  2050. };
  2051. GetMinPos(0.0f, 0.0f);
  2052. GetMinPos(1.0f, 0.0f);
  2053. GetMinPos(0.0f, 1.0f);
  2054. GetMinPos(1.0f, 1.0f);
  2055. }
  2056. static vec3 GetItemTL(obs_sceneitem_t *item)
  2057. {
  2058. vec3 tl, br;
  2059. GetItemBox(item, tl, br);
  2060. return tl;
  2061. }
  2062. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  2063. {
  2064. vec3 newTL;
  2065. vec2 pos;
  2066. obs_sceneitem_get_pos(item, &pos);
  2067. newTL = GetItemTL(item);
  2068. pos.x += tl.x - newTL.x;
  2069. pos.y += tl.y - newTL.y;
  2070. obs_sceneitem_set_pos(item, &pos);
  2071. }
  2072. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  2073. void *param)
  2074. {
  2075. if (!obs_sceneitem_selected(item))
  2076. return true;
  2077. float rot = *reinterpret_cast<float*>(param);
  2078. vec3 tl = GetItemTL(item);
  2079. rot += obs_sceneitem_get_rot(item);
  2080. if (rot >= 360.0f) rot -= 360.0f;
  2081. else if (rot <= -360.0f) rot += 360.0f;
  2082. obs_sceneitem_set_rot(item, rot);
  2083. SetItemTL(item, tl);
  2084. UNUSED_PARAMETER(scene);
  2085. UNUSED_PARAMETER(param);
  2086. return true;
  2087. };
  2088. void OBSBasic::on_actionRotate90CW_triggered()
  2089. {
  2090. float f90CW = 90.0f;
  2091. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  2092. }
  2093. void OBSBasic::on_actionRotate90CCW_triggered()
  2094. {
  2095. float f90CCW = -90.0f;
  2096. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  2097. }
  2098. void OBSBasic::on_actionRotate180_triggered()
  2099. {
  2100. float f180 = 180.0f;
  2101. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  2102. }
  2103. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  2104. void *param)
  2105. {
  2106. vec2 &mul = *reinterpret_cast<vec2*>(param);
  2107. if (!obs_sceneitem_selected(item))
  2108. return true;
  2109. vec3 tl = GetItemTL(item);
  2110. vec2 scale;
  2111. obs_sceneitem_get_scale(item, &scale);
  2112. vec2_mul(&scale, &scale, &mul);
  2113. obs_sceneitem_set_scale(item, &scale);
  2114. SetItemTL(item, tl);
  2115. UNUSED_PARAMETER(scene);
  2116. return true;
  2117. }
  2118. void OBSBasic::on_actionFlipHorizontal_triggered()
  2119. {
  2120. vec2 scale;
  2121. vec2_set(&scale, -1.0f, 1.0f);
  2122. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  2123. &scale);
  2124. }
  2125. void OBSBasic::on_actionFlipVertical_triggered()
  2126. {
  2127. vec2 scale;
  2128. vec2_set(&scale, 1.0f, -1.0f);
  2129. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  2130. &scale);
  2131. }
  2132. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  2133. void *param)
  2134. {
  2135. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  2136. if (!obs_sceneitem_selected(item))
  2137. return true;
  2138. obs_video_info ovi;
  2139. obs_get_video_info(&ovi);
  2140. obs_transform_info itemInfo;
  2141. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  2142. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  2143. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  2144. itemInfo.rot = 0.0f;
  2145. vec2_set(&itemInfo.bounds,
  2146. float(ovi.base_width), float(ovi.base_height));
  2147. itemInfo.bounds_type = boundsType;
  2148. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  2149. obs_sceneitem_set_info(item, &itemInfo);
  2150. UNUSED_PARAMETER(scene);
  2151. return true;
  2152. }
  2153. void OBSBasic::on_actionFitToScreen_triggered()
  2154. {
  2155. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  2156. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  2157. &boundsType);
  2158. }
  2159. void OBSBasic::on_actionStretchToScreen_triggered()
  2160. {
  2161. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  2162. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  2163. &boundsType);
  2164. }
  2165. void OBSBasic::on_actionCenterToScreen_triggered()
  2166. {
  2167. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2168. {
  2169. vec3 tl, br, itemCenter, screenCenter, offset;
  2170. obs_video_info ovi;
  2171. if (!obs_sceneitem_selected(item))
  2172. return true;
  2173. obs_get_video_info(&ovi);
  2174. vec3_set(&screenCenter, float(ovi.base_width),
  2175. float(ovi.base_height), 0.0f);
  2176. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  2177. GetItemBox(item, tl, br);
  2178. vec3_sub(&itemCenter, &br, &tl);
  2179. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  2180. vec3_add(&itemCenter, &itemCenter, &tl);
  2181. vec3_sub(&offset, &screenCenter, &itemCenter);
  2182. vec3_add(&tl, &tl, &offset);
  2183. SetItemTL(item, tl);
  2184. UNUSED_PARAMETER(scene);
  2185. UNUSED_PARAMETER(param);
  2186. return true;
  2187. };
  2188. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  2189. }