window-basic-main.cpp 60 KB

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