window-basic-main.cpp 46 KB

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