window-basic-main.cpp 66 KB

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