window-basic-main.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140
  1. /******************************************************************************
  2. Copyright (C) 2013-2014 by Hugh Bailey <[email protected]>
  3. Zachary Lund <[email protected]>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. ******************************************************************************/
  15. #include <obs.hpp>
  16. #include <QMessageBox>
  17. #include <QShowEvent>
  18. #include <QFileDialog>
  19. #include <QNetworkRequest>
  20. #include <QNetworkReply>
  21. #include <util/dstr.h>
  22. #include <util/util.hpp>
  23. #include <util/platform.h>
  24. #include <graphics/math-defs.h>
  25. #include "obs-app.hpp"
  26. #include "platform.hpp"
  27. #include "window-basic-settings.hpp"
  28. #include "window-namedialog.hpp"
  29. #include "window-basic-source-select.hpp"
  30. #include "window-basic-main.hpp"
  31. #include "window-basic-properties.hpp"
  32. #include "window-log-reply.hpp"
  33. #include "qt-wrappers.hpp"
  34. #include "display-helpers.hpp"
  35. #include "volume-control.hpp"
  36. #include "ui_OBSBasic.h"
  37. #include <fstream>
  38. #include <sstream>
  39. #include <QScreen>
  40. #include <QWindow>
  41. #define PREVIEW_EDGE_SIZE 10
  42. using namespace std;
  43. Q_DECLARE_METATYPE(OBSScene);
  44. Q_DECLARE_METATYPE(OBSSceneItem);
  45. Q_DECLARE_METATYPE(order_movement);
  46. OBSBasic::OBSBasic(QWidget *parent)
  47. : OBSMainWindow (parent),
  48. ui (new Ui::OBSBasic)
  49. {
  50. ui->setupUi(this);
  51. connect(windowHandle(), &QWindow::screenChanged, [this]() {
  52. struct obs_video_info ovi;
  53. if (obs_get_video_info(&ovi))
  54. ResizePreview(ovi.base_width, ovi.base_height);
  55. });
  56. stringstream name;
  57. name << "OBS " << App()->GetVersionString();
  58. blog(LOG_INFO, "%s", name.str().c_str());
  59. setWindowTitle(QT_UTF8(name.str().c_str()));
  60. connect(ui->scenes->itemDelegate(),
  61. SIGNAL(closeEditor(QWidget*,
  62. QAbstractItemDelegate::EndEditHint)),
  63. this,
  64. SLOT(SceneNameEdited(QWidget*,
  65. QAbstractItemDelegate::EndEditHint)));
  66. connect(ui->sources->itemDelegate(),
  67. SIGNAL(closeEditor(QWidget*,
  68. QAbstractItemDelegate::EndEditHint)),
  69. this,
  70. SLOT(SceneItemNameEdited(QWidget*,
  71. QAbstractItemDelegate::EndEditHint)));
  72. }
  73. static void SaveAudioDevice(const char *name, int channel, obs_data_t parent)
  74. {
  75. obs_source_t source = obs_get_output_source(channel);
  76. if (!source)
  77. return;
  78. obs_data_t data = obs_save_source(source);
  79. obs_data_setobj(parent, name, data);
  80. obs_data_release(data);
  81. obs_source_release(source);
  82. }
  83. static obs_data_t GenerateSaveData()
  84. {
  85. obs_data_t saveData = obs_data_create();
  86. obs_data_array_t sourcesArray = obs_save_sources();
  87. obs_source_t currentScene = obs_get_output_source(0);
  88. const char *sceneName = obs_source_getname(currentScene);
  89. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData);
  90. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData);
  91. SaveAudioDevice(AUX_AUDIO_1, 3, saveData);
  92. SaveAudioDevice(AUX_AUDIO_2, 4, saveData);
  93. SaveAudioDevice(AUX_AUDIO_3, 5, saveData);
  94. obs_data_setstring(saveData, "current_scene", sceneName);
  95. obs_data_setarray(saveData, "sources", sourcesArray);
  96. obs_data_array_release(sourcesArray);
  97. obs_source_release(currentScene);
  98. return saveData;
  99. }
  100. void OBSBasic::ClearVolumeControls()
  101. {
  102. VolControl *control;
  103. for (size_t i = 0; i < volumes.size(); i++) {
  104. control = volumes[i];
  105. delete control;
  106. }
  107. volumes.clear();
  108. }
  109. void OBSBasic::Save(const char *file)
  110. {
  111. obs_data_t saveData = GenerateSaveData();
  112. const char *jsonData = obs_data_getjson(saveData);
  113. /* TODO maybe a message box here? */
  114. if (!os_quick_write_utf8_file(file, jsonData, strlen(jsonData), false))
  115. blog(LOG_ERROR, "Could not save scene data to %s", file);
  116. obs_data_release(saveData);
  117. }
  118. static void LoadAudioDevice(const char *name, int channel, obs_data_t parent)
  119. {
  120. obs_data_t data = obs_data_getobj(parent, name);
  121. if (!data)
  122. return;
  123. obs_source_t source = obs_load_source(data);
  124. if (source) {
  125. obs_set_output_source(channel, source);
  126. obs_source_release(source);
  127. }
  128. obs_data_release(data);
  129. }
  130. void OBSBasic::CreateDefaultScene()
  131. {
  132. obs_scene_t scene = obs_scene_create(Str("Basic.Scene"));
  133. obs_source_t source = obs_scene_getsource(scene);
  134. obs_add_source(source);
  135. #ifdef __APPLE__
  136. source = obs_source_create(OBS_SOURCE_TYPE_INPUT, "display_capture",
  137. Str("Basic.DisplayCapture"), NULL);
  138. if (source) {
  139. obs_scene_add(scene, source);
  140. obs_add_source(source);
  141. obs_source_release(source);
  142. }
  143. #endif
  144. obs_set_output_source(0, obs_scene_getsource(scene));
  145. obs_scene_release(scene);
  146. }
  147. void OBSBasic::Load(const char *file)
  148. {
  149. if (!file) {
  150. blog(LOG_ERROR, "Could not find file %s", file);
  151. return;
  152. }
  153. BPtr<char> jsonData = os_quick_read_utf8_file(file);
  154. if (!jsonData) {
  155. CreateDefaultScene();
  156. return;
  157. }
  158. obs_data_t data = obs_data_create_from_json(jsonData);
  159. obs_data_array_t sources = obs_data_getarray(data, "sources");
  160. const char *sceneName = obs_data_getstring(data, "current_scene");
  161. obs_source_t curScene;
  162. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  163. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  164. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  165. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  166. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  167. obs_load_sources(sources);
  168. curScene = obs_get_source_by_name(sceneName);
  169. obs_set_output_source(0, curScene);
  170. obs_source_release(curScene);
  171. obs_data_array_release(sources);
  172. obs_data_release(data);
  173. }
  174. static inline bool HasAudioDevices(const char *source_id)
  175. {
  176. const char *output_id = source_id;
  177. obs_properties_t props = obs_get_source_properties(
  178. OBS_SOURCE_TYPE_INPUT, output_id);
  179. size_t count = 0;
  180. if (!props)
  181. return false;
  182. obs_property_t devices = obs_properties_get(props, "device_id");
  183. if (devices)
  184. count = obs_property_list_item_count(devices);
  185. obs_properties_destroy(props);
  186. return count != 0;
  187. }
  188. static void OBSStartStreaming(void *data, calldata_t params)
  189. {
  190. UNUSED_PARAMETER(params);
  191. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  192. "StreamingStart");
  193. }
  194. static void OBSStopStreaming(void *data, calldata_t params)
  195. {
  196. int code = (int)calldata_int(params, "code");
  197. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  198. "StreamingStop", Q_ARG(int, code));
  199. }
  200. static void OBSStopRecording(void *data, calldata_t params)
  201. {
  202. UNUSED_PARAMETER(params);
  203. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  204. "RecordingStop");
  205. }
  206. #define SERVICE_PATH "obs-studio/basic/service.json"
  207. void OBSBasic::SaveService()
  208. {
  209. if (!service)
  210. return;
  211. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  212. if (!serviceJsonPath)
  213. return;
  214. obs_data_t data = obs_data_create();
  215. obs_data_t settings = obs_service_get_settings(service);
  216. obs_data_setstring(data, "type", obs_service_gettype(service));
  217. obs_data_setobj(data, "settings", settings);
  218. const char *json = obs_data_getjson(data);
  219. os_quick_write_utf8_file(serviceJsonPath, json, strlen(json), false);
  220. obs_data_release(settings);
  221. obs_data_release(data);
  222. }
  223. bool OBSBasic::LoadService()
  224. {
  225. const char *type;
  226. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  227. if (!serviceJsonPath)
  228. return false;
  229. BPtr<char> jsonText = os_quick_read_utf8_file(serviceJsonPath);
  230. if (!jsonText)
  231. return false;
  232. obs_data_t data = obs_data_create_from_json(jsonText);
  233. obs_data_set_default_string(data, "type", "rtmp_common");
  234. type = obs_data_getstring(data, "type");
  235. obs_data_t settings = obs_data_getobj(data, "settings");
  236. service = obs_service_create(type, "default", settings);
  237. obs_data_release(settings);
  238. obs_data_release(data);
  239. return !!service;
  240. }
  241. bool OBSBasic::InitOutputs()
  242. {
  243. fileOutput = obs_output_create("flv_output", "default", nullptr);
  244. if (!fileOutput)
  245. return false;
  246. streamOutput = obs_output_create("rtmp_output", "default", nullptr);
  247. if (!streamOutput)
  248. return false;
  249. signal_handler_connect(obs_output_signalhandler(streamOutput),
  250. "start", OBSStartStreaming, this);
  251. signal_handler_connect(obs_output_signalhandler(streamOutput),
  252. "stop", OBSStopStreaming, this);
  253. signal_handler_connect(obs_output_signalhandler(fileOutput),
  254. "stop", OBSStopRecording, this);
  255. return true;
  256. }
  257. bool OBSBasic::InitEncoders()
  258. {
  259. x264 = obs_video_encoder_create("obs_x264", "h264", nullptr);
  260. if (!x264)
  261. return false;
  262. aac = obs_audio_encoder_create("libfdk_aac", "aac", nullptr);
  263. if(!aac)
  264. aac = obs_audio_encoder_create("ffmpeg_aac", "aac", nullptr);
  265. if (!aac)
  266. return false;
  267. return true;
  268. }
  269. bool OBSBasic::InitService()
  270. {
  271. if (LoadService())
  272. return true;
  273. service = obs_service_create("rtmp_common", nullptr, nullptr);
  274. if (!service)
  275. return false;
  276. return true;
  277. }
  278. bool OBSBasic::InitBasicConfigDefaults()
  279. {
  280. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  281. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  282. config_set_default_int(basicConfig, "Window", "PosX", -1);
  283. config_set_default_int(basicConfig, "Window", "PosY", -1);
  284. config_set_default_int(basicConfig, "Window", "SizeX", -1);
  285. config_set_default_int(basicConfig, "Window", "SizeY", -1);
  286. vector<MonitorInfo> monitors;
  287. GetMonitors(monitors);
  288. if (!monitors.size()) {
  289. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  290. "technically shouldn't be possible.");
  291. return false;
  292. }
  293. uint32_t cx = monitors[0].cx;
  294. uint32_t cy = monitors[0].cy;
  295. /* TODO: temporary */
  296. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  297. GetDefaultVideoSavePath().c_str());
  298. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  299. 2500);
  300. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 128);
  301. config_set_default_bool (basicConfig, "SimpleOutput", "Reconnect",
  302. true);
  303. config_set_default_uint (basicConfig, "SimpleOutput", "RetryDelay", 2);
  304. config_set_default_uint (basicConfig, "SimpleOutput", "MaxRetries",
  305. 20);
  306. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  307. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  308. cx = cx * 10 / 15;
  309. cy = cy * 10 / 15;
  310. config_set_default_uint (basicConfig, "Video", "OutputCX", cx);
  311. config_set_default_uint (basicConfig, "Video", "OutputCY", cy);
  312. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  313. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  314. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  315. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  316. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  317. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  318. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  319. "Stereo");
  320. config_set_default_uint (basicConfig, "Audio", "BufferingTime", 1000);
  321. config_set_default_string(basicConfig, "Audio", "DesktopDevice1",
  322. hasDesktopAudio ? "default" : "disabled");
  323. config_set_default_string(basicConfig, "Audio", "DesktopDevice2",
  324. "disabled");
  325. config_set_default_string(basicConfig, "Audio", "AuxDevice1",
  326. hasInputAudio ? "default" : "disabled");
  327. config_set_default_string(basicConfig, "Audio", "AuxDevice2",
  328. "disabled");
  329. config_set_default_string(basicConfig, "Audio", "AuxDevice3",
  330. "disabled");
  331. return true;
  332. }
  333. bool OBSBasic::InitBasicConfig()
  334. {
  335. BPtr<char> configPath(os_get_config_path("obs-studio/basic/basic.ini"));
  336. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  337. if (code != CONFIG_SUCCESS) {
  338. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  339. return false;
  340. }
  341. return InitBasicConfigDefaults();
  342. }
  343. void OBSBasic::InitOBSCallbacks()
  344. {
  345. signal_handler_connect(obs_signalhandler(), "source_add",
  346. OBSBasic::SourceAdded, this);
  347. signal_handler_connect(obs_signalhandler(), "source_remove",
  348. OBSBasic::SourceRemoved, this);
  349. signal_handler_connect(obs_signalhandler(), "channel_change",
  350. OBSBasic::ChannelChanged, this);
  351. signal_handler_connect(obs_signalhandler(), "source_activate",
  352. OBSBasic::SourceActivated, this);
  353. signal_handler_connect(obs_signalhandler(), "source_deactivate",
  354. OBSBasic::SourceDeactivated, this);
  355. signal_handler_connect(obs_signalhandler(), "source_rename",
  356. OBSBasic::SourceRenamed, this);
  357. }
  358. void OBSBasic::InitPrimitives()
  359. {
  360. gs_entercontext(obs_graphics());
  361. gs_renderstart(true);
  362. gs_vertex2f(0.0f, 0.0f);
  363. gs_vertex2f(0.0f, 1.0f);
  364. gs_vertex2f(1.0f, 1.0f);
  365. gs_vertex2f(1.0f, 0.0f);
  366. gs_vertex2f(0.0f, 0.0f);
  367. box = gs_rendersave();
  368. gs_renderstart(true);
  369. for (int i = 0; i <= 360; i += (360/20)) {
  370. float pos = RAD(float(i));
  371. gs_vertex2f(cosf(pos), sinf(pos));
  372. }
  373. circle = gs_rendersave();
  374. gs_leavecontext();
  375. }
  376. void OBSBasic::OBSInit()
  377. {
  378. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  379. /* make sure it's fully displayed before doing any initialization */
  380. show();
  381. App()->processEvents();
  382. if (!obs_startup(App()->GetLocale()))
  383. throw "Failed to initialize libobs";
  384. if (!InitBasicConfig())
  385. throw "Failed to load basic.ini";
  386. if (!ResetVideo())
  387. throw "Failed to initialize video";
  388. if (!ResetAudio())
  389. throw "Failed to initialize audio";
  390. InitOBSCallbacks();
  391. /* TODO: this is a test, all modules will be searched for and loaded
  392. * automatically later */
  393. obs_load_module("image-source");
  394. obs_load_module("test-input");
  395. obs_load_module("obs-ffmpeg");
  396. obs_load_module("obs-libfdk");
  397. obs_load_module("obs-x264");
  398. obs_load_module("obs-outputs");
  399. obs_load_module("rtmp-services");
  400. #ifdef __APPLE__
  401. obs_load_module("mac-avcapture");
  402. obs_load_module("mac-capture");
  403. #elif _WIN32
  404. obs_load_module("win-wasapi");
  405. obs_load_module("win-capture");
  406. obs_load_module("win-dshow");
  407. #else
  408. obs_load_module("linux-xshm");
  409. obs_load_module("linux-xcomposite");
  410. obs_load_module("linux-pulseaudio");
  411. obs_load_module("linux-v4l2");
  412. #endif
  413. if (!InitOutputs())
  414. throw "Failed to initialize outputs";
  415. if (!InitEncoders())
  416. throw "Failed to initialize encoders";
  417. if (!InitService())
  418. throw "Failed to initialize service";
  419. InitPrimitives();
  420. Load(savePath);
  421. ResetAudioDevices();
  422. loaded = true;
  423. }
  424. OBSBasic::~OBSBasic()
  425. {
  426. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  427. SaveService();
  428. Save(savePath);
  429. /* XXX: any obs data must be released before calling obs_shutdown.
  430. * currently, we can't automate this with C++ RAII because of the
  431. * delicate nature of obs_shutdown needing to be freed before the UI
  432. * can be freed, and we have no control over the destruction order of
  433. * the Qt UI stuff, so we have to manually clear any references to
  434. * libobs. */
  435. delete properties;
  436. delete transformWindow;
  437. ClearVolumeControls();
  438. ui->sources->clear();
  439. ui->scenes->clear();
  440. gs_entercontext(obs_graphics());
  441. vertexbuffer_destroy(box);
  442. vertexbuffer_destroy(circle);
  443. gs_leavecontext();
  444. obs_shutdown();
  445. }
  446. OBSScene OBSBasic::GetCurrentScene()
  447. {
  448. QListWidgetItem *item = ui->scenes->currentItem();
  449. return item ? item->data(Qt::UserRole).value<OBSScene>() : nullptr;
  450. }
  451. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  452. {
  453. QListWidgetItem *item = ui->sources->currentItem();
  454. return item ? item->data(Qt::UserRole).value<OBSSceneItem>() : nullptr;
  455. }
  456. void OBSBasic::UpdateSources(OBSScene scene)
  457. {
  458. ui->sources->clear();
  459. obs_scene_enum_items(scene,
  460. [] (obs_scene_t scene, obs_sceneitem_t item, void *p)
  461. {
  462. OBSBasic *window = static_cast<OBSBasic*>(p);
  463. window->InsertSceneItem(item);
  464. UNUSED_PARAMETER(scene);
  465. return true;
  466. }, this);
  467. }
  468. void OBSBasic::InsertSceneItem(obs_sceneitem_t item)
  469. {
  470. obs_source_t source = obs_sceneitem_getsource(item);
  471. const char *name = obs_source_getname(source);
  472. QListWidgetItem *listItem = new QListWidgetItem(QT_UTF8(name));
  473. listItem->setFlags(listItem->flags() | Qt::ItemIsEditable);
  474. listItem->setData(Qt::UserRole,
  475. QVariant::fromValue(OBSSceneItem(item)));
  476. ui->sources->insertItem(0, listItem);
  477. ui->sources->setCurrentRow(0);
  478. /* if the source was just created, open properties dialog */
  479. if (sourceSceneRefs[source] == 0 && loaded) {
  480. delete properties;
  481. properties = new OBSBasicProperties(this, source);
  482. properties->Init();
  483. }
  484. }
  485. /* Qt callbacks for invokeMethod */
  486. void OBSBasic::AddScene(OBSSource source)
  487. {
  488. const char *name = obs_source_getname(source);
  489. obs_scene_t scene = obs_scene_fromsource(source);
  490. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  491. item->setFlags(item->flags() | Qt::ItemIsEditable);
  492. item->setData(Qt::UserRole, QVariant::fromValue(OBSScene(scene)));
  493. ui->scenes->addItem(item);
  494. signal_handler_t handler = obs_source_signalhandler(source);
  495. signal_handler_connect(handler, "item_add",
  496. OBSBasic::SceneItemAdded, this);
  497. signal_handler_connect(handler, "item_remove",
  498. OBSBasic::SceneItemRemoved, this);
  499. signal_handler_connect(handler, "item_move_up",
  500. OBSBasic::SceneItemMoveUp, this);
  501. signal_handler_connect(handler, "item_move_down",
  502. OBSBasic::SceneItemMoveDown, this);
  503. signal_handler_connect(handler, "item_move_top",
  504. OBSBasic::SceneItemMoveTop, this);
  505. signal_handler_connect(handler, "item_move_bottom",
  506. OBSBasic::SceneItemMoveBottom, this);
  507. }
  508. void OBSBasic::RemoveScene(OBSSource source)
  509. {
  510. const char *name = obs_source_getname(source);
  511. QListWidgetItem *sel = ui->scenes->currentItem();
  512. QList<QListWidgetItem*> items = ui->scenes->findItems(QT_UTF8(name),
  513. Qt::MatchExactly);
  514. if (sel != nullptr) {
  515. if (items.contains(sel))
  516. ui->sources->clear();
  517. delete sel;
  518. }
  519. }
  520. void OBSBasic::AddSceneItem(OBSSceneItem item)
  521. {
  522. obs_scene_t scene = obs_sceneitem_getscene(item);
  523. obs_source_t source = obs_sceneitem_getsource(item);
  524. if (GetCurrentScene() == scene)
  525. InsertSceneItem(item);
  526. sourceSceneRefs[source] = sourceSceneRefs[source] + 1;
  527. }
  528. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  529. {
  530. obs_scene_t scene = obs_sceneitem_getscene(item);
  531. if (GetCurrentScene() == scene) {
  532. for (int i = 0; i < ui->sources->count(); i++) {
  533. QListWidgetItem *listItem = ui->sources->item(i);
  534. QVariant userData = listItem->data(Qt::UserRole);
  535. if (userData.value<OBSSceneItem>() == item) {
  536. delete listItem;
  537. break;
  538. }
  539. }
  540. }
  541. obs_source_t source = obs_sceneitem_getsource(item);
  542. int scenes = sourceSceneRefs[source] - 1;
  543. sourceSceneRefs[source] = scenes;
  544. if (scenes == 0) {
  545. obs_source_remove(source);
  546. sourceSceneRefs.erase(source);
  547. }
  548. }
  549. void OBSBasic::UpdateSceneSelection(OBSSource source)
  550. {
  551. if (source) {
  552. obs_source_type type;
  553. obs_source_gettype(source, &type, NULL);
  554. obs_scene_t scene = obs_scene_fromsource(source);
  555. const char *name = obs_source_getname(source);
  556. if (!scene)
  557. return;
  558. QList<QListWidgetItem*> items =
  559. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  560. if (items.count()) {
  561. sceneChanging = true;
  562. ui->scenes->setCurrentItem(items.first());
  563. sceneChanging = false;
  564. UpdateSources(scene);
  565. }
  566. }
  567. }
  568. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  569. const QString &prevName)
  570. {
  571. QList<QListWidgetItem*> items =
  572. listWidget->findItems(prevName, Qt::MatchExactly);
  573. for (int i = 0; i < items.count(); i++)
  574. items[i]->setText(newName);
  575. }
  576. void OBSBasic::RenameSources(QString newName, QString prevName)
  577. {
  578. RenameListValues(ui->scenes, newName, prevName);
  579. RenameListValues(ui->sources, newName, prevName);
  580. }
  581. void OBSBasic::MoveSceneItem(OBSSceneItem item, order_movement movement)
  582. {
  583. OBSScene scene = obs_sceneitem_getscene(item);
  584. if (scene != GetCurrentScene())
  585. return;
  586. int curRow = ui->sources->currentRow();
  587. if (curRow == -1)
  588. return;
  589. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  590. switch (movement) {
  591. case ORDER_MOVE_UP:
  592. if (curRow > 0)
  593. curRow--;
  594. break;
  595. case ORDER_MOVE_DOWN:
  596. if (curRow < ui->sources->count())
  597. curRow++;
  598. break;
  599. case ORDER_MOVE_TOP:
  600. curRow = 0;
  601. break;
  602. case ORDER_MOVE_BOTTOM:
  603. curRow = ui->sources->count();
  604. break;
  605. }
  606. ui->sources->insertItem(curRow, listItem);
  607. ui->sources->setCurrentRow(curRow);
  608. }
  609. void OBSBasic::ActivateAudioSource(OBSSource source)
  610. {
  611. VolControl *vol = new VolControl(source);
  612. volumes.push_back(vol);
  613. ui->volumeWidgets->layout()->addWidget(vol);
  614. }
  615. void OBSBasic::DeactivateAudioSource(OBSSource source)
  616. {
  617. for (size_t i = 0; i < volumes.size(); i++) {
  618. if (volumes[i]->GetSource() == source) {
  619. delete volumes[i];
  620. volumes.erase(volumes.begin() + i);
  621. break;
  622. }
  623. }
  624. }
  625. bool OBSBasic::QueryRemoveSource(obs_source_t source)
  626. {
  627. const char *name = obs_source_getname(source);
  628. QString text = QTStr("ConfirmRemove.Text");
  629. text.replace("$1", QT_UTF8(name));
  630. QMessageBox::StandardButton button;
  631. button = QMessageBox::question(this,
  632. QTStr("ConfirmRemove.Remove"), text);
  633. return button == QMessageBox::Yes;
  634. }
  635. void OBSBasic::RemoveSelectedScene()
  636. {
  637. OBSScene scene = GetCurrentScene();
  638. if (scene) {
  639. obs_source_t source = obs_scene_getsource(scene);
  640. if (QueryRemoveSource(source))
  641. obs_source_remove(source);
  642. }
  643. }
  644. void OBSBasic::RemoveSelectedSceneItem()
  645. {
  646. OBSSceneItem item = GetCurrentSceneItem();
  647. if (item) {
  648. obs_source_t source = obs_sceneitem_getsource(item);
  649. if (QueryRemoveSource(source))
  650. obs_sceneitem_remove(item);
  651. }
  652. }
  653. /* OBS Callbacks */
  654. void OBSBasic::SceneItemAdded(void *data, calldata_t params)
  655. {
  656. OBSBasic *window = static_cast<OBSBasic*>(data);
  657. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  658. QMetaObject::invokeMethod(window, "AddSceneItem",
  659. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  660. }
  661. void OBSBasic::SceneItemRemoved(void *data, calldata_t params)
  662. {
  663. OBSBasic *window = static_cast<OBSBasic*>(data);
  664. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  665. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  666. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  667. }
  668. void OBSBasic::SourceAdded(void *data, calldata_t params)
  669. {
  670. OBSBasic *window = static_cast<OBSBasic*>(data);
  671. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  672. if (obs_scene_fromsource(source) != NULL)
  673. QMetaObject::invokeMethod(window,
  674. "AddScene",
  675. Q_ARG(OBSSource, OBSSource(source)));
  676. else
  677. window->sourceSceneRefs[source] = 0;
  678. }
  679. void OBSBasic::SourceRemoved(void *data, calldata_t params)
  680. {
  681. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  682. if (obs_scene_fromsource(source) != NULL)
  683. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  684. "RemoveScene",
  685. Q_ARG(OBSSource, OBSSource(source)));
  686. }
  687. void OBSBasic::SourceActivated(void *data, calldata_t params)
  688. {
  689. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  690. uint32_t flags = obs_source_get_output_flags(source);
  691. if (flags & OBS_SOURCE_AUDIO)
  692. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  693. "ActivateAudioSource",
  694. Q_ARG(OBSSource, OBSSource(source)));
  695. }
  696. void OBSBasic::SourceDeactivated(void *data, calldata_t params)
  697. {
  698. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  699. uint32_t flags = obs_source_get_output_flags(source);
  700. if (flags & OBS_SOURCE_AUDIO)
  701. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  702. "DeactivateAudioSource",
  703. Q_ARG(OBSSource, OBSSource(source)));
  704. }
  705. void OBSBasic::SourceRenamed(void *data, calldata_t params)
  706. {
  707. const char *newName = calldata_string(params, "new_name");
  708. const char *prevName = calldata_string(params, "prev_name");
  709. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  710. "RenameSources",
  711. Q_ARG(QString, QT_UTF8(newName)),
  712. Q_ARG(QString, QT_UTF8(prevName)));
  713. }
  714. void OBSBasic::ChannelChanged(void *data, calldata_t params)
  715. {
  716. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  717. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  718. if (channel == 0)
  719. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  720. "UpdateSceneSelection",
  721. Q_ARG(OBSSource, OBSSource(source)));
  722. }
  723. void OBSBasic::DrawBackdrop(float cx, float cy)
  724. {
  725. if (!box)
  726. return;
  727. effect_t solid = obs_get_solid_effect();
  728. eparam_t color = effect_getparambyname(solid, "color");
  729. technique_t tech = effect_gettechnique(solid, "Solid");
  730. vec4 colorVal;
  731. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  732. effect_setvec4(color, &colorVal);
  733. technique_begin(tech);
  734. technique_beginpass(tech, 0);
  735. gs_matrix_push();
  736. gs_matrix_identity();
  737. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  738. gs_load_vertexbuffer(box);
  739. gs_draw(GS_TRISTRIP, 0, 0);
  740. gs_matrix_pop();
  741. technique_endpass(tech);
  742. technique_end(tech);
  743. gs_load_vertexbuffer(nullptr);
  744. }
  745. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  746. {
  747. OBSBasic *window = static_cast<OBSBasic*>(data);
  748. obs_video_info ovi;
  749. obs_get_video_info(&ovi);
  750. window->previewCX = int(window->previewScale * float(ovi.base_width));
  751. window->previewCY = int(window->previewScale * float(ovi.base_height));
  752. gs_viewport_push();
  753. gs_projection_push();
  754. /* --------------------------------------- */
  755. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  756. -100.0f, 100.0f);
  757. gs_setviewport(window->previewX, window->previewY,
  758. window->previewCX, window->previewCY);
  759. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  760. obs_render_main_view();
  761. gs_load_vertexbuffer(nullptr);
  762. /* --------------------------------------- */
  763. float right = float(window->ui->preview->width()) - window->previewX;
  764. float bottom = float(window->ui->preview->height()) - window->previewY;
  765. gs_ortho(-window->previewX, right,
  766. -window->previewY, bottom,
  767. -100.0f, 100.0f);
  768. gs_resetviewport();
  769. window->ui->preview->DrawSceneEditing();
  770. /* --------------------------------------- */
  771. gs_projection_pop();
  772. gs_viewport_pop();
  773. UNUSED_PARAMETER(cx);
  774. UNUSED_PARAMETER(cy);
  775. }
  776. void OBSBasic::SceneItemMoveUp(void *data, calldata_t params)
  777. {
  778. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  779. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  780. "MoveSceneItem",
  781. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  782. Q_ARG(order_movement, ORDER_MOVE_UP));
  783. }
  784. void OBSBasic::SceneItemMoveDown(void *data, calldata_t params)
  785. {
  786. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  787. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  788. "MoveSceneItem",
  789. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  790. Q_ARG(order_movement, ORDER_MOVE_DOWN));
  791. }
  792. void OBSBasic::SceneItemMoveTop(void *data, calldata_t params)
  793. {
  794. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  795. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  796. "MoveSceneItem",
  797. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  798. Q_ARG(order_movement, ORDER_MOVE_TOP));
  799. }
  800. void OBSBasic::SceneItemMoveBottom(void *data, calldata_t params)
  801. {
  802. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  803. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  804. "MoveSceneItem",
  805. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  806. Q_ARG(order_movement, ORDER_MOVE_BOTTOM));
  807. }
  808. /* Main class functions */
  809. obs_service_t OBSBasic::GetService()
  810. {
  811. if (!service)
  812. service = obs_service_create("rtmp_common", NULL, NULL);
  813. return service;
  814. }
  815. void OBSBasic::SetService(obs_service_t newService)
  816. {
  817. if (newService) {
  818. if (service)
  819. obs_service_destroy(service);
  820. service = newService;
  821. }
  822. }
  823. bool OBSBasic::ResetVideo()
  824. {
  825. struct obs_video_info ovi;
  826. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  827. ovi.graphics_module = App()->GetRenderModule();
  828. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  829. "Video", "BaseCX");
  830. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  831. "Video", "BaseCY");
  832. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  833. "Video", "OutputCX");
  834. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  835. "Video", "OutputCY");
  836. ovi.output_format = VIDEO_FORMAT_NV12;
  837. ovi.adapter = 0;
  838. ovi.gpu_conversion = true;
  839. QTToGSWindow(ui->preview->winId(), ovi.window);
  840. //required to make opengl display stuff on osx(?)
  841. ResizePreview(ovi.base_width, ovi.base_height);
  842. QSize size = GetPixelSize(ui->preview);
  843. ovi.window_width = size.width();
  844. ovi.window_height = size.height();
  845. if (!obs_reset_video(&ovi))
  846. return false;
  847. obs_add_draw_callback(OBSBasic::RenderMain, this);
  848. return true;
  849. }
  850. bool OBSBasic::ResetAudio()
  851. {
  852. struct audio_output_info ai;
  853. ai.name = "Main Audio Track";
  854. ai.format = AUDIO_FORMAT_FLOAT;
  855. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  856. "SampleRate");
  857. const char *channelSetupStr = config_get_string(basicConfig,
  858. "Audio", "ChannelSetup");
  859. if (strcmp(channelSetupStr, "Mono") == 0)
  860. ai.speakers = SPEAKERS_MONO;
  861. else
  862. ai.speakers = SPEAKERS_STEREO;
  863. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  864. return obs_reset_audio(&ai);
  865. }
  866. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  867. const char *deviceDesc, int channel)
  868. {
  869. const char *deviceId = config_get_string(basicConfig, "Audio",
  870. deviceName);
  871. obs_source_t source;
  872. obs_data_t settings;
  873. bool same = false;
  874. source = obs_get_output_source(channel);
  875. if (source) {
  876. settings = obs_source_getsettings(source);
  877. const char *curId = obs_data_getstring(settings, "device_id");
  878. same = (strcmp(curId, deviceId) == 0);
  879. obs_data_release(settings);
  880. obs_source_release(source);
  881. }
  882. if (!same)
  883. obs_set_output_source(channel, nullptr);
  884. if (!same && strcmp(deviceId, "disabled") != 0) {
  885. obs_data_t settings = obs_data_create();
  886. obs_data_setstring(settings, "device_id", deviceId);
  887. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  888. sourceId, deviceDesc, settings);
  889. obs_data_release(settings);
  890. obs_set_output_source(channel, source);
  891. obs_source_release(source);
  892. }
  893. }
  894. void OBSBasic::ResetAudioDevices()
  895. {
  896. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  897. Str("Basic.DesktopDevice1"), 1);
  898. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  899. Str("Basic.DesktopDevice2"), 2);
  900. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  901. Str("Basic.AuxDevice1"), 3);
  902. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  903. Str("Basic.AuxDevice2"), 4);
  904. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  905. Str("Basic.AuxDevice3"), 5);
  906. }
  907. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  908. {
  909. QSize targetSize;
  910. /* resize preview panel to fix to the top section of the window */
  911. targetSize = GetPixelSize(ui->preview);
  912. GetScaleAndCenterPos(int(cx), int(cy),
  913. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  914. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  915. previewX, previewY, previewScale);
  916. previewX += float(PREVIEW_EDGE_SIZE);
  917. previewY += float(PREVIEW_EDGE_SIZE);
  918. if (isVisible()) {
  919. if (resizeTimer)
  920. killTimer(resizeTimer);
  921. resizeTimer = startTimer(100);
  922. }
  923. }
  924. void OBSBasic::closeEvent(QCloseEvent *event)
  925. {
  926. QWidget::closeEvent(event);
  927. if (!event->isAccepted())
  928. return;
  929. // remove draw callback in case our drawable surfaces go away before
  930. // the destructor gets called
  931. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  932. }
  933. void OBSBasic::changeEvent(QEvent *event)
  934. {
  935. /* TODO */
  936. UNUSED_PARAMETER(event);
  937. }
  938. void OBSBasic::resizeEvent(QResizeEvent *event)
  939. {
  940. struct obs_video_info ovi;
  941. if (obs_get_video_info(&ovi))
  942. ResizePreview(ovi.base_width, ovi.base_height);
  943. UNUSED_PARAMETER(event);
  944. }
  945. void OBSBasic::timerEvent(QTimerEvent *event)
  946. {
  947. if (event->timerId() == resizeTimer) {
  948. killTimer(resizeTimer);
  949. resizeTimer = 0;
  950. QSize size = GetPixelSize(ui->preview);
  951. obs_resize(size.width(), size.height());
  952. }
  953. }
  954. void OBSBasic::on_action_New_triggered()
  955. {
  956. /* TODO */
  957. }
  958. void OBSBasic::on_action_Open_triggered()
  959. {
  960. /* TODO */
  961. }
  962. void OBSBasic::on_action_Save_triggered()
  963. {
  964. /* TODO */
  965. }
  966. void OBSBasic::on_action_Settings_triggered()
  967. {
  968. OBSBasicSettings settings(this);
  969. settings.exec();
  970. }
  971. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  972. QListWidgetItem *prev)
  973. {
  974. obs_source_t source = NULL;
  975. if (sceneChanging)
  976. return;
  977. if (current) {
  978. obs_scene_t scene;
  979. scene = current->data(Qt::UserRole).value<OBSScene>();
  980. source = obs_scene_getsource(scene);
  981. }
  982. /* TODO: allow transitions */
  983. obs_set_output_source(0, source);
  984. UNUSED_PARAMETER(prev);
  985. }
  986. void OBSBasic::EditSceneName()
  987. {
  988. ui->scenes->editItem(ui->scenes->currentItem());
  989. }
  990. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  991. {
  992. QListWidgetItem *item = ui->scenes->itemAt(pos);
  993. QMenu popup;
  994. popup.addAction(QTStr("Add"),
  995. this, SLOT(on_actionAddScene_triggered()));
  996. if (item)
  997. popup.addAction(QTStr("Remove"),
  998. this, SLOT(RemoveSelectedScene()));
  999. popup.exec(QCursor::pos());
  1000. }
  1001. void OBSBasic::on_actionAddScene_triggered()
  1002. {
  1003. string name;
  1004. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1005. int i = 1;
  1006. QString placeHolderText = format.arg(i);
  1007. obs_source_t source = nullptr;
  1008. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1009. obs_source_release(source);
  1010. placeHolderText = format.arg(++i);
  1011. }
  1012. bool accepted = NameDialog::AskForName(this,
  1013. QTStr("Basic.Main.AddSceneDlg.Title"),
  1014. QTStr("Basic.Main.AddSceneDlg.Text"),
  1015. name,
  1016. placeHolderText);
  1017. if (accepted) {
  1018. if (name.empty()) {
  1019. QMessageBox::information(this,
  1020. QTStr("NoNameEntered"),
  1021. QTStr("NoNameEntered"));
  1022. on_actionAddScene_triggered();
  1023. return;
  1024. }
  1025. obs_source_t source = obs_get_source_by_name(name.c_str());
  1026. if (source) {
  1027. QMessageBox::information(this,
  1028. QTStr("NameExists.Title"),
  1029. QTStr("NameExists.Text"));
  1030. obs_source_release(source);
  1031. on_actionAddScene_triggered();
  1032. return;
  1033. }
  1034. obs_scene_t scene = obs_scene_create(name.c_str());
  1035. source = obs_scene_getsource(scene);
  1036. obs_add_source(source);
  1037. obs_scene_release(scene);
  1038. obs_set_output_source(0, source);
  1039. }
  1040. }
  1041. void OBSBasic::on_actionRemoveScene_triggered()
  1042. {
  1043. OBSScene scene = GetCurrentScene();
  1044. obs_source_t source = obs_scene_getsource(scene);
  1045. if (source && QueryRemoveSource(source))
  1046. obs_source_remove(source);
  1047. }
  1048. void OBSBasic::on_actionSceneProperties_triggered()
  1049. {
  1050. /* TODO */
  1051. }
  1052. void OBSBasic::on_actionSceneUp_triggered()
  1053. {
  1054. /* TODO */
  1055. }
  1056. void OBSBasic::on_actionSceneDown_triggered()
  1057. {
  1058. /* TODO */
  1059. }
  1060. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1061. QListWidgetItem *prev)
  1062. {
  1063. auto select_one = [] (obs_scene_t scene, obs_sceneitem_t item,
  1064. void *param)
  1065. {
  1066. obs_sceneitem_t selectedItem =
  1067. *reinterpret_cast<OBSSceneItem*>(param);
  1068. obs_sceneitem_select(item, (selectedItem == item));
  1069. UNUSED_PARAMETER(scene);
  1070. return true;
  1071. };
  1072. if (!current)
  1073. return;
  1074. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1075. obs_source_t source = obs_sceneitem_getsource(item);
  1076. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1077. return;
  1078. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1079. UNUSED_PARAMETER(prev);
  1080. }
  1081. void OBSBasic::EditSceneItemName()
  1082. {
  1083. ui->sources->editItem(ui->sources->currentItem());
  1084. }
  1085. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1086. {
  1087. QListWidgetItem *item = ui->sources->itemAt(pos);
  1088. QMenu popup;
  1089. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1090. if (addSourceMenu)
  1091. popup.addMenu(addSourceMenu);
  1092. if (item) {
  1093. if (addSourceMenu)
  1094. popup.addSeparator();
  1095. popup.addAction(QTStr("Rename"), this,
  1096. SLOT(EditSceneItemName()));
  1097. popup.addAction(QTStr("Remove"), this,
  1098. SLOT(on_actionRemoveSource_triggered()),
  1099. QKeySequence::Delete);
  1100. popup.addSeparator();
  1101. popup.addMenu(ui->orderMenu);
  1102. popup.addMenu(ui->transformMenu);
  1103. popup.addSeparator();
  1104. popup.addAction(QTStr("Properties"), this,
  1105. SLOT(on_actionSourceProperties_triggered()));
  1106. }
  1107. popup.exec(QCursor::pos());
  1108. }
  1109. void OBSBasic::AddSource(const char *id)
  1110. {
  1111. if (id && *id) {
  1112. OBSBasicSourceSelect sourceSelect(this, id);
  1113. sourceSelect.exec();
  1114. }
  1115. }
  1116. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1117. {
  1118. const char *type;
  1119. bool foundValues = false;
  1120. size_t idx = 0;
  1121. QMenu *popup = new QMenu(QTStr("Add"));
  1122. while (obs_enum_input_types(idx++, &type)) {
  1123. const char *name = obs_source_getdisplayname(
  1124. OBS_SOURCE_TYPE_INPUT, type);
  1125. if (strcmp(type, "scene") == 0)
  1126. continue;
  1127. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1128. popupItem->setData(QT_UTF8(type));
  1129. connect(popupItem, SIGNAL(triggered(bool)),
  1130. this, SLOT(AddSourceFromAction()));
  1131. popup->addAction(popupItem);
  1132. foundValues = true;
  1133. }
  1134. if (!foundValues) {
  1135. delete popup;
  1136. popup = nullptr;
  1137. }
  1138. return popup;
  1139. }
  1140. void OBSBasic::AddSourceFromAction()
  1141. {
  1142. QAction *action = qobject_cast<QAction*>(sender());
  1143. if (!action)
  1144. return;
  1145. AddSource(QT_TO_UTF8(action->data().toString()));
  1146. }
  1147. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1148. {
  1149. if (!GetCurrentScene()) {
  1150. // Tell the user he needs a scene first (help beginners).
  1151. QMessageBox::information(this,
  1152. QTStr("Basic.Main.AddSourceHelp.Title"),
  1153. QTStr("Basic.Main.AddSourceHelp.Text"));
  1154. return;
  1155. }
  1156. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1157. if (popup)
  1158. popup->exec(pos);
  1159. }
  1160. void OBSBasic::on_actionAddSource_triggered()
  1161. {
  1162. AddSourcePopupMenu(QCursor::pos());
  1163. }
  1164. void OBSBasic::on_actionRemoveSource_triggered()
  1165. {
  1166. OBSSceneItem item = GetCurrentSceneItem();
  1167. obs_source_t source = obs_sceneitem_getsource(item);
  1168. if (source && QueryRemoveSource(source))
  1169. obs_sceneitem_remove(item);
  1170. }
  1171. void OBSBasic::on_actionSourceProperties_triggered()
  1172. {
  1173. OBSSceneItem item = GetCurrentSceneItem();
  1174. OBSSource source = obs_sceneitem_getsource(item);
  1175. if (source) {
  1176. delete properties;
  1177. properties = new OBSBasicProperties(this, source);
  1178. properties->Init();
  1179. }
  1180. }
  1181. void OBSBasic::on_actionSourceUp_triggered()
  1182. {
  1183. OBSSceneItem item = GetCurrentSceneItem();
  1184. obs_sceneitem_setorder(item, ORDER_MOVE_UP);
  1185. }
  1186. void OBSBasic::on_actionSourceDown_triggered()
  1187. {
  1188. OBSSceneItem item = GetCurrentSceneItem();
  1189. obs_sceneitem_setorder(item, ORDER_MOVE_DOWN);
  1190. }
  1191. void OBSBasic::on_actionMoveUp_triggered()
  1192. {
  1193. OBSSceneItem item = GetCurrentSceneItem();
  1194. obs_sceneitem_setorder(item, ORDER_MOVE_UP);
  1195. }
  1196. void OBSBasic::on_actionMoveDown_triggered()
  1197. {
  1198. OBSSceneItem item = GetCurrentSceneItem();
  1199. obs_sceneitem_setorder(item, ORDER_MOVE_DOWN);
  1200. }
  1201. void OBSBasic::on_actionMoveToTop_triggered()
  1202. {
  1203. OBSSceneItem item = GetCurrentSceneItem();
  1204. obs_sceneitem_setorder(item, ORDER_MOVE_TOP);
  1205. }
  1206. void OBSBasic::on_actionMoveToBottom_triggered()
  1207. {
  1208. OBSSceneItem item = GetCurrentSceneItem();
  1209. obs_sceneitem_setorder(item, ORDER_MOVE_BOTTOM);
  1210. }
  1211. static char *ReadLogFile(const char *log)
  1212. {
  1213. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  1214. string path = (char*)logDir;
  1215. path += "/";
  1216. path += log;
  1217. char *file = os_quick_read_utf8_file(path.c_str());
  1218. if (!file)
  1219. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1220. return file;
  1221. }
  1222. void OBSBasic::UploadLog(const char *file)
  1223. {
  1224. dstr fileString = {};
  1225. stringstream ss;
  1226. string jsonData;
  1227. dstr_move_array(&fileString, ReadLogFile(file));
  1228. if (!fileString.array)
  1229. return;
  1230. if (!*fileString.array) {
  1231. dstr_free(&fileString);
  1232. return;
  1233. }
  1234. ui->menuLogFiles->setEnabled(false);
  1235. dstr_replace(&fileString, "\\", "\\\\");
  1236. dstr_replace(&fileString, "\"", "\\\"");
  1237. dstr_replace(&fileString, "\n", "\\n");
  1238. dstr_replace(&fileString, "\r", "\\r");
  1239. dstr_replace(&fileString, "\t", "\\t");
  1240. dstr_replace(&fileString, "\t", "\\t");
  1241. dstr_replace(&fileString, "/", "\\/");
  1242. ss << "{ \"public\": false, \"description\": \"OBS " <<
  1243. App()->GetVersionString() << " log file uploaded at " <<
  1244. CurrentDateTimeString() << "\", \"files\": { \"" <<
  1245. file << "\": { \"content\": \"" <<
  1246. fileString.array << "\" } } }";
  1247. jsonData = std::move(ss.str());
  1248. logUploadPostData.setData(jsonData.c_str(), (int)jsonData.size());
  1249. QUrl url("https://api.github.com/gists");
  1250. logUploadReply = networkManager.post(QNetworkRequest(url),
  1251. &logUploadPostData);
  1252. connect(logUploadReply, SIGNAL(finished()),
  1253. this, SLOT(logUploadFinished()));
  1254. connect(logUploadReply, SIGNAL(readyRead()),
  1255. this, SLOT(logUploadRead()));
  1256. dstr_free(&fileString);
  1257. }
  1258. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1259. {
  1260. UploadLog(App()->GetCurrentLog());
  1261. }
  1262. void OBSBasic::on_actionUploadLastLog_triggered()
  1263. {
  1264. UploadLog(App()->GetLastLog());
  1265. }
  1266. void OBSBasic::logUploadRead()
  1267. {
  1268. logUploadReturnData.push_back(logUploadReply->readAll());
  1269. }
  1270. void OBSBasic::logUploadFinished()
  1271. {
  1272. ui->menuLogFiles->setEnabled(true);
  1273. if (logUploadReply->error()) {
  1274. QMessageBox::information(this,
  1275. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1276. logUploadReply->errorString());
  1277. return;
  1278. }
  1279. const char *jsonReply = logUploadReturnData.constData();
  1280. if (!jsonReply || !*jsonReply)
  1281. return;
  1282. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  1283. QString logURL = obs_data_getstring(returnData, "html_url");
  1284. obs_data_release(returnData);
  1285. OBSLogReply logDialog(this, logURL);
  1286. logDialog.exec();
  1287. }
  1288. static void RenameListItem(QListWidget *listWidget, obs_source_t source,
  1289. const string &name)
  1290. {
  1291. const char *prevName = obs_source_getname(source);
  1292. obs_source_t foundSource = obs_get_source_by_name(name.c_str());
  1293. QListWidgetItem *listItem = listWidget->currentItem();
  1294. if (foundSource || name.compare(prevName) == 0 || name.empty()) {
  1295. listItem->setText(QT_UTF8(prevName));
  1296. obs_source_release(foundSource);
  1297. } else {
  1298. listItem->setText(QT_UTF8(name.c_str()));
  1299. obs_source_setname(source, name.c_str());
  1300. }
  1301. }
  1302. void OBSBasic::SceneNameEdited(QWidget *editor,
  1303. QAbstractItemDelegate::EndEditHint endHint)
  1304. {
  1305. OBSScene scene = GetCurrentScene();
  1306. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1307. string text = QT_TO_UTF8(edit->text().trimmed());
  1308. if (!scene)
  1309. return;
  1310. obs_source_t source = obs_scene_getsource(scene);
  1311. RenameListItem(ui->scenes, source, text);
  1312. UNUSED_PARAMETER(endHint);
  1313. }
  1314. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1315. QAbstractItemDelegate::EndEditHint endHint)
  1316. {
  1317. OBSSceneItem item = GetCurrentSceneItem();
  1318. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1319. string text = QT_TO_UTF8(edit->text().trimmed());
  1320. if (!item)
  1321. return;
  1322. obs_source_t source = obs_sceneitem_getsource(item);
  1323. RenameListItem(ui->sources, source, text);
  1324. UNUSED_PARAMETER(endHint);
  1325. }
  1326. void OBSBasic::StreamingStart()
  1327. {
  1328. ui->streamButton->setText("Stop Streaming");
  1329. ui->streamButton->setEnabled(true);
  1330. }
  1331. void OBSBasic::StreamingStop(int code)
  1332. {
  1333. const char *errorMessage;
  1334. switch (code) {
  1335. case OBS_OUTPUT_BAD_PATH:
  1336. errorMessage = Str("Output.ConnectFail.BadPath");
  1337. break;
  1338. case OBS_OUTPUT_CONNECT_FAILED:
  1339. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1340. break;
  1341. case OBS_OUTPUT_INVALID_STREAM:
  1342. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1343. break;
  1344. default:
  1345. case OBS_OUTPUT_ERROR:
  1346. errorMessage = Str("Output.ConnectFail.Error");
  1347. break;
  1348. case OBS_OUTPUT_DISCONNECTED:
  1349. /* doesn't happen if output is set to reconnect. note that
  1350. * reconnects are handled in the output, not in the UI */
  1351. errorMessage = Str("Output.ConnectFail.Disconnected");
  1352. }
  1353. activeRefs--;
  1354. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1355. ui->streamButton->setEnabled(true);
  1356. if (code != OBS_OUTPUT_SUCCESS)
  1357. QMessageBox::information(this,
  1358. QTStr("Output.ConnectFail.Title"),
  1359. QT_UTF8(errorMessage));
  1360. }
  1361. void OBSBasic::RecordingStop()
  1362. {
  1363. activeRefs--;
  1364. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1365. }
  1366. void OBSBasic::SetupEncoders()
  1367. {
  1368. if (activeRefs == 0) {
  1369. obs_data_t x264Settings = obs_data_create();
  1370. obs_data_t aacSettings = obs_data_create();
  1371. int videoBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1372. "VBitrate");
  1373. int audioBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1374. "ABitrate");
  1375. obs_data_setint(x264Settings, "bitrate", videoBitrate);
  1376. obs_data_setbool(x264Settings, "cbr", true);
  1377. obs_data_setint(aacSettings, "bitrate", audioBitrate);
  1378. obs_encoder_update(x264, x264Settings);
  1379. obs_encoder_update(aac, aacSettings);
  1380. obs_data_release(x264Settings);
  1381. obs_data_release(aacSettings);
  1382. obs_encoder_set_video(x264, obs_video());
  1383. obs_encoder_set_audio(aac, obs_audio());
  1384. }
  1385. }
  1386. void OBSBasic::on_streamButton_clicked()
  1387. {
  1388. if (obs_output_active(streamOutput)) {
  1389. obs_output_stop(streamOutput);
  1390. } else {
  1391. SaveService();
  1392. SetupEncoders();
  1393. obs_output_set_video_encoder(streamOutput, x264);
  1394. obs_output_set_audio_encoder(streamOutput, aac);
  1395. obs_output_set_service(streamOutput, service);
  1396. bool reconnect = config_get_bool(basicConfig, "SimpleOutput",
  1397. "Reconnect");
  1398. int retryDelay = config_get_uint(basicConfig, "SimpleOutput",
  1399. "RetryDelay");
  1400. int maxRetries = config_get_uint(basicConfig, "SimpleOutput",
  1401. "MaxRetries");
  1402. if (!reconnect)
  1403. maxRetries = 0;
  1404. obs_output_set_reconnect_settings(streamOutput, maxRetries,
  1405. retryDelay);
  1406. if (obs_output_start(streamOutput)) {
  1407. activeRefs++;
  1408. ui->streamButton->setEnabled(false);
  1409. ui->streamButton->setText(
  1410. QTStr("Basic.Main.Connecting"));
  1411. }
  1412. }
  1413. }
  1414. void OBSBasic::on_recordButton_clicked()
  1415. {
  1416. if (obs_output_active(fileOutput)) {
  1417. obs_output_stop(fileOutput);
  1418. } else {
  1419. const char *path = config_get_string(basicConfig,
  1420. "SimpleOutput", "FilePath");
  1421. os_dir_t dir = path ? os_opendir(path) : nullptr;
  1422. if (!dir) {
  1423. QMessageBox::information(this,
  1424. QTStr("Output.BadPath.Title"),
  1425. QTStr("Output.BadPath.Text"));
  1426. return;
  1427. }
  1428. os_closedir(dir);
  1429. string strPath;
  1430. strPath += path;
  1431. char lastChar = strPath.back();
  1432. if (lastChar != '/' && lastChar != '\\')
  1433. strPath += "/";
  1434. strPath += GenerateTimeDateFilename("flv");
  1435. SetupEncoders();
  1436. obs_output_set_video_encoder(fileOutput, x264);
  1437. obs_output_set_audio_encoder(fileOutput, aac);
  1438. obs_data_t settings = obs_data_create();
  1439. obs_data_setstring(settings, "path", strPath.c_str());
  1440. obs_output_update(fileOutput, settings);
  1441. obs_data_release(settings);
  1442. if (obs_output_start(fileOutput)) {
  1443. activeRefs++;
  1444. ui->recordButton->setText(
  1445. QTStr("Basic.Main.StopRecording"));
  1446. }
  1447. }
  1448. }
  1449. void OBSBasic::on_settingsButton_clicked()
  1450. {
  1451. OBSBasicSettings settings(this);
  1452. settings.exec();
  1453. }
  1454. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1455. {
  1456. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1457. if (strcmp(val, "10") == 0) {
  1458. num = 10;
  1459. den = 1;
  1460. } else if (strcmp(val, "20") == 0) {
  1461. num = 20;
  1462. den = 1;
  1463. } else if (strcmp(val, "25") == 0) {
  1464. num = 25;
  1465. den = 1;
  1466. } else if (strcmp(val, "29.97") == 0) {
  1467. num = 30000;
  1468. den = 1001;
  1469. } else if (strcmp(val, "48") == 0) {
  1470. num = 48;
  1471. den = 1;
  1472. } else if (strcmp(val, "59.94") == 0) {
  1473. num = 60000;
  1474. den = 1001;
  1475. } else if (strcmp(val, "60") == 0) {
  1476. num = 60;
  1477. den = 1;
  1478. } else {
  1479. num = 30;
  1480. den = 1;
  1481. }
  1482. }
  1483. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1484. {
  1485. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1486. den = 1;
  1487. }
  1488. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1489. {
  1490. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1491. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1492. }
  1493. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1494. {
  1495. num = 1000000000;
  1496. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1497. }
  1498. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1499. {
  1500. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1501. if (type == 1) //"Integer"
  1502. GetFPSInteger(num, den);
  1503. else if (type == 2) //"Fraction"
  1504. GetFPSFraction(num, den);
  1505. else if (false) //"Nanoseconds", currently not implemented
  1506. GetFPSNanoseconds(num, den);
  1507. else
  1508. GetFPSCommon(num, den);
  1509. }
  1510. config_t OBSBasic::Config() const
  1511. {
  1512. return basicConfig;
  1513. }
  1514. void OBSBasic::on_actionEditTransform_triggered()
  1515. {
  1516. delete transformWindow;
  1517. transformWindow = new OBSBasicTransform(this);
  1518. transformWindow->show();
  1519. }
  1520. void OBSBasic::on_actionResetTransform_triggered()
  1521. {
  1522. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1523. {
  1524. if (!obs_sceneitem_selected(item))
  1525. return true;
  1526. obs_sceneitem_info info;
  1527. vec2_set(&info.pos, 0.0f, 0.0f);
  1528. vec2_set(&info.scale, 1.0f, 1.0f);
  1529. info.rot = 0.0f;
  1530. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1531. info.bounds_type = OBS_BOUNDS_NONE;
  1532. info.bounds_alignment = OBS_ALIGN_CENTER;
  1533. vec2_set(&info.bounds, 0.0f, 0.0f);
  1534. obs_sceneitem_set_info(item, &info);
  1535. UNUSED_PARAMETER(scene);
  1536. UNUSED_PARAMETER(param);
  1537. return true;
  1538. };
  1539. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1540. }
  1541. static void GetItemBox(obs_sceneitem_t item, vec3 &tl, vec3 &br)
  1542. {
  1543. matrix4 boxTransform;
  1544. obs_sceneitem_get_box_transform(item, &boxTransform);
  1545. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1546. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  1547. auto GetMinPos = [&] (float x, float y)
  1548. {
  1549. vec3 pos;
  1550. vec3_set(&pos, x, y, 0.0f);
  1551. vec3_transform(&pos, &pos, &boxTransform);
  1552. vec3_min(&tl, &tl, &pos);
  1553. vec3_max(&br, &br, &pos);
  1554. };
  1555. GetMinPos(0.0f, 0.0f);
  1556. GetMinPos(1.0f, 0.0f);
  1557. GetMinPos(0.0f, 1.0f);
  1558. GetMinPos(1.0f, 1.0f);
  1559. }
  1560. static vec3 GetItemTL(obs_sceneitem_t item)
  1561. {
  1562. vec3 tl, br;
  1563. GetItemBox(item, tl, br);
  1564. return tl;
  1565. }
  1566. static void SetItemTL(obs_sceneitem_t item, const vec3 &tl)
  1567. {
  1568. vec3 newTL;
  1569. vec2 pos;
  1570. obs_sceneitem_getpos(item, &pos);
  1571. newTL = GetItemTL(item);
  1572. pos.x += tl.x - newTL.x;
  1573. pos.y += tl.y - newTL.y;
  1574. obs_sceneitem_setpos(item, &pos);
  1575. }
  1576. static bool RotateSelectedSources(obs_scene_t scene, obs_sceneitem_t item,
  1577. void *param)
  1578. {
  1579. if (!obs_sceneitem_selected(item))
  1580. return true;
  1581. float rot = *reinterpret_cast<float*>(param);
  1582. vec3 tl = GetItemTL(item);
  1583. rot += obs_sceneitem_getrot(item);
  1584. if (rot >= 360.0f) rot -= 360.0f;
  1585. else if (rot <= -360.0f) rot += 360.0f;
  1586. obs_sceneitem_setrot(item, rot);
  1587. SetItemTL(item, tl);
  1588. UNUSED_PARAMETER(scene);
  1589. UNUSED_PARAMETER(param);
  1590. return true;
  1591. };
  1592. void OBSBasic::on_actionRotate90CW_triggered()
  1593. {
  1594. float f90CW = 90.0f;
  1595. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  1596. }
  1597. void OBSBasic::on_actionRotate90CCW_triggered()
  1598. {
  1599. float f90CCW = -90.0f;
  1600. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  1601. }
  1602. void OBSBasic::on_actionRotate180_triggered()
  1603. {
  1604. float f180 = 180.0f;
  1605. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  1606. }
  1607. static bool MultiplySelectedItemScale(obs_scene_t scene, obs_sceneitem_t item,
  1608. void *param)
  1609. {
  1610. vec2 &mul = *reinterpret_cast<vec2*>(param);
  1611. if (!obs_sceneitem_selected(item))
  1612. return true;
  1613. vec3 tl = GetItemTL(item);
  1614. vec2 scale;
  1615. obs_sceneitem_getscale(item, &scale);
  1616. vec2_mul(&scale, &scale, &mul);
  1617. obs_sceneitem_setscale(item, &scale);
  1618. SetItemTL(item, tl);
  1619. UNUSED_PARAMETER(scene);
  1620. return true;
  1621. }
  1622. void OBSBasic::on_actionFlipHorizontal_triggered()
  1623. {
  1624. vec2 scale;
  1625. vec2_set(&scale, -1.0f, 1.0f);
  1626. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1627. &scale);
  1628. }
  1629. void OBSBasic::on_actionFlipVertical_triggered()
  1630. {
  1631. vec2 scale;
  1632. vec2_set(&scale, 1.0f, -1.0f);
  1633. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1634. &scale);
  1635. }
  1636. static bool CenterAlignSelectedItems(obs_scene_t scene, obs_sceneitem_t item,
  1637. void *param)
  1638. {
  1639. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  1640. if (!obs_sceneitem_selected(item))
  1641. return true;
  1642. obs_video_info ovi;
  1643. obs_get_video_info(&ovi);
  1644. obs_sceneitem_info itemInfo;
  1645. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  1646. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  1647. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  1648. itemInfo.rot = 0.0f;
  1649. vec2_set(&itemInfo.bounds,
  1650. float(ovi.base_width), float(ovi.base_height));
  1651. itemInfo.bounds_type = boundsType;
  1652. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  1653. obs_sceneitem_set_info(item, &itemInfo);
  1654. UNUSED_PARAMETER(scene);
  1655. return true;
  1656. }
  1657. void OBSBasic::on_actionFitToScreen_triggered()
  1658. {
  1659. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  1660. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1661. &boundsType);
  1662. }
  1663. void OBSBasic::on_actionStretchToScreen_triggered()
  1664. {
  1665. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  1666. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1667. &boundsType);
  1668. }
  1669. void OBSBasic::on_actionCenterToScreen_triggered()
  1670. {
  1671. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1672. {
  1673. vec3 tl, br, itemCenter, screenCenter, offset;
  1674. obs_video_info ovi;
  1675. if (!obs_sceneitem_selected(item))
  1676. return true;
  1677. obs_get_video_info(&ovi);
  1678. vec3_set(&screenCenter, float(ovi.base_width),
  1679. float(ovi.base_height), 0.0f);
  1680. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  1681. GetItemBox(item, tl, br);
  1682. vec3_sub(&itemCenter, &br, &tl);
  1683. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  1684. vec3_add(&itemCenter, &itemCenter, &tl);
  1685. vec3_sub(&offset, &screenCenter, &itemCenter);
  1686. vec3_add(&tl, &tl, &offset);
  1687. SetItemTL(item, tl);
  1688. UNUSED_PARAMETER(scene);
  1689. UNUSED_PARAMETER(param);
  1690. return true;
  1691. };
  1692. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1693. }