window-basic-main.cpp 68 KB

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