window-basic-main.cpp 56 KB

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