1
0

window-basic-main.cpp 46 KB

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