window-basic-main.cpp 63 KB

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