window-basic-main.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353
  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 remove_source;
  664. remove_source.setInformativeText(text);
  665. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  666. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  667. remove_source.setIcon(QMessageBox::Question);
  668. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  669. remove_source.exec();
  670. return Yes == remove_source.clickedButton();
  671. }
  672. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  673. void OBSBasic::TimedCheckForUpdates()
  674. {
  675. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  676. "LastUpdateCheck");
  677. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  678. "LastVersion");
  679. if (lastVersion < LIBOBS_API_VER) {
  680. lastUpdate = 0;
  681. config_set_int(App()->GlobalConfig(), "General",
  682. "LastUpdateCheck", 0);
  683. }
  684. long long t = (long long)time(nullptr);
  685. long long secs = t - lastUpdate;
  686. if (secs > UPDATE_CHECK_INTERVAL)
  687. CheckForUpdates();
  688. }
  689. void OBSBasic::CheckForUpdates()
  690. {
  691. ui->actionCheckForUpdates->setEnabled(false);
  692. string versionString("obs-basic ");
  693. versionString += App()->GetVersionString();
  694. QNetworkRequest request;
  695. request.setUrl(QUrl("https://obsproject.com/obs2_update/basic.json"));
  696. request.setRawHeader("User-Agent", versionString.c_str());
  697. updateReply = networkManager.get(request);
  698. connect(updateReply, SIGNAL(finished()),
  699. this, SLOT(updateFileFinished()));
  700. connect(updateReply, SIGNAL(readyRead()),
  701. this, SLOT(updateFileRead()));
  702. }
  703. void OBSBasic::updateFileRead()
  704. {
  705. updateReturnData.push_back(updateReply->readAll());
  706. }
  707. #ifdef __APPLE__
  708. #define VERSION_ENTRY "mac"
  709. #elif _WIN32
  710. #define VERSION_ENTRY "windows"
  711. #else
  712. #define VERSION_ENTRY "other"
  713. #endif
  714. void OBSBasic::updateFileFinished()
  715. {
  716. ui->actionCheckForUpdates->setEnabled(true);
  717. if (updateReply->error()) {
  718. blog(LOG_WARNING, "Update check failed: %s",
  719. QT_TO_UTF8(updateReply->errorString()));
  720. return;
  721. }
  722. const char *jsonReply = updateReturnData.constData();
  723. if (!jsonReply || !*jsonReply)
  724. return;
  725. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  726. obs_data_t versionData = obs_data_get_obj(returnData, VERSION_ENTRY);
  727. const char *description = obs_data_get_string(returnData,
  728. "description");
  729. const char *download = obs_data_get_string(versionData, "download");
  730. if (returnData && versionData && description && download) {
  731. long major = obs_data_get_int(versionData, "major");
  732. long minor = obs_data_get_int(versionData, "minor");
  733. long patch = obs_data_get_int(versionData, "patch");
  734. long version = MAKE_SEMANTIC_VERSION(major, minor, patch);
  735. blog(LOG_INFO, "Update check: latest version is: %ld.%ld.%ld",
  736. major, minor, patch);
  737. if (version > LIBOBS_API_VER) {
  738. QString str = QTStr("UpdateAvailable.Text");
  739. QMessageBox messageBox(this);
  740. str = str.arg(QString::number(major),
  741. QString::number(minor),
  742. QString::number(patch),
  743. download);
  744. messageBox.setWindowTitle(QTStr("UpdateAvailable"));
  745. messageBox.setTextFormat(Qt::RichText);
  746. messageBox.setText(str);
  747. messageBox.setInformativeText(QT_UTF8(description));
  748. messageBox.exec();
  749. long long t = (long long)time(nullptr);
  750. config_set_int(App()->GlobalConfig(), "General",
  751. "LastUpdateCheck", t);
  752. config_save(App()->GlobalConfig());
  753. }
  754. } else {
  755. blog(LOG_WARNING, "Bad JSON file received from server");
  756. }
  757. obs_data_release(versionData);
  758. obs_data_release(returnData);
  759. }
  760. void OBSBasic::RemoveSelectedScene()
  761. {
  762. OBSScene scene = GetCurrentScene();
  763. if (scene) {
  764. obs_source_t source = obs_scene_get_source(scene);
  765. if (QueryRemoveSource(source))
  766. obs_source_remove(source);
  767. }
  768. }
  769. void OBSBasic::RemoveSelectedSceneItem()
  770. {
  771. OBSSceneItem item = GetCurrentSceneItem();
  772. if (item) {
  773. obs_source_t source = obs_sceneitem_get_source(item);
  774. if (QueryRemoveSource(source))
  775. obs_sceneitem_remove(item);
  776. }
  777. }
  778. /* OBS Callbacks */
  779. void OBSBasic::SceneItemAdded(void *data, calldata_t params)
  780. {
  781. OBSBasic *window = static_cast<OBSBasic*>(data);
  782. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  783. QMetaObject::invokeMethod(window, "AddSceneItem",
  784. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  785. }
  786. void OBSBasic::SceneItemRemoved(void *data, calldata_t params)
  787. {
  788. OBSBasic *window = static_cast<OBSBasic*>(data);
  789. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  790. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  791. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  792. }
  793. void OBSBasic::SourceAdded(void *data, calldata_t params)
  794. {
  795. OBSBasic *window = static_cast<OBSBasic*>(data);
  796. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  797. if (obs_scene_from_source(source) != NULL)
  798. QMetaObject::invokeMethod(window,
  799. "AddScene",
  800. Q_ARG(OBSSource, OBSSource(source)));
  801. }
  802. void OBSBasic::SourceRemoved(void *data, calldata_t params)
  803. {
  804. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  805. if (obs_scene_from_source(source) != NULL)
  806. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  807. "RemoveScene",
  808. Q_ARG(OBSSource, OBSSource(source)));
  809. }
  810. void OBSBasic::SourceActivated(void *data, calldata_t params)
  811. {
  812. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  813. uint32_t flags = obs_source_get_output_flags(source);
  814. if (flags & OBS_SOURCE_AUDIO)
  815. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  816. "ActivateAudioSource",
  817. Q_ARG(OBSSource, OBSSource(source)));
  818. }
  819. void OBSBasic::SourceDeactivated(void *data, calldata_t params)
  820. {
  821. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  822. uint32_t flags = obs_source_get_output_flags(source);
  823. if (flags & OBS_SOURCE_AUDIO)
  824. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  825. "DeactivateAudioSource",
  826. Q_ARG(OBSSource, OBSSource(source)));
  827. }
  828. void OBSBasic::SourceRenamed(void *data, calldata_t params)
  829. {
  830. const char *newName = calldata_string(params, "new_name");
  831. const char *prevName = calldata_string(params, "prev_name");
  832. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  833. "RenameSources",
  834. Q_ARG(QString, QT_UTF8(newName)),
  835. Q_ARG(QString, QT_UTF8(prevName)));
  836. }
  837. void OBSBasic::ChannelChanged(void *data, calldata_t params)
  838. {
  839. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  840. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  841. if (channel == 0)
  842. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  843. "UpdateSceneSelection",
  844. Q_ARG(OBSSource, OBSSource(source)));
  845. }
  846. void OBSBasic::DrawBackdrop(float cx, float cy)
  847. {
  848. if (!box)
  849. return;
  850. gs_effect_t solid = obs_get_solid_effect();
  851. gs_eparam_t color = gs_effect_get_param_by_name(solid, "color");
  852. gs_technique_t tech = gs_effect_get_technique(solid, "Solid");
  853. vec4 colorVal;
  854. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  855. gs_effect_set_vec4(color, &colorVal);
  856. gs_technique_begin(tech);
  857. gs_technique_begin_pass(tech, 0);
  858. gs_matrix_push();
  859. gs_matrix_identity();
  860. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  861. gs_load_vertexbuffer(box);
  862. gs_draw(GS_TRISTRIP, 0, 0);
  863. gs_matrix_pop();
  864. gs_technique_end_pass(tech);
  865. gs_technique_end(tech);
  866. gs_load_vertexbuffer(nullptr);
  867. }
  868. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  869. {
  870. OBSBasic *window = static_cast<OBSBasic*>(data);
  871. obs_video_info ovi;
  872. obs_get_video_info(&ovi);
  873. window->previewCX = int(window->previewScale * float(ovi.base_width));
  874. window->previewCY = int(window->previewScale * float(ovi.base_height));
  875. gs_viewport_push();
  876. gs_projection_push();
  877. /* --------------------------------------- */
  878. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  879. -100.0f, 100.0f);
  880. gs_set_viewport(window->previewX, window->previewY,
  881. window->previewCX, window->previewCY);
  882. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  883. obs_render_main_view();
  884. gs_load_vertexbuffer(nullptr);
  885. /* --------------------------------------- */
  886. QSize previewSize = GetPixelSize(window->ui->preview);
  887. float right = float(previewSize.width()) - window->previewX;
  888. float bottom = float(previewSize.height()) - window->previewY;
  889. gs_ortho(-window->previewX, right,
  890. -window->previewY, bottom,
  891. -100.0f, 100.0f);
  892. gs_reset_viewport();
  893. window->ui->preview->DrawSceneEditing();
  894. /* --------------------------------------- */
  895. gs_projection_pop();
  896. gs_viewport_pop();
  897. UNUSED_PARAMETER(cx);
  898. UNUSED_PARAMETER(cy);
  899. }
  900. void OBSBasic::SceneItemMoveUp(void *data, calldata_t params)
  901. {
  902. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  903. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  904. "MoveSceneItem",
  905. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  906. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_UP));
  907. }
  908. void OBSBasic::SceneItemMoveDown(void *data, calldata_t params)
  909. {
  910. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  911. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  912. "MoveSceneItem",
  913. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  914. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_DOWN));
  915. }
  916. void OBSBasic::SceneItemMoveTop(void *data, calldata_t params)
  917. {
  918. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  919. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  920. "MoveSceneItem",
  921. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  922. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_TOP));
  923. }
  924. void OBSBasic::SceneItemMoveBottom(void *data, calldata_t params)
  925. {
  926. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  927. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  928. "MoveSceneItem",
  929. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  930. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_BOTTOM));
  931. }
  932. /* Main class functions */
  933. obs_service_t OBSBasic::GetService()
  934. {
  935. if (!service)
  936. service = obs_service_create("rtmp_common", NULL, NULL);
  937. return service;
  938. }
  939. void OBSBasic::SetService(obs_service_t newService)
  940. {
  941. if (newService) {
  942. if (service)
  943. obs_service_destroy(service);
  944. service = newService;
  945. }
  946. }
  947. #ifdef _WIN32
  948. #define IS_WIN32 1
  949. #else
  950. #define IS_WIN32 0
  951. #endif
  952. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  953. {
  954. int ret = obs_reset_video(ovi);
  955. if (ret == OBS_VIDEO_INVALID_PARAM) {
  956. struct obs_video_info new_params = *ovi;
  957. if (new_params.window_width == 0)
  958. new_params.window_width = 512;
  959. if (new_params.window_height == 0)
  960. new_params.window_height = 512;
  961. new_params.output_width = new_params.window_width;
  962. new_params.output_height = new_params.window_height;
  963. new_params.base_width = new_params.window_width;
  964. new_params.base_height = new_params.window_height;
  965. ret = obs_reset_video(&new_params);
  966. }
  967. return ret;
  968. }
  969. int OBSBasic::ResetVideo()
  970. {
  971. struct obs_video_info ovi;
  972. int ret;
  973. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  974. ovi.graphics_module = App()->GetRenderModule();
  975. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  976. "Video", "BaseCX");
  977. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  978. "Video", "BaseCY");
  979. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  980. "Video", "OutputCX");
  981. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  982. "Video", "OutputCY");
  983. ovi.output_format = VIDEO_FORMAT_NV12;
  984. ovi.adapter = 0;
  985. ovi.gpu_conversion = true;
  986. QTToGSWindow(ui->preview->winId(), ovi.window);
  987. //required to make opengl display stuff on osx(?)
  988. ResizePreview(ovi.base_width, ovi.base_height);
  989. QSize size = GetPixelSize(ui->preview);
  990. ovi.window_width = size.width();
  991. ovi.window_height = size.height();
  992. ret = AttemptToResetVideo(&ovi);
  993. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  994. /* Try OpenGL if DirectX fails on windows */
  995. if (astrcmpi(ovi.graphics_module, "libobs-opengl") != 0) {
  996. ovi.graphics_module = "libobs-opengl";
  997. ret = AttemptToResetVideo(&ovi);
  998. }
  999. }
  1000. if (ret == OBS_VIDEO_SUCCESS)
  1001. obs_add_draw_callback(OBSBasic::RenderMain, this);
  1002. return ret;
  1003. }
  1004. bool OBSBasic::ResetAudio()
  1005. {
  1006. struct audio_output_info ai;
  1007. ai.name = "Main Audio Track";
  1008. ai.format = AUDIO_FORMAT_FLOAT;
  1009. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  1010. "SampleRate");
  1011. const char *channelSetupStr = config_get_string(basicConfig,
  1012. "Audio", "ChannelSetup");
  1013. if (strcmp(channelSetupStr, "Mono") == 0)
  1014. ai.speakers = SPEAKERS_MONO;
  1015. else
  1016. ai.speakers = SPEAKERS_STEREO;
  1017. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  1018. return obs_reset_audio(&ai);
  1019. }
  1020. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  1021. const char *deviceDesc, int channel)
  1022. {
  1023. const char *deviceId = config_get_string(basicConfig, "Audio",
  1024. deviceName);
  1025. obs_source_t source;
  1026. obs_data_t settings;
  1027. bool same = false;
  1028. source = obs_get_output_source(channel);
  1029. if (source) {
  1030. settings = obs_source_get_settings(source);
  1031. const char *curId = obs_data_get_string(settings, "device_id");
  1032. same = (strcmp(curId, deviceId) == 0);
  1033. obs_data_release(settings);
  1034. obs_source_release(source);
  1035. }
  1036. if (!same)
  1037. obs_set_output_source(channel, nullptr);
  1038. if (!same && strcmp(deviceId, "disabled") != 0) {
  1039. obs_data_t settings = obs_data_create();
  1040. obs_data_set_string(settings, "device_id", deviceId);
  1041. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  1042. sourceId, deviceDesc, settings);
  1043. obs_data_release(settings);
  1044. obs_set_output_source(channel, source);
  1045. obs_source_release(source);
  1046. }
  1047. }
  1048. void OBSBasic::ResetAudioDevices()
  1049. {
  1050. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  1051. Str("Basic.DesktopDevice1"), 1);
  1052. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  1053. Str("Basic.DesktopDevice2"), 2);
  1054. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  1055. Str("Basic.AuxDevice1"), 3);
  1056. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  1057. Str("Basic.AuxDevice2"), 4);
  1058. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  1059. Str("Basic.AuxDevice3"), 5);
  1060. }
  1061. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  1062. {
  1063. QSize targetSize;
  1064. /* resize preview panel to fix to the top section of the window */
  1065. targetSize = GetPixelSize(ui->preview);
  1066. GetScaleAndCenterPos(int(cx), int(cy),
  1067. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  1068. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  1069. previewX, previewY, previewScale);
  1070. previewX += float(PREVIEW_EDGE_SIZE);
  1071. previewY += float(PREVIEW_EDGE_SIZE);
  1072. if (isVisible()) {
  1073. if (resizeTimer)
  1074. killTimer(resizeTimer);
  1075. resizeTimer = startTimer(100);
  1076. }
  1077. }
  1078. void OBSBasic::closeEvent(QCloseEvent *event)
  1079. {
  1080. QWidget::closeEvent(event);
  1081. if (!event->isAccepted())
  1082. return;
  1083. // remove draw callback in case our drawable surfaces go away before
  1084. // the destructor gets called
  1085. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  1086. }
  1087. void OBSBasic::changeEvent(QEvent *event)
  1088. {
  1089. /* TODO */
  1090. UNUSED_PARAMETER(event);
  1091. }
  1092. void OBSBasic::resizeEvent(QResizeEvent *event)
  1093. {
  1094. struct obs_video_info ovi;
  1095. if (obs_get_video_info(&ovi))
  1096. ResizePreview(ovi.base_width, ovi.base_height);
  1097. UNUSED_PARAMETER(event);
  1098. }
  1099. void OBSBasic::timerEvent(QTimerEvent *event)
  1100. {
  1101. if (event->timerId() == resizeTimer) {
  1102. killTimer(resizeTimer);
  1103. resizeTimer = 0;
  1104. QSize size = GetPixelSize(ui->preview);
  1105. obs_resize(size.width(), size.height());
  1106. }
  1107. }
  1108. void OBSBasic::on_action_New_triggered()
  1109. {
  1110. /* TODO */
  1111. }
  1112. void OBSBasic::on_action_Open_triggered()
  1113. {
  1114. /* TODO */
  1115. }
  1116. void OBSBasic::on_action_Save_triggered()
  1117. {
  1118. /* TODO */
  1119. }
  1120. void OBSBasic::on_action_Settings_triggered()
  1121. {
  1122. OBSBasicSettings settings(this);
  1123. settings.exec();
  1124. }
  1125. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  1126. QListWidgetItem *prev)
  1127. {
  1128. obs_source_t source = NULL;
  1129. if (sceneChanging)
  1130. return;
  1131. if (current) {
  1132. obs_scene_t scene;
  1133. scene = current->data(Qt::UserRole).value<OBSScene>();
  1134. source = obs_scene_get_source(scene);
  1135. }
  1136. /* TODO: allow transitions */
  1137. obs_set_output_source(0, source);
  1138. UNUSED_PARAMETER(prev);
  1139. }
  1140. void OBSBasic::EditSceneName()
  1141. {
  1142. ui->scenes->editItem(ui->scenes->currentItem());
  1143. }
  1144. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  1145. {
  1146. QListWidgetItem *item = ui->scenes->itemAt(pos);
  1147. QMenu popup;
  1148. popup.addAction(QTStr("Add"),
  1149. this, SLOT(on_actionAddScene_triggered()));
  1150. if (item)
  1151. popup.addAction(QTStr("Remove"),
  1152. this, SLOT(RemoveSelectedScene()));
  1153. popup.exec(QCursor::pos());
  1154. }
  1155. void OBSBasic::on_actionAddScene_triggered()
  1156. {
  1157. string name;
  1158. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1159. int i = 1;
  1160. QString placeHolderText = format.arg(i);
  1161. obs_source_t source = nullptr;
  1162. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1163. obs_source_release(source);
  1164. placeHolderText = format.arg(++i);
  1165. }
  1166. bool accepted = NameDialog::AskForName(this,
  1167. QTStr("Basic.Main.AddSceneDlg.Title"),
  1168. QTStr("Basic.Main.AddSceneDlg.Text"),
  1169. name,
  1170. placeHolderText);
  1171. if (accepted) {
  1172. if (name.empty()) {
  1173. QMessageBox::information(this,
  1174. QTStr("NoNameEntered.Title"),
  1175. QTStr("NoNameEntered.Text"));
  1176. on_actionAddScene_triggered();
  1177. return;
  1178. }
  1179. obs_source_t source = obs_get_source_by_name(name.c_str());
  1180. if (source) {
  1181. QMessageBox::information(this,
  1182. QTStr("NameExists.Title"),
  1183. QTStr("NameExists.Text"));
  1184. obs_source_release(source);
  1185. on_actionAddScene_triggered();
  1186. return;
  1187. }
  1188. obs_scene_t scene = obs_scene_create(name.c_str());
  1189. source = obs_scene_get_source(scene);
  1190. obs_add_source(source);
  1191. obs_scene_release(scene);
  1192. obs_set_output_source(0, source);
  1193. }
  1194. }
  1195. void OBSBasic::on_actionRemoveScene_triggered()
  1196. {
  1197. OBSScene scene = GetCurrentScene();
  1198. obs_source_t source = obs_scene_get_source(scene);
  1199. if (source && QueryRemoveSource(source))
  1200. obs_source_remove(source);
  1201. }
  1202. void OBSBasic::on_actionSceneProperties_triggered()
  1203. {
  1204. /* TODO */
  1205. }
  1206. void OBSBasic::on_actionSceneUp_triggered()
  1207. {
  1208. /* TODO */
  1209. }
  1210. void OBSBasic::on_actionSceneDown_triggered()
  1211. {
  1212. /* TODO */
  1213. }
  1214. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1215. QListWidgetItem *prev)
  1216. {
  1217. auto select_one = [] (obs_scene_t scene, obs_sceneitem_t item,
  1218. void *param)
  1219. {
  1220. obs_sceneitem_t selectedItem =
  1221. *reinterpret_cast<OBSSceneItem*>(param);
  1222. obs_sceneitem_select(item, (selectedItem == item));
  1223. UNUSED_PARAMETER(scene);
  1224. return true;
  1225. };
  1226. if (!current)
  1227. return;
  1228. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1229. obs_source_t source = obs_sceneitem_get_source(item);
  1230. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1231. return;
  1232. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1233. UNUSED_PARAMETER(prev);
  1234. }
  1235. void OBSBasic::EditSceneItemName()
  1236. {
  1237. ui->sources->editItem(ui->sources->currentItem());
  1238. }
  1239. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1240. {
  1241. QListWidgetItem *item = ui->sources->itemAt(pos);
  1242. QMenu popup;
  1243. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1244. if (addSourceMenu)
  1245. popup.addMenu(addSourceMenu);
  1246. if (item) {
  1247. if (addSourceMenu)
  1248. popup.addSeparator();
  1249. popup.addAction(QTStr("Rename"), this,
  1250. SLOT(EditSceneItemName()));
  1251. popup.addAction(QTStr("Remove"), this,
  1252. SLOT(on_actionRemoveSource_triggered()),
  1253. QKeySequence::Delete);
  1254. popup.addSeparator();
  1255. popup.addMenu(ui->orderMenu);
  1256. popup.addMenu(ui->transformMenu);
  1257. popup.addSeparator();
  1258. popup.addAction(QTStr("Properties"), this,
  1259. SLOT(on_actionSourceProperties_triggered()));
  1260. }
  1261. popup.exec(QCursor::pos());
  1262. }
  1263. void OBSBasic::AddSource(const char *id)
  1264. {
  1265. if (id && *id) {
  1266. OBSBasicSourceSelect sourceSelect(this, id);
  1267. sourceSelect.exec();
  1268. }
  1269. }
  1270. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1271. {
  1272. const char *type;
  1273. bool foundValues = false;
  1274. size_t idx = 0;
  1275. QMenu *popup = new QMenu(QTStr("Add"));
  1276. while (obs_enum_input_types(idx++, &type)) {
  1277. const char *name = obs_source_get_display_name(
  1278. OBS_SOURCE_TYPE_INPUT, type);
  1279. if (strcmp(type, "scene") == 0)
  1280. continue;
  1281. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1282. popupItem->setData(QT_UTF8(type));
  1283. connect(popupItem, SIGNAL(triggered(bool)),
  1284. this, SLOT(AddSourceFromAction()));
  1285. popup->addAction(popupItem);
  1286. foundValues = true;
  1287. }
  1288. if (!foundValues) {
  1289. delete popup;
  1290. popup = nullptr;
  1291. }
  1292. return popup;
  1293. }
  1294. void OBSBasic::AddSourceFromAction()
  1295. {
  1296. QAction *action = qobject_cast<QAction*>(sender());
  1297. if (!action)
  1298. return;
  1299. AddSource(QT_TO_UTF8(action->data().toString()));
  1300. }
  1301. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1302. {
  1303. if (!GetCurrentScene()) {
  1304. // Tell the user he needs a scene first (help beginners).
  1305. QMessageBox::information(this,
  1306. QTStr("Basic.Main.AddSourceHelp.Title"),
  1307. QTStr("Basic.Main.AddSourceHelp.Text"));
  1308. return;
  1309. }
  1310. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1311. if (popup)
  1312. popup->exec(pos);
  1313. }
  1314. void OBSBasic::on_actionAddSource_triggered()
  1315. {
  1316. AddSourcePopupMenu(QCursor::pos());
  1317. }
  1318. void OBSBasic::on_actionRemoveSource_triggered()
  1319. {
  1320. OBSSceneItem item = GetCurrentSceneItem();
  1321. obs_source_t source = obs_sceneitem_get_source(item);
  1322. if (source && QueryRemoveSource(source))
  1323. obs_sceneitem_remove(item);
  1324. }
  1325. void OBSBasic::on_actionSourceProperties_triggered()
  1326. {
  1327. OBSSceneItem item = GetCurrentSceneItem();
  1328. OBSSource source = obs_sceneitem_get_source(item);
  1329. if (source)
  1330. CreatePropertiesWindow(source);
  1331. }
  1332. void OBSBasic::on_actionSourceUp_triggered()
  1333. {
  1334. OBSSceneItem item = GetCurrentSceneItem();
  1335. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1336. }
  1337. void OBSBasic::on_actionSourceDown_triggered()
  1338. {
  1339. OBSSceneItem item = GetCurrentSceneItem();
  1340. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1341. }
  1342. void OBSBasic::on_actionMoveUp_triggered()
  1343. {
  1344. OBSSceneItem item = GetCurrentSceneItem();
  1345. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1346. }
  1347. void OBSBasic::on_actionMoveDown_triggered()
  1348. {
  1349. OBSSceneItem item = GetCurrentSceneItem();
  1350. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1351. }
  1352. void OBSBasic::on_actionMoveToTop_triggered()
  1353. {
  1354. OBSSceneItem item = GetCurrentSceneItem();
  1355. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  1356. }
  1357. void OBSBasic::on_actionMoveToBottom_triggered()
  1358. {
  1359. OBSSceneItem item = GetCurrentSceneItem();
  1360. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  1361. }
  1362. static char *ReadLogFile(const char *log)
  1363. {
  1364. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  1365. string path = (char*)logDir;
  1366. path += "/";
  1367. path += log;
  1368. char *file = os_quick_read_utf8_file(path.c_str());
  1369. if (!file)
  1370. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1371. return file;
  1372. }
  1373. void OBSBasic::UploadLog(const char *file)
  1374. {
  1375. dstr fileString = {};
  1376. stringstream ss;
  1377. string jsonData;
  1378. dstr_move_array(&fileString, ReadLogFile(file));
  1379. if (!fileString.array)
  1380. return;
  1381. if (!*fileString.array) {
  1382. dstr_free(&fileString);
  1383. return;
  1384. }
  1385. ui->menuLogFiles->setEnabled(false);
  1386. dstr_replace(&fileString, "\\", "\\\\");
  1387. dstr_replace(&fileString, "\"", "\\\"");
  1388. dstr_replace(&fileString, "\n", "\\n");
  1389. dstr_replace(&fileString, "\r", "\\r");
  1390. dstr_replace(&fileString, "\t", "\\t");
  1391. dstr_replace(&fileString, "\t", "\\t");
  1392. dstr_replace(&fileString, "/", "\\/");
  1393. ss << "{ \"public\": false, \"description\": \"OBS " <<
  1394. App()->GetVersionString() << " log file uploaded at " <<
  1395. CurrentDateTimeString() << "\", \"files\": { \"" <<
  1396. file << "\": { \"content\": \"" <<
  1397. fileString.array << "\" } } }";
  1398. jsonData = std::move(ss.str());
  1399. logUploadPostData.setData(jsonData.c_str(), (int)jsonData.size());
  1400. QUrl url("https://api.github.com/gists");
  1401. logUploadReply = networkManager.post(QNetworkRequest(url),
  1402. &logUploadPostData);
  1403. connect(logUploadReply, SIGNAL(finished()),
  1404. this, SLOT(logUploadFinished()));
  1405. connect(logUploadReply, SIGNAL(readyRead()),
  1406. this, SLOT(logUploadRead()));
  1407. dstr_free(&fileString);
  1408. }
  1409. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1410. {
  1411. UploadLog(App()->GetCurrentLog());
  1412. }
  1413. void OBSBasic::on_actionUploadLastLog_triggered()
  1414. {
  1415. UploadLog(App()->GetLastLog());
  1416. }
  1417. void OBSBasic::on_actionCheckForUpdates_triggered()
  1418. {
  1419. CheckForUpdates();
  1420. }
  1421. void OBSBasic::logUploadRead()
  1422. {
  1423. logUploadReturnData.push_back(logUploadReply->readAll());
  1424. }
  1425. void OBSBasic::logUploadFinished()
  1426. {
  1427. ui->menuLogFiles->setEnabled(true);
  1428. if (logUploadReply->error()) {
  1429. QMessageBox::information(this,
  1430. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1431. logUploadReply->errorString());
  1432. return;
  1433. }
  1434. const char *jsonReply = logUploadReturnData.constData();
  1435. if (!jsonReply || !*jsonReply)
  1436. return;
  1437. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  1438. QString logURL = obs_data_get_string(returnData, "html_url");
  1439. obs_data_release(returnData);
  1440. OBSLogReply logDialog(this, logURL);
  1441. logDialog.exec();
  1442. }
  1443. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget, obs_source_t source,
  1444. const string &name)
  1445. {
  1446. const char *prevName = obs_source_get_name(source);
  1447. obs_source_t foundSource = obs_get_source_by_name(name.c_str());
  1448. QListWidgetItem *listItem = listWidget->currentItem();
  1449. if (foundSource || name.compare(prevName) == 0 || name.empty()) {
  1450. listItem->setText(QT_UTF8(prevName));
  1451. if (foundSource || name.compare(prevName) == 0) {
  1452. QMessageBox::information(parent,
  1453. QTStr("NameExists.Title"),
  1454. QTStr("NameExists.Text"));
  1455. } else if (name.empty()) {
  1456. QMessageBox::information(parent,
  1457. QTStr("NoNameEntered.Title"),
  1458. QTStr("NoNameEntered.Text"));
  1459. }
  1460. obs_source_release(foundSource);
  1461. } else {
  1462. listItem->setText(QT_UTF8(name.c_str()));
  1463. obs_source_set_name(source, name.c_str());
  1464. }
  1465. }
  1466. void OBSBasic::SceneNameEdited(QWidget *editor,
  1467. QAbstractItemDelegate::EndEditHint endHint)
  1468. {
  1469. OBSScene scene = GetCurrentScene();
  1470. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1471. string text = QT_TO_UTF8(edit->text().trimmed());
  1472. if (!scene)
  1473. return;
  1474. obs_source_t source = obs_scene_get_source(scene);
  1475. RenameListItem(this, ui->scenes, source, text);
  1476. UNUSED_PARAMETER(endHint);
  1477. }
  1478. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1479. QAbstractItemDelegate::EndEditHint endHint)
  1480. {
  1481. OBSSceneItem item = GetCurrentSceneItem();
  1482. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1483. string text = QT_TO_UTF8(edit->text().trimmed());
  1484. if (!item)
  1485. return;
  1486. obs_source_t source = obs_sceneitem_get_source(item);
  1487. RenameListItem(this, ui->sources, source, text);
  1488. UNUSED_PARAMETER(endHint);
  1489. }
  1490. void OBSBasic::StreamingStart()
  1491. {
  1492. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  1493. ui->streamButton->setEnabled(true);
  1494. ui->statusbar->StreamStarted(streamOutput);
  1495. }
  1496. void OBSBasic::StreamingStop(int code)
  1497. {
  1498. const char *errorMessage;
  1499. switch (code) {
  1500. case OBS_OUTPUT_BAD_PATH:
  1501. errorMessage = Str("Output.ConnectFail.BadPath");
  1502. break;
  1503. case OBS_OUTPUT_CONNECT_FAILED:
  1504. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1505. break;
  1506. case OBS_OUTPUT_INVALID_STREAM:
  1507. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1508. break;
  1509. default:
  1510. case OBS_OUTPUT_ERROR:
  1511. errorMessage = Str("Output.ConnectFail.Error");
  1512. break;
  1513. case OBS_OUTPUT_DISCONNECTED:
  1514. /* doesn't happen if output is set to reconnect. note that
  1515. * reconnects are handled in the output, not in the UI */
  1516. errorMessage = Str("Output.ConnectFail.Disconnected");
  1517. }
  1518. activeRefs--;
  1519. ui->statusbar->StreamStopped();
  1520. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1521. ui->streamButton->setEnabled(true);
  1522. if (code != OBS_OUTPUT_SUCCESS)
  1523. QMessageBox::information(this,
  1524. QTStr("Output.ConnectFail.Title"),
  1525. QT_UTF8(errorMessage));
  1526. }
  1527. void OBSBasic::RecordingStop()
  1528. {
  1529. activeRefs--;
  1530. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1531. }
  1532. void OBSBasic::SetupEncoders()
  1533. {
  1534. if (activeRefs == 0) {
  1535. obs_data_t x264Settings = obs_data_create();
  1536. obs_data_t aacSettings = obs_data_create();
  1537. int videoBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1538. "VBitrate");
  1539. int audioBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1540. "ABitrate");
  1541. obs_data_set_int(x264Settings, "bitrate", videoBitrate);
  1542. obs_data_set_int(x264Settings, "buffer_size", videoBitrate);
  1543. obs_data_set_bool(x264Settings, "cbr", true);
  1544. obs_data_set_int(aacSettings, "bitrate", audioBitrate);
  1545. obs_encoder_update(x264, x264Settings);
  1546. obs_encoder_update(aac, aacSettings);
  1547. obs_data_release(x264Settings);
  1548. obs_data_release(aacSettings);
  1549. obs_encoder_set_video(x264, obs_get_video());
  1550. obs_encoder_set_audio(aac, obs_get_audio());
  1551. }
  1552. }
  1553. void OBSBasic::on_streamButton_clicked()
  1554. {
  1555. if (obs_output_active(streamOutput)) {
  1556. obs_output_stop(streamOutput);
  1557. } else {
  1558. SaveService();
  1559. SetupEncoders();
  1560. obs_output_set_video_encoder(streamOutput, x264);
  1561. obs_output_set_audio_encoder(streamOutput, aac);
  1562. obs_output_set_service(streamOutput, service);
  1563. bool reconnect = config_get_bool(basicConfig, "SimpleOutput",
  1564. "Reconnect");
  1565. int retryDelay = config_get_uint(basicConfig, "SimpleOutput",
  1566. "RetryDelay");
  1567. int maxRetries = config_get_uint(basicConfig, "SimpleOutput",
  1568. "MaxRetries");
  1569. if (!reconnect)
  1570. maxRetries = 0;
  1571. obs_output_set_reconnect_settings(streamOutput, maxRetries,
  1572. retryDelay);
  1573. if (obs_output_start(streamOutput)) {
  1574. activeRefs++;
  1575. ui->streamButton->setEnabled(false);
  1576. ui->streamButton->setText(
  1577. QTStr("Basic.Main.Connecting"));
  1578. }
  1579. }
  1580. }
  1581. void OBSBasic::on_recordButton_clicked()
  1582. {
  1583. if (obs_output_active(fileOutput)) {
  1584. obs_output_stop(fileOutput);
  1585. } else {
  1586. const char *path = config_get_string(basicConfig,
  1587. "SimpleOutput", "FilePath");
  1588. os_dir_t dir = path ? os_opendir(path) : nullptr;
  1589. if (!dir) {
  1590. QMessageBox::information(this,
  1591. QTStr("Output.BadPath.Title"),
  1592. QTStr("Output.BadPath.Text"));
  1593. return;
  1594. }
  1595. os_closedir(dir);
  1596. string strPath;
  1597. strPath += path;
  1598. char lastChar = strPath.back();
  1599. if (lastChar != '/' && lastChar != '\\')
  1600. strPath += "/";
  1601. strPath += GenerateTimeDateFilename("flv");
  1602. SetupEncoders();
  1603. obs_output_set_video_encoder(fileOutput, x264);
  1604. obs_output_set_audio_encoder(fileOutput, aac);
  1605. obs_data_t settings = obs_data_create();
  1606. obs_data_set_string(settings, "path", strPath.c_str());
  1607. obs_output_update(fileOutput, settings);
  1608. obs_data_release(settings);
  1609. if (obs_output_start(fileOutput)) {
  1610. activeRefs++;
  1611. ui->recordButton->setText(
  1612. QTStr("Basic.Main.StopRecording"));
  1613. }
  1614. }
  1615. }
  1616. void OBSBasic::on_settingsButton_clicked()
  1617. {
  1618. OBSBasicSettings settings(this);
  1619. settings.exec();
  1620. }
  1621. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1622. {
  1623. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1624. if (strcmp(val, "10") == 0) {
  1625. num = 10;
  1626. den = 1;
  1627. } else if (strcmp(val, "20") == 0) {
  1628. num = 20;
  1629. den = 1;
  1630. } else if (strcmp(val, "25") == 0) {
  1631. num = 25;
  1632. den = 1;
  1633. } else if (strcmp(val, "29.97") == 0) {
  1634. num = 30000;
  1635. den = 1001;
  1636. } else if (strcmp(val, "48") == 0) {
  1637. num = 48;
  1638. den = 1;
  1639. } else if (strcmp(val, "59.94") == 0) {
  1640. num = 60000;
  1641. den = 1001;
  1642. } else if (strcmp(val, "60") == 0) {
  1643. num = 60;
  1644. den = 1;
  1645. } else {
  1646. num = 30;
  1647. den = 1;
  1648. }
  1649. }
  1650. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1651. {
  1652. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1653. den = 1;
  1654. }
  1655. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1656. {
  1657. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1658. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1659. }
  1660. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1661. {
  1662. num = 1000000000;
  1663. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1664. }
  1665. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1666. {
  1667. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1668. if (type == 1) //"Integer"
  1669. GetFPSInteger(num, den);
  1670. else if (type == 2) //"Fraction"
  1671. GetFPSFraction(num, den);
  1672. else if (false) //"Nanoseconds", currently not implemented
  1673. GetFPSNanoseconds(num, den);
  1674. else
  1675. GetFPSCommon(num, den);
  1676. }
  1677. config_t OBSBasic::Config() const
  1678. {
  1679. return basicConfig;
  1680. }
  1681. void OBSBasic::on_actionEditTransform_triggered()
  1682. {
  1683. if (transformWindow)
  1684. transformWindow->close();
  1685. transformWindow = new OBSBasicTransform(this);
  1686. transformWindow->show();
  1687. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1688. }
  1689. void OBSBasic::on_actionResetTransform_triggered()
  1690. {
  1691. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1692. {
  1693. if (!obs_sceneitem_selected(item))
  1694. return true;
  1695. obs_transform_info info;
  1696. vec2_set(&info.pos, 0.0f, 0.0f);
  1697. vec2_set(&info.scale, 1.0f, 1.0f);
  1698. info.rot = 0.0f;
  1699. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1700. info.bounds_type = OBS_BOUNDS_NONE;
  1701. info.bounds_alignment = OBS_ALIGN_CENTER;
  1702. vec2_set(&info.bounds, 0.0f, 0.0f);
  1703. obs_sceneitem_set_info(item, &info);
  1704. UNUSED_PARAMETER(scene);
  1705. UNUSED_PARAMETER(param);
  1706. return true;
  1707. };
  1708. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1709. }
  1710. static void GetItemBox(obs_sceneitem_t item, vec3 &tl, vec3 &br)
  1711. {
  1712. matrix4 boxTransform;
  1713. obs_sceneitem_get_box_transform(item, &boxTransform);
  1714. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1715. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  1716. auto GetMinPos = [&] (float x, float y)
  1717. {
  1718. vec3 pos;
  1719. vec3_set(&pos, x, y, 0.0f);
  1720. vec3_transform(&pos, &pos, &boxTransform);
  1721. vec3_min(&tl, &tl, &pos);
  1722. vec3_max(&br, &br, &pos);
  1723. };
  1724. GetMinPos(0.0f, 0.0f);
  1725. GetMinPos(1.0f, 0.0f);
  1726. GetMinPos(0.0f, 1.0f);
  1727. GetMinPos(1.0f, 1.0f);
  1728. }
  1729. static vec3 GetItemTL(obs_sceneitem_t item)
  1730. {
  1731. vec3 tl, br;
  1732. GetItemBox(item, tl, br);
  1733. return tl;
  1734. }
  1735. static void SetItemTL(obs_sceneitem_t item, const vec3 &tl)
  1736. {
  1737. vec3 newTL;
  1738. vec2 pos;
  1739. obs_sceneitem_get_pos(item, &pos);
  1740. newTL = GetItemTL(item);
  1741. pos.x += tl.x - newTL.x;
  1742. pos.y += tl.y - newTL.y;
  1743. obs_sceneitem_set_pos(item, &pos);
  1744. }
  1745. static bool RotateSelectedSources(obs_scene_t scene, obs_sceneitem_t item,
  1746. void *param)
  1747. {
  1748. if (!obs_sceneitem_selected(item))
  1749. return true;
  1750. float rot = *reinterpret_cast<float*>(param);
  1751. vec3 tl = GetItemTL(item);
  1752. rot += obs_sceneitem_get_rot(item);
  1753. if (rot >= 360.0f) rot -= 360.0f;
  1754. else if (rot <= -360.0f) rot += 360.0f;
  1755. obs_sceneitem_set_rot(item, rot);
  1756. SetItemTL(item, tl);
  1757. UNUSED_PARAMETER(scene);
  1758. UNUSED_PARAMETER(param);
  1759. return true;
  1760. };
  1761. void OBSBasic::on_actionRotate90CW_triggered()
  1762. {
  1763. float f90CW = 90.0f;
  1764. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  1765. }
  1766. void OBSBasic::on_actionRotate90CCW_triggered()
  1767. {
  1768. float f90CCW = -90.0f;
  1769. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  1770. }
  1771. void OBSBasic::on_actionRotate180_triggered()
  1772. {
  1773. float f180 = 180.0f;
  1774. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  1775. }
  1776. static bool MultiplySelectedItemScale(obs_scene_t scene, obs_sceneitem_t item,
  1777. void *param)
  1778. {
  1779. vec2 &mul = *reinterpret_cast<vec2*>(param);
  1780. if (!obs_sceneitem_selected(item))
  1781. return true;
  1782. vec3 tl = GetItemTL(item);
  1783. vec2 scale;
  1784. obs_sceneitem_get_scale(item, &scale);
  1785. vec2_mul(&scale, &scale, &mul);
  1786. obs_sceneitem_set_scale(item, &scale);
  1787. SetItemTL(item, tl);
  1788. UNUSED_PARAMETER(scene);
  1789. return true;
  1790. }
  1791. void OBSBasic::on_actionFlipHorizontal_triggered()
  1792. {
  1793. vec2 scale;
  1794. vec2_set(&scale, -1.0f, 1.0f);
  1795. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1796. &scale);
  1797. }
  1798. void OBSBasic::on_actionFlipVertical_triggered()
  1799. {
  1800. vec2 scale;
  1801. vec2_set(&scale, 1.0f, -1.0f);
  1802. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1803. &scale);
  1804. }
  1805. static bool CenterAlignSelectedItems(obs_scene_t scene, obs_sceneitem_t item,
  1806. void *param)
  1807. {
  1808. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  1809. if (!obs_sceneitem_selected(item))
  1810. return true;
  1811. obs_video_info ovi;
  1812. obs_get_video_info(&ovi);
  1813. obs_transform_info itemInfo;
  1814. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  1815. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  1816. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  1817. itemInfo.rot = 0.0f;
  1818. vec2_set(&itemInfo.bounds,
  1819. float(ovi.base_width), float(ovi.base_height));
  1820. itemInfo.bounds_type = boundsType;
  1821. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  1822. obs_sceneitem_set_info(item, &itemInfo);
  1823. UNUSED_PARAMETER(scene);
  1824. return true;
  1825. }
  1826. void OBSBasic::on_actionFitToScreen_triggered()
  1827. {
  1828. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  1829. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1830. &boundsType);
  1831. }
  1832. void OBSBasic::on_actionStretchToScreen_triggered()
  1833. {
  1834. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  1835. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1836. &boundsType);
  1837. }
  1838. void OBSBasic::on_actionCenterToScreen_triggered()
  1839. {
  1840. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1841. {
  1842. vec3 tl, br, itemCenter, screenCenter, offset;
  1843. obs_video_info ovi;
  1844. if (!obs_sceneitem_selected(item))
  1845. return true;
  1846. obs_get_video_info(&ovi);
  1847. vec3_set(&screenCenter, float(ovi.base_width),
  1848. float(ovi.base_height), 0.0f);
  1849. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  1850. GetItemBox(item, tl, br);
  1851. vec3_sub(&itemCenter, &br, &tl);
  1852. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  1853. vec3_add(&itemCenter, &itemCenter, &tl);
  1854. vec3_sub(&offset, &screenCenter, &itemCenter);
  1855. vec3_add(&tl, &tl, &offset);
  1856. SetItemTL(item, tl);
  1857. UNUSED_PARAMETER(scene);
  1858. UNUSED_PARAMETER(param);
  1859. return true;
  1860. };
  1861. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1862. }