window-basic-main.cpp 60 KB

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