window-basic-main.cpp 53 KB

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