window-basic-main.cpp 63 KB

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