window-basic-main.cpp 58 KB

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