1
0

window-basic-main.cpp 59 KB

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