window-basic-main.cpp 60 KB

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